title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Tensorflow tf.add() Function - GeeksforGeeks
04 Mar, 2021 The tf.add() function returns the addition of two tf.Tensor objects element wise. The tf.Tensor object represents the multidimensional array of numbers. Syntax: tf.add( a, b ) Parameters: a: It contains the first tf.Tensor object that is to be added. The value of this parameter can be tf.TensorTypedArray|Array. b: It contains the second tf.Tensor object that is to be added into the first tf.Tensor object. The value of this parameter can be (tf.Tensor|TypedArray|Array). The type of this parameter is same as type of a. Return Value: This function returns the tf.Tensor object. Example 1: Javascript // Importing the tensorflow.js library import * as tf from "@tensorflow/tfjs" // Declare the Tensor arrayconst arr1 = tf.tensor1d([10, 20, 30, 40, 50]);const arr2 = tf.tensor1d([5, 10, 15, 20, 25]); // Use add() function to add// two Tensor objectsarr1.add(arr2).print(); Output: Tensor [15, 30, 45, 60, 75] Example 2: Javascript // Importing the tensorflow.js library import * as tf from "@tensorflow/tfjs" // Declare the Tensor arrayconst arr1 = tf.tensor1d([30, 40, 50]);const arr2 = tf.tensor1d([5, 10, 15, 20, 25]); // Use add() function to add// two Tensor objectsarr1.add(arr2).print(); Output: An error occured on line: 7 Operands could not be broadcast together with shapes 3 and 5. Example 3: Javascript // Importing the tensorflow.js library import * as tf from "@tensorflow/tfjs" // Declare the Tensor arrayconst arr = tf.tensor1d([5, 10, 15, 20, 25]); // Declare a numberconst num = tf.scalar(30); // Use add() function to add// Tensor object and a numberarr.add(num).print(); Output: Tensor [35, 40, 45, 50, 55] Reference: https://js.tensorflow.org/api/latest/#add Tensorflow JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n04 Mar, 2021" }, { "code": null, "e": 26698, "s": 26545, "text": "The tf.add() function returns the addition of two tf.Tensor objects element wise. The tf.Tensor object represents the multidimensional array of numbers." }, { "code": null, "e": 26706, "s": 26698, "text": "Syntax:" }, { "code": null, "e": 26721, "s": 26706, "text": "tf.add( a, b )" }, { "code": null, "e": 26734, "s": 26721, "text": "Parameters: " }, { "code": null, "e": 26859, "s": 26734, "text": "a: It contains the first tf.Tensor object that is to be added. The value of this parameter can be tf.TensorTypedArray|Array." }, { "code": null, "e": 27069, "s": 26859, "text": "b: It contains the second tf.Tensor object that is to be added into the first tf.Tensor object. The value of this parameter can be (tf.Tensor|TypedArray|Array). The type of this parameter is same as type of a." }, { "code": null, "e": 27127, "s": 27069, "text": "Return Value: This function returns the tf.Tensor object." }, { "code": null, "e": 27138, "s": 27127, "text": "Example 1:" }, { "code": null, "e": 27149, "s": 27138, "text": "Javascript" }, { "code": "// Importing the tensorflow.js library import * as tf from \"@tensorflow/tfjs\" // Declare the Tensor arrayconst arr1 = tf.tensor1d([10, 20, 30, 40, 50]);const arr2 = tf.tensor1d([5, 10, 15, 20, 25]); // Use add() function to add// two Tensor objectsarr1.add(arr2).print();", "e": 27423, "s": 27149, "text": null }, { "code": null, "e": 27431, "s": 27423, "text": "Output:" }, { "code": null, "e": 27463, "s": 27431, "text": "Tensor\n [15, 30, 45, 60, 75]" }, { "code": null, "e": 27474, "s": 27463, "text": "Example 2:" }, { "code": null, "e": 27485, "s": 27474, "text": "Javascript" }, { "code": "// Importing the tensorflow.js library import * as tf from \"@tensorflow/tfjs\" // Declare the Tensor arrayconst arr1 = tf.tensor1d([30, 40, 50]);const arr2 = tf.tensor1d([5, 10, 15, 20, 25]); // Use add() function to add// two Tensor objectsarr1.add(arr2).print();", "e": 27751, "s": 27485, "text": null }, { "code": null, "e": 27759, "s": 27751, "text": "Output:" }, { "code": null, "e": 27849, "s": 27759, "text": "An error occured on line: 7\nOperands could not be broadcast together with shapes 3 and 5." }, { "code": null, "e": 27860, "s": 27849, "text": "Example 3:" }, { "code": null, "e": 27871, "s": 27860, "text": "Javascript" }, { "code": "// Importing the tensorflow.js library import * as tf from \"@tensorflow/tfjs\" // Declare the Tensor arrayconst arr = tf.tensor1d([5, 10, 15, 20, 25]); // Declare a numberconst num = tf.scalar(30); // Use add() function to add// Tensor object and a numberarr.add(num).print();", "e": 28150, "s": 27871, "text": null }, { "code": null, "e": 28158, "s": 28150, "text": "Output:" }, { "code": null, "e": 28190, "s": 28158, "text": "Tensor\n [35, 40, 45, 50, 55]" }, { "code": null, "e": 28243, "s": 28190, "text": "Reference: https://js.tensorflow.org/api/latest/#add" }, { "code": null, "e": 28254, "s": 28243, "text": "Tensorflow" }, { "code": null, "e": 28265, "s": 28254, "text": "JavaScript" }, { "code": null, "e": 28282, "s": 28265, "text": "Web Technologies" }, { "code": null, "e": 28380, "s": 28282, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28420, "s": 28380, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28481, "s": 28420, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28522, "s": 28481, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28544, "s": 28522, "text": "JavaScript | Promises" }, { "code": null, "e": 28598, "s": 28544, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28638, "s": 28598, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28671, "s": 28638, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28714, "s": 28671, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28764, "s": 28714, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python - Interconvert Tuple to Byte Integer - GeeksforGeeks
03 Jul, 2020 Sometimes, while working with Python data, we can have a problem in which we need to perform conversion of tuple values, into combined byte and then to integer and vice-versa. This kind of problem can have application in data domains. Let’s discuss certain ways in which this task can be performed. Input : test_tuple = (1, 2, 3, 4, 5)Output : 4328719365 Input : test_int = 4328719365Output : (1, 2, 3, 4, 5) Method #1 : Tuple -> Byte Integer : Using int.from_bytes()The combination of above functions can be used to solve this problem. In this, we perform the task of conversion using internal function from_bytes() and obtain the desired integer value. # Python3 code to demonstrate working of # Interconvert Tuple to Byte Integer# Tuple -> Byte Integer : Using int.from_bytes() # initializing tuplestest_tuple = (6, 8, 3, 2) # printing original tupleprint("The original tuple : " + str(test_tuple)) # Interconvert Tuple to Byte Integer# Tuple -> Byte Integer : Using int.from_bytes()res = int.from_bytes(test_tuple, byteorder ='big') # printing result print("Tuple after conversion : " + str(res)) The original tuple : (6, 8, 3, 2) Tuple after conversion : 101188354 Method #2 : Byte Integer -> Tuple : Using tuple.to_bytes()The combination of above functions can be used to solve this problem. In this, we perform the task of conversion using internal method to_bytes() to obtain desired result. # Python3 code to demonstrate working of # Interconvert Tuple to Byte Integer# Using Byte Integer -> Tuple : Using tuple.to_bytes() # initializing integertest_int = 101188354 # printing original integerprint("The original integer : " + str(test_int)) # Interconvert Tuple to Byte Integer# Using Byte Integer -> Tuple : Using tuple.to_bytes()res = tuple(test_int.to_bytes(4, byteorder ='big')) # printing result print("Integer after conversion : " + str(res)) The original integer : 101188354 Integer after conversion : (6, 8, 3, 2) Python tuple-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n03 Jul, 2020" }, { "code": null, "e": 25836, "s": 25537, "text": "Sometimes, while working with Python data, we can have a problem in which we need to perform conversion of tuple values, into combined byte and then to integer and vice-versa. This kind of problem can have application in data domains. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 25892, "s": 25836, "text": "Input : test_tuple = (1, 2, 3, 4, 5)Output : 4328719365" }, { "code": null, "e": 25946, "s": 25892, "text": "Input : test_int = 4328719365Output : (1, 2, 3, 4, 5)" }, { "code": null, "e": 26192, "s": 25946, "text": "Method #1 : Tuple -> Byte Integer : Using int.from_bytes()The combination of above functions can be used to solve this problem. In this, we perform the task of conversion using internal function from_bytes() and obtain the desired integer value." }, { "code": "# Python3 code to demonstrate working of # Interconvert Tuple to Byte Integer# Tuple -> Byte Integer : Using int.from_bytes() # initializing tuplestest_tuple = (6, 8, 3, 2) # printing original tupleprint(\"The original tuple : \" + str(test_tuple)) # Interconvert Tuple to Byte Integer# Tuple -> Byte Integer : Using int.from_bytes()res = int.from_bytes(test_tuple, byteorder ='big') # printing result print(\"Tuple after conversion : \" + str(res))", "e": 26642, "s": 26192, "text": null }, { "code": null, "e": 26712, "s": 26642, "text": "The original tuple : (6, 8, 3, 2)\nTuple after conversion : 101188354\n" }, { "code": null, "e": 26944, "s": 26714, "text": "Method #2 : Byte Integer -> Tuple : Using tuple.to_bytes()The combination of above functions can be used to solve this problem. In this, we perform the task of conversion using internal method to_bytes() to obtain desired result." }, { "code": "# Python3 code to demonstrate working of # Interconvert Tuple to Byte Integer# Using Byte Integer -> Tuple : Using tuple.to_bytes() # initializing integertest_int = 101188354 # printing original integerprint(\"The original integer : \" + str(test_int)) # Interconvert Tuple to Byte Integer# Using Byte Integer -> Tuple : Using tuple.to_bytes()res = tuple(test_int.to_bytes(4, byteorder ='big')) # printing result print(\"Integer after conversion : \" + str(res))", "e": 27407, "s": 26944, "text": null }, { "code": null, "e": 27481, "s": 27407, "text": "The original integer : 101188354\nInteger after conversion : (6, 8, 3, 2)\n" }, { "code": null, "e": 27503, "s": 27481, "text": "Python tuple-programs" }, { "code": null, "e": 27510, "s": 27503, "text": "Python" }, { "code": null, "e": 27526, "s": 27510, "text": "Python Programs" }, { "code": null, "e": 27624, "s": 27526, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27656, "s": 27624, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27698, "s": 27656, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27740, "s": 27698, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27767, "s": 27740, "text": "Python Classes and Objects" }, { "code": null, "e": 27823, "s": 27767, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27845, "s": 27823, "text": "Defaultdict in Python" }, { "code": null, "e": 27884, "s": 27845, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27930, "s": 27884, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27968, "s": 27930, "text": "Python | Convert a list to dictionary" } ]
DXC Technology Interview Experience - GeeksforGeeks
27 Jul, 2021 DXC Technology Campus Drive was held in the month of July 21 (For the batch of 2022 i.e final year students) for the full-time employees as Associate Professional-Software Engineering. All rounds were held online. ROUND 1: This was an Aptitude based exam with the following sections- Logical Reasoning, Quantitative Aptitude, Verbal Ability, Essay Writing, Computer Programming, and Coding Section(Automata Fix) and its platform was Amcat. Apart from Automata Fix and Essay Writing all other sections were objective type(MCQs) and each section had limited time. Sample papers and preparatory material for this test are available online. Automata Fix consists of 7 questions. These questions are debugging and coding-based questions. These questions were very basic. It was an elimination round and only the students who cleared the test were invited for Technical+HR Round. Candidates were asked to submit their resumes in DXC Format with this test. ROUND 2: This was a mix of Technical and HR interviews. The interviewer asked me few general questions like “Tell me about yourself”, “Short term and long term goal”, “Are you willing to relocate”, “Do you have any gap in education or not”. After that, My interview is solely based on my projects. He asked me few questions related to my projects. At last, he asked me “Do you have any questions for me”. I asked him one question and after answering it my interview got over. Some candidates were also asked to write the code in the editor. The interview was held on the Amcat SmartMeet platform. The result was declared when all interviews were done and I got selected for the role of Associate Professional. Verdict: Selected DXC Technology Marketing Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Amazon Interview Experience for SDE-1 (Off-Campus) 2022 Amazon Interview Experience Amazon Interview Experience for SDE-1 EPAM Interview Experience (Off-Campus) Amazon Interview Experience (Off-Campus) 2022 JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 Amazon Interview Experience for SDE-1 (On-Campus) Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)
[ { "code": null, "e": 26261, "s": 26233, "text": "\n27 Jul, 2021" }, { "code": null, "e": 26446, "s": 26261, "text": "DXC Technology Campus Drive was held in the month of July 21 (For the batch of 2022 i.e final year students) for the full-time employees as Associate Professional-Software Engineering." }, { "code": null, "e": 26475, "s": 26446, "text": "All rounds were held online." }, { "code": null, "e": 26701, "s": 26475, "text": "ROUND 1: This was an Aptitude based exam with the following sections- Logical Reasoning, Quantitative Aptitude, Verbal Ability, Essay Writing, Computer Programming, and Coding Section(Automata Fix) and its platform was Amcat." }, { "code": null, "e": 26898, "s": 26701, "text": "Apart from Automata Fix and Essay Writing all other sections were objective type(MCQs) and each section had limited time. Sample papers and preparatory material for this test are available online." }, { "code": null, "e": 27027, "s": 26898, "text": "Automata Fix consists of 7 questions. These questions are debugging and coding-based questions. These questions were very basic." }, { "code": null, "e": 27135, "s": 27027, "text": "It was an elimination round and only the students who cleared the test were invited for Technical+HR Round." }, { "code": null, "e": 27211, "s": 27135, "text": "Candidates were asked to submit their resumes in DXC Format with this test." }, { "code": null, "e": 27268, "s": 27211, "text": "ROUND 2: This was a mix of Technical and HR interviews. " }, { "code": null, "e": 27454, "s": 27268, "text": "The interviewer asked me few general questions like “Tell me about yourself”, “Short term and long term goal”, “Are you willing to relocate”, “Do you have any gap in education or not”. " }, { "code": null, "e": 27562, "s": 27454, "text": "After that, My interview is solely based on my projects. He asked me few questions related to my projects. " }, { "code": null, "e": 27690, "s": 27562, "text": "At last, he asked me “Do you have any questions for me”. I asked him one question and after answering it my interview got over." }, { "code": null, "e": 27811, "s": 27690, "text": "Some candidates were also asked to write the code in the editor. The interview was held on the Amcat SmartMeet platform." }, { "code": null, "e": 27924, "s": 27811, "text": "The result was declared when all interviews were done and I got selected for the role of Associate Professional." }, { "code": null, "e": 27942, "s": 27924, "text": "Verdict: Selected" }, { "code": null, "e": 27957, "s": 27942, "text": "DXC Technology" }, { "code": null, "e": 27967, "s": 27957, "text": "Marketing" }, { "code": null, "e": 27989, "s": 27967, "text": "Interview Experiences" }, { "code": null, "e": 28087, "s": 27989, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28138, "s": 28087, "text": "Amazon Interview Experience for SDE-1 (Off-Campus)" }, { "code": null, "e": 28180, "s": 28138, "text": "Amazon AWS Interview Experience for SDE-1" }, { "code": null, "e": 28236, "s": 28180, "text": "Amazon Interview Experience for SDE-1 (Off-Campus) 2022" }, { "code": null, "e": 28264, "s": 28236, "text": "Amazon Interview Experience" }, { "code": null, "e": 28302, "s": 28264, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 28341, "s": 28302, "text": "EPAM Interview Experience (Off-Campus)" }, { "code": null, "e": 28387, "s": 28341, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 28459, "s": 28387, "text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021" }, { "code": null, "e": 28509, "s": 28459, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" } ]
Shuffle Elements of ArrayList in Java - GeeksforGeeks
07 Jan, 2021 Shuffling means changing the positions of ArrayList elements randomly. After shuffling, they will be in different order. Following is the example of Shuffling ArrayList elements. Ways to shuffle elements of ArrayList: Using Random classUsing Collections.shuffle() Using Random class Using Collections.shuffle() Method 1: Using Random class In this method we will be going to shuffle ArrayList element using Random class to generate random index. And java collections.swap() method to swap ArrayList elements. And one more algorithm we will be going to use that is Fisher–Yates shuffle. Code: Java // Java program to demonstrate shuffling of arraylist// elements Using Random class import java.util.*;class ArraylistShuffle { public static void main(String args[]) { // creating // ArrayList ArrayList<Integer> al = new ArrayList<Integer>(); // adding object in ArrayList al.add(10); al.add(20); al.add(30); al.add(40); al.add(50); al.add(60); al.add(70); al.add(80); System.out.println("Before shuffling Arraylist:"); // getting Iterator // from arraylist to // traverse elements Iterator itr = al.iterator(); while (itr.hasNext()) { System.out.print(itr.next() + " "); } System.out.println(""); Random r1 = new Random(); for (int i = al.size() - 1; i >= 1; i--) { // swapping current index value // with random index value Collections.swap(al, i, r1.nextInt(i + 1)); } System.out.println("After shuffling Arraylist:"); itr = al.iterator(); while (itr.hasNext()) { System.out.print(itr.next() + " "); } }} Before shuffling Arraylist: 10 20 30 40 50 60 70 80 After shuffling Arraylist: 10 60 30 20 50 80 40 70 Method 2: Using Collections.shuffle() Shuffle ArrayList Elements by using Collections.shuffle(). Java // Java program to demonstrate shuffling// ArrayList elements using Collections.shuffle() import java.util.*;class ArraylistShuffle { public static void main(String args[]) { // creating ArrayList ArrayList<String> al = new ArrayList<String>(); // adding object in ArrayList al.add("C"); al.add("C++"); al.add("Java"); al.add("Python"); al.add("PHP"); al.add("Javascript"); System.out.println("Before shuffling Arraylist:"); // getting Iterator // from arraylist to // traverse elements Iterator itr = al.iterator(); while (itr.hasNext()) { System.out.print(itr.next() + " "); } System.out.println(""); Collections.shuffle(al); System.out.println("After shuffling Arraylist:"); itr = al.iterator(); while (itr.hasNext()) { System.out.print(itr.next() + " "); } }} Before shuffling Arraylist: C C++ Java Python PHP Javascript After shuffling Arraylist: PHP Java C++ C Javascript Python Java-ArrayList Java-Collections Picked Java Java Programs Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file 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? Program to print ASCII Value of a character
[ { "code": null, "e": 25225, "s": 25197, "text": "\n07 Jan, 2021" }, { "code": null, "e": 25347, "s": 25225, "text": "Shuffling means changing the positions of ArrayList elements randomly. After shuffling, they will be in different order. " }, { "code": null, "e": 25405, "s": 25347, "text": "Following is the example of Shuffling ArrayList elements." }, { "code": null, "e": 25444, "s": 25405, "text": "Ways to shuffle elements of ArrayList:" }, { "code": null, "e": 25490, "s": 25444, "text": "Using Random classUsing Collections.shuffle()" }, { "code": null, "e": 25509, "s": 25490, "text": "Using Random class" }, { "code": null, "e": 25537, "s": 25509, "text": "Using Collections.shuffle()" }, { "code": null, "e": 25566, "s": 25537, "text": "Method 1: Using Random class" }, { "code": null, "e": 25672, "s": 25566, "text": "In this method we will be going to shuffle ArrayList element using Random class to generate random index." }, { "code": null, "e": 25735, "s": 25672, "text": "And java collections.swap() method to swap ArrayList elements." }, { "code": null, "e": 25812, "s": 25735, "text": "And one more algorithm we will be going to use that is Fisher–Yates shuffle." }, { "code": null, "e": 25818, "s": 25812, "text": "Code:" }, { "code": null, "e": 25823, "s": 25818, "text": "Java" }, { "code": "// Java program to demonstrate shuffling of arraylist// elements Using Random class import java.util.*;class ArraylistShuffle { public static void main(String args[]) { // creating // ArrayList ArrayList<Integer> al = new ArrayList<Integer>(); // adding object in ArrayList al.add(10); al.add(20); al.add(30); al.add(40); al.add(50); al.add(60); al.add(70); al.add(80); System.out.println(\"Before shuffling Arraylist:\"); // getting Iterator // from arraylist to // traverse elements Iterator itr = al.iterator(); while (itr.hasNext()) { System.out.print(itr.next() + \" \"); } System.out.println(\"\"); Random r1 = new Random(); for (int i = al.size() - 1; i >= 1; i--) { // swapping current index value // with random index value Collections.swap(al, i, r1.nextInt(i + 1)); } System.out.println(\"After shuffling Arraylist:\"); itr = al.iterator(); while (itr.hasNext()) { System.out.print(itr.next() + \" \"); } }}", "e": 27006, "s": 25823, "text": null }, { "code": null, "e": 27111, "s": 27006, "text": "Before shuffling Arraylist:\n10 20 30 40 50 60 70 80 \nAfter shuffling Arraylist:\n10 60 30 20 50 80 40 70 " }, { "code": null, "e": 27149, "s": 27111, "text": "Method 2: Using Collections.shuffle()" }, { "code": null, "e": 27208, "s": 27149, "text": "Shuffle ArrayList Elements by using Collections.shuffle()." }, { "code": null, "e": 27213, "s": 27208, "text": "Java" }, { "code": "// Java program to demonstrate shuffling// ArrayList elements using Collections.shuffle() import java.util.*;class ArraylistShuffle { public static void main(String args[]) { // creating ArrayList ArrayList<String> al = new ArrayList<String>(); // adding object in ArrayList al.add(\"C\"); al.add(\"C++\"); al.add(\"Java\"); al.add(\"Python\"); al.add(\"PHP\"); al.add(\"Javascript\"); System.out.println(\"Before shuffling Arraylist:\"); // getting Iterator // from arraylist to // traverse elements Iterator itr = al.iterator(); while (itr.hasNext()) { System.out.print(itr.next() + \" \"); } System.out.println(\"\"); Collections.shuffle(al); System.out.println(\"After shuffling Arraylist:\"); itr = al.iterator(); while (itr.hasNext()) { System.out.print(itr.next() + \" \"); } }}", "e": 28181, "s": 27213, "text": null }, { "code": null, "e": 28304, "s": 28181, "text": "Before shuffling Arraylist:\nC C++ Java Python PHP Javascript \nAfter shuffling Arraylist:\nPHP Java C++ C Javascript Python " }, { "code": null, "e": 28319, "s": 28304, "text": "Java-ArrayList" }, { "code": null, "e": 28336, "s": 28319, "text": "Java-Collections" }, { "code": null, "e": 28343, "s": 28336, "text": "Picked" }, { "code": null, "e": 28348, "s": 28343, "text": "Java" }, { "code": null, "e": 28362, "s": 28348, "text": "Java Programs" }, { "code": null, "e": 28367, "s": 28362, "text": "Java" }, { "code": null, "e": 28384, "s": 28367, "text": "Java-Collections" }, { "code": null, "e": 28482, "s": 28384, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28497, "s": 28482, "text": "Stream In Java" }, { "code": null, "e": 28518, "s": 28497, "text": "Constructors in Java" }, { "code": null, "e": 28537, "s": 28518, "text": "Exceptions in Java" }, { "code": null, "e": 28567, "s": 28537, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28613, "s": 28567, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28639, "s": 28613, "text": "Java Programming Examples" }, { "code": null, "e": 28673, "s": 28639, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 28720, "s": 28673, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 28752, "s": 28720, "text": "How to Iterate HashMap in Java?" } ]
Multiple Inheritance in Python - GeeksforGeeks
22 Feb, 2022 Inheritance is the mechanism to achieve the re-usability of code as one class(child class) can derive the properties of another class(parent class). It also provides transitivity ie. if class C inherits from P then all the sub-classes of C would also inherit from P. Multiple Inheritance When a class is derived from more than one base class it is called multiple Inheritance. The derived class inherits all the features of the base case. Syntax: Class Base1: Body of the class Class Base2: Body of the class Class Derived(Base1, Base2): Body of the class In the coming section, we will see the problem faced during multiple inheritance and how to tackle it with the help of examples. The Diamond Problem It refers to an ambiguity that arises when two classes Class2 and Class3 inherit from a superclass Class1 and class Class4 inherits from both Class2 and Class3. If there is a method “m” which is an overridden method in one of Class2 and Class3 or both then the ambiguity arises which of the method “m” Class4 should inherit. When the method is overridden in both classes Python3 # Python Program to depict multiple inheritance# when method is overridden in both classes class Class1: def m(self): print("In Class1") class Class2(Class1): def m(self): print("In Class2") class Class3(Class1): def m(self): print("In Class3") class Class4(Class2, Class3): pass obj = Class4()obj.m() Output: In Class2 Note: When you call obj.m() (m on the instance of Class4) the output is In Class2. If Class4 is declared as Class4(Class3, Class2) then the output of obj.m() will be In Class3. When the method is overridden in one of the classes Python3 # Python Program to depict multiple inheritance# when method is overridden in one of the classes class Class1: def m(self): print("In Class1") class Class2(Class1): pass class Class3(Class1): def m(self): print("In Class3") class Class4(Class2, Class3): pass obj = Class4()obj.m() Output: In Class3 When every class defines the same method Python3 # Python Program to depict multiple inheritance# when every class defines the same method class Class1: def m(self): print("In Class1") class Class2(Class1): def m(self): print("In Class2") class Class3(Class1): def m(self): print("In Class3") class Class4(Class2, Class3): def m(self): print("In Class4") obj = Class4()obj.m() Class2.m(obj)Class3.m(obj)Class1.m(obj) Output: In Class4 In Class2 In Class3 In Class1 The output of the method obj.m() in the above code is In Class4. The method “m” of Class4 is executed. To execute the method “m” of the other classes it can be done using the class names.Now, to call the method m for Class1, Class2, Class3 directly from the method “m” of the Class4 see the below example Python3 # Python Program to depict multiple inheritance# when we try to call the method m for Class1,# Class2, Class3 from the method m of Class4 class Class1: def m(self): print("In Class1") class Class2(Class1): def m(self): print("In Class2") class Class3(Class1): def m(self): print("In Class3") class Class4(Class2, Class3): def m(self): print("In Class4") Class2.m(self) Class3.m(self) Class1.m(self) obj = Class4()obj.m() Output: In Class4 In Class2 In Class3 In Class1 To call “m” of Class1 from both “m” of Class2 and “m” of Class3 instead of Class4 is shown below: Python3 # Python Program to depict multiple inheritance# when we try to call m of Class1 from both m of# Class2 and m of Class3 class Class1: def m(self): print("In Class1") class Class2(Class1): def m(self): print("In Class2") Class1.m(self) class Class3(Class1): def m(self): print("In Class3") Class1.m(self) class Class4(Class2, Class3): def m(self): print("In Class4") Class2.m(self) Class3.m(self) obj = Class4()obj.m() Output: In Class4 In Class2 In Class1 In Class3 In Class1 The output of the above code has one problem associated with it, the method m of Class1 is called twice. Python provides a solution to the above problem with the help of the super() function. Let’s see how it works. The super Function Python3 # Python program to demonstrate# super() class Class1: def m(self): print("In Class1") class Class2(Class1): def m(self): print("In Class2") super().m() class Class3(Class1): def m(self): print("In Class3") super().m() class Class4(Class2, Class3): def m(self): print("In Class4") super().m() obj = Class4()obj.m() Output: In Class4 In Class2 In Class3 In Class1 Super() is generally used with the __init__ function when the instances are initialized. The super function comes to a conclusion, on which method to call with the help of the method resolution order (MRO). In Python, every class whether built-in or user-defined is derived from the object class and all the objects are instances of the class object. Hence, the object class is the base class for all the other classes.In the case of multiple inheritance, a given attribute is first searched in the current class if it’s not found then it’s searched in the parent classes. The parent classes are searched in a left-right fashion and each class is searched once.If we see the above example then the order of search for the attributes will be Derived, Base1, Base2, object. The order that is followed is known as a linearization of the class Derived and this order is found out using a set of rules called Method Resolution Order (MRO).To view the MRO of a class: Use the mro() method, it returns a list Eg. Class4.mro() Use the _mro_ attribute, it returns a tuple Eg. Class4.__mro__ Example: Python3 # Python program to demonstrate# super() class Class1: def m(self): print("In Class1") class Class2(Class1): def m(self): print("In Class2") super().m() class Class3(Class1): def m(self): print("In Class3") super().m() class Class4(Class2, Class3): def m(self): print("In Class4") super().m() print(Class4.mro()) #This will print listprint(Class4.__mro__) #This will print tuple Output: [<class ‘__main__.Class4’>, <class ‘__main__.Class2’>, <class ‘__main__.Class3’>, <class ‘__main__.Class1’>, <class ‘object’>] (<class ‘__main__.Class4’>, <class ‘__main__.Class2’>, <class ‘__main__.Class3’>, <class ‘__main__.Class1’>, <class ‘object’>) anushkalaharia trdeshmukh2012 python-inheritance Python-OOP Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25375, "s": 25347, "text": "\n22 Feb, 2022" }, { "code": null, "e": 25643, "s": 25375, "text": "Inheritance is the mechanism to achieve the re-usability of code as one class(child class) can derive the properties of another class(parent class). It also provides transitivity ie. if class C inherits from P then all the sub-classes of C would also inherit from P. " }, { "code": null, "e": 25816, "s": 25643, "text": "Multiple Inheritance When a class is derived from more than one base class it is called multiple Inheritance. The derived class inherits all the features of the base case. " }, { "code": null, "e": 25955, "s": 25818, "text": "Syntax:\n\nClass Base1:\n Body of the class\n\nClass Base2:\n Body of the class\n\nClass Derived(Base1, Base2):\n Body of the class" }, { "code": null, "e": 26085, "s": 25955, "text": "In the coming section, we will see the problem faced during multiple inheritance and how to tackle it with the help of examples. " }, { "code": null, "e": 26106, "s": 26085, "text": "The Diamond Problem " }, { "code": null, "e": 26432, "s": 26106, "text": "It refers to an ambiguity that arises when two classes Class2 and Class3 inherit from a superclass Class1 and class Class4 inherits from both Class2 and Class3. If there is a method “m” which is an overridden method in one of Class2 and Class3 or both then the ambiguity arises which of the method “m” Class4 should inherit. " }, { "code": null, "e": 26479, "s": 26432, "text": "When the method is overridden in both classes " }, { "code": null, "e": 26487, "s": 26479, "text": "Python3" }, { "code": "# Python Program to depict multiple inheritance# when method is overridden in both classes class Class1: def m(self): print(\"In Class1\") class Class2(Class1): def m(self): print(\"In Class2\") class Class3(Class1): def m(self): print(\"In Class3\") class Class4(Class2, Class3): pass obj = Class4()obj.m()", "e": 26842, "s": 26487, "text": null }, { "code": null, "e": 26850, "s": 26842, "text": "Output:" }, { "code": null, "e": 26860, "s": 26850, "text": "In Class2" }, { "code": null, "e": 27038, "s": 26860, "text": "Note: When you call obj.m() (m on the instance of Class4) the output is In Class2. If Class4 is declared as Class4(Class3, Class2) then the output of obj.m() will be In Class3. " }, { "code": null, "e": 27091, "s": 27038, "text": "When the method is overridden in one of the classes " }, { "code": null, "e": 27099, "s": 27091, "text": "Python3" }, { "code": "# Python Program to depict multiple inheritance# when method is overridden in one of the classes class Class1: def m(self): print(\"In Class1\") class Class2(Class1): pass class Class3(Class1): def m(self): print(\"In Class3\") class Class4(Class2, Class3): pass obj = Class4()obj.m()", "e": 27426, "s": 27099, "text": null }, { "code": null, "e": 27434, "s": 27426, "text": "Output:" }, { "code": null, "e": 27444, "s": 27434, "text": "In Class3" }, { "code": null, "e": 27485, "s": 27444, "text": "When every class defines the same method" }, { "code": null, "e": 27493, "s": 27485, "text": "Python3" }, { "code": "# Python Program to depict multiple inheritance# when every class defines the same method class Class1: def m(self): print(\"In Class1\") class Class2(Class1): def m(self): print(\"In Class2\") class Class3(Class1): def m(self): print(\"In Class3\") class Class4(Class2, Class3): def m(self): print(\"In Class4\") obj = Class4()obj.m() Class2.m(obj)Class3.m(obj)Class1.m(obj)", "e": 27918, "s": 27493, "text": null }, { "code": null, "e": 27926, "s": 27918, "text": "Output:" }, { "code": null, "e": 27966, "s": 27926, "text": "In Class4\nIn Class2\nIn Class3\nIn Class1" }, { "code": null, "e": 28272, "s": 27966, "text": "The output of the method obj.m() in the above code is In Class4. The method “m” of Class4 is executed. To execute the method “m” of the other classes it can be done using the class names.Now, to call the method m for Class1, Class2, Class3 directly from the method “m” of the Class4 see the below example " }, { "code": null, "e": 28280, "s": 28272, "text": "Python3" }, { "code": "# Python Program to depict multiple inheritance# when we try to call the method m for Class1,# Class2, Class3 from the method m of Class4 class Class1: def m(self): print(\"In Class1\") class Class2(Class1): def m(self): print(\"In Class2\") class Class3(Class1): def m(self): print(\"In Class3\") class Class4(Class2, Class3): def m(self): print(\"In Class4\") Class2.m(self) Class3.m(self) Class1.m(self) obj = Class4()obj.m()", "e": 28779, "s": 28280, "text": null }, { "code": null, "e": 28787, "s": 28779, "text": "Output:" }, { "code": null, "e": 28827, "s": 28787, "text": "In Class4\nIn Class2\nIn Class3\nIn Class1" }, { "code": null, "e": 28925, "s": 28827, "text": "To call “m” of Class1 from both “m” of Class2 and “m” of Class3 instead of Class4 is shown below:" }, { "code": null, "e": 28933, "s": 28925, "text": "Python3" }, { "code": "# Python Program to depict multiple inheritance# when we try to call m of Class1 from both m of# Class2 and m of Class3 class Class1: def m(self): print(\"In Class1\") class Class2(Class1): def m(self): print(\"In Class2\") Class1.m(self) class Class3(Class1): def m(self): print(\"In Class3\") Class1.m(self) class Class4(Class2, Class3): def m(self): print(\"In Class4\") Class2.m(self) Class3.m(self) obj = Class4()obj.m()", "e": 29439, "s": 28933, "text": null }, { "code": null, "e": 29447, "s": 29439, "text": "Output:" }, { "code": null, "e": 29497, "s": 29447, "text": "In Class4\nIn Class2\nIn Class1\nIn Class3\nIn Class1" }, { "code": null, "e": 29714, "s": 29497, "text": "The output of the above code has one problem associated with it, the method m of Class1 is called twice. Python provides a solution to the above problem with the help of the super() function. Let’s see how it works. " }, { "code": null, "e": 29734, "s": 29714, "text": "The super Function " }, { "code": null, "e": 29742, "s": 29734, "text": "Python3" }, { "code": "# Python program to demonstrate# super() class Class1: def m(self): print(\"In Class1\") class Class2(Class1): def m(self): print(\"In Class2\") super().m() class Class3(Class1): def m(self): print(\"In Class3\") super().m() class Class4(Class2, Class3): def m(self): print(\"In Class4\") super().m() obj = Class4()obj.m()", "e": 30125, "s": 29742, "text": null }, { "code": null, "e": 30133, "s": 30125, "text": "Output:" }, { "code": null, "e": 30173, "s": 30133, "text": "In Class4\nIn Class2\nIn Class3\nIn Class1" }, { "code": null, "e": 30381, "s": 30173, "text": "Super() is generally used with the __init__ function when the instances are initialized. The super function comes to a conclusion, on which method to call with the help of the method resolution order (MRO). " }, { "code": null, "e": 31138, "s": 30381, "text": "In Python, every class whether built-in or user-defined is derived from the object class and all the objects are instances of the class object. Hence, the object class is the base class for all the other classes.In the case of multiple inheritance, a given attribute is first searched in the current class if it’s not found then it’s searched in the parent classes. The parent classes are searched in a left-right fashion and each class is searched once.If we see the above example then the order of search for the attributes will be Derived, Base1, Base2, object. The order that is followed is known as a linearization of the class Derived and this order is found out using a set of rules called Method Resolution Order (MRO).To view the MRO of a class: " }, { "code": null, "e": 31195, "s": 31138, "text": "Use the mro() method, it returns a list Eg. Class4.mro()" }, { "code": null, "e": 31260, "s": 31195, "text": "Use the _mro_ attribute, it returns a tuple Eg. Class4.__mro__ " }, { "code": null, "e": 31270, "s": 31260, "text": "Example: " }, { "code": null, "e": 31278, "s": 31270, "text": "Python3" }, { "code": "# Python program to demonstrate# super() class Class1: def m(self): print(\"In Class1\") class Class2(Class1): def m(self): print(\"In Class2\") super().m() class Class3(Class1): def m(self): print(\"In Class3\") super().m() class Class4(Class2, Class3): def m(self): print(\"In Class4\") super().m() print(Class4.mro()) #This will print listprint(Class4.__mro__) #This will print tuple", "e": 31740, "s": 31278, "text": null }, { "code": null, "e": 31748, "s": 31740, "text": "Output:" }, { "code": null, "e": 32004, "s": 31748, "text": "[<class ‘__main__.Class4’>, <class ‘__main__.Class2’>, <class ‘__main__.Class3’>, <class ‘__main__.Class1’>, <class ‘object’>] (<class ‘__main__.Class4’>, <class ‘__main__.Class2’>, <class ‘__main__.Class3’>, <class ‘__main__.Class1’>, <class ‘object’>) " }, { "code": null, "e": 32019, "s": 32004, "text": "anushkalaharia" }, { "code": null, "e": 32034, "s": 32019, "text": "trdeshmukh2012" }, { "code": null, "e": 32053, "s": 32034, "text": "python-inheritance" }, { "code": null, "e": 32064, "s": 32053, "text": "Python-OOP" }, { "code": null, "e": 32071, "s": 32064, "text": "Python" }, { "code": null, "e": 32169, "s": 32071, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32187, "s": 32169, "text": "Python Dictionary" }, { "code": null, "e": 32222, "s": 32187, "text": "Read a file line by line in Python" }, { "code": null, "e": 32254, "s": 32222, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32276, "s": 32254, "text": "Enumerate() in Python" }, { "code": null, "e": 32318, "s": 32276, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 32348, "s": 32318, "text": "Iterate over a list in Python" }, { "code": null, "e": 32374, "s": 32348, "text": "Python String | replace()" }, { "code": null, "e": 32403, "s": 32374, "text": "*args and **kwargs in Python" }, { "code": null, "e": 32447, "s": 32403, "text": "Reading and Writing to text files in Python" } ]
Print BST elements in given range | Practice | GeeksforGeeks
Given a Binary Search Tree and a range [low, high]. Find all the numbers in the BST that lie in the given range. Note: Element greater than or equal to root go to the right side. Example 1: Input: 17 / \ 4 18 / \ 2 9 l = 4, h = 24 Output: 4 9 17 18 Example 2: Input: 16 / \ 7 20 / \ 1 10 l = 13, h = 23 Output: 16 20 Your Task: You don't need to read input or print anything. Your task is to complete the function printNearNodes() which takes the root Node of the BST and the range elements low and high as inputs and returns an array that contains the BST elements in the given range low to high (inclusive) in non-decreasing order. Expected Time Complexity: O(N). Expected Auxiliary Space: O(Height of the BST). Constraints: 1 ≤ Number of nodes ≤ 104 1 ≤ l ≤ h ≤ 105 0 sparhibsp20182 days ago simple c++ solution using another function void fun(Node *root,int low,int high,vector<int> &v) { if(!root) return ; fun(root->left,low,high,v); if(root->data >= low && root->data <= high ) v.push_back(root->data); fun(root->right,low,high,v); } vector<int> printNearNodes(Node *root, int low, int high) { vector<int> v; fun(root,low,high,v); return v; } 0 kuldeepy104593 weeks ago void inorder(Node * root ,int low ,int high,vector<int>&ans){ if(root==NULL){ return; } inorder(root->left,low,high,ans); if(root->data>=low&&root->data<=high){ ans.push_back(root->data); } inorder(root->right,low,high,ans); } vector<int> printNearNodes(Node *root, int low, int high) { //code here vector<int>ans; inorder(root,low,high,ans); return ans; } 0 aryankhatana351 month ago C++ sol void inorder(Node *root, vector<int> &a){ if(root==NULL){ return; } inorder(root->left,a); a.push_back(root->data); inorder(root->right,a); } vector<int> printNearNodes(Node *root, int low, int high) { //code here vector<int> ans; inorder(root,ans); vector<int>temp ; for(int i=0;i<ans.size();i++){ if(ans[i]>=low && ans[i]<=high){ temp.push_back(ans[i]); } } return temp; } 0 chhitizgoyal1 month ago Java Solution. public static ArrayList<Integer> printNearNodes(Node root,int low,int high) { ArrayList<Integer> list = new ArrayList<>(); if(root==null){ return list; } if(root.data>=low && root.data<=high){ list.add(root.data); } list.addAll(printNearNodes(root.left, low, high)); list.addAll(printNearNodes(root.right, low, high)); Collections.sort(list); return list; } +1 rohanyt742 months ago class Solution { public: void inorder(Node*root,vector<int>&v){ if(root==NULL) return; inorder(root->left,v); v.push_back(root->data); inorder(root->right,v); } vector<int> printNearNodes(Node *root, int low, int high) { //code here vector<int>res; vector<int>res1; inorder(root,res); for(int i=0;i<res.size();i++){ if(res[i]>=low and res[i]<=high) res1.push_back(res[i]); } return res1; }}; +1 sarthakjagetiya10012 months ago Total Time Taken: 0.2/1.4 C++ void check(Node* root, int low, int high, vector<int> &ans){ if(root==NULL){ return; } if((root->data >= low) && (root->data <= high)){ ans.push_back(root->data); } check(root->left, low, high, ans); check(root->right, low, high, ans); } vector<int> printNearNodes(Node *root, int low, int high) { //code here vector<int> ans; check(root, low, high, ans); sort(ans.begin(), ans.end()); return ans; } 0 patildhiren442 months ago // Java - 1.4 static ArrayList<Integer> al = new ArrayList<Integer>(); static void util(Node root, int low, int high){ if(root==null){ return ; } util(root.left, low, high); if(low<=root.data && high>=root.data){ al.add(root.data); } util(root.right, low, high); } public static ArrayList<Integer> printNearNodes(Node root,int low,int high) { // code here. al = new ArrayList<>(); util(root,low,high); return al; } +1 forcer3 months ago void solve(Node *root,vector<int>&v,int l,int h) { if(!root) return; solve(root->left,v,l,h); if(root->data>=l&&root->data<=h) v.push_back(root->data); solve(root->right,v,l,h); } vector<int> printNearNodes(Node *root, int low, int high) { //code here vector<int>v; solve(root,v,low,high); return v; } +1 shyamprakash8073 months ago Simple Python SOlution : Time Taken : 0.8/2.7 class Solution: def printNearNodes(self, root, low, high): ans = [] self.find(root, low, high, ans) ans.sort() return ans def find(self, root, low, high, ans): if root==None: return if low<=root.data<=high: ans.append(root.data) if low <= root.data and high <= root.data: self.find(root.left,low, high, ans) elif low >= root.data and high >= root.data: self.find(root.right, low, high, ans) else: self.find(root.left, low, high, ans) self.find(root.right, low, high, ans) 0 haritasboy12053 months ago C++ || Recursive Solution void solve(Node* root, int low, int high, vector<int> &ans) { if(root == NULL) return; solve(root->left,low,high,ans); if(root->data >= low && root->data <= high) ans.push_back(root->data); solve(root->right,low,high,ans); } vector<int> printNearNodes(Node *root, int low, int high) { //code here vector<int> ans; solve(root,low,high,ans); return ans; } 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": 417, "s": 238, "text": "Given a Binary Search Tree and a range [low, high]. Find all the numbers in the BST that lie in the given range.\nNote: Element greater than or equal to root go to the right side." }, { "code": null, "e": 428, "s": 417, "text": "Example 1:" }, { "code": null, "e": 522, "s": 428, "text": "Input:\n 17\n / \\\n 4 18\n / \\\n 2 9 \nl = 4, h = 24\nOutput: 4 9 17 18 \n" }, { "code": null, "e": 533, "s": 522, "text": "Example 2:" }, { "code": null, "e": 623, "s": 533, "text": "Input:\n 16\n / \\\n 7 20\n / \\\n 1 10\nl = 13, h = 23\nOutput: 16 20 \n" }, { "code": null, "e": 940, "s": 623, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function printNearNodes() which takes the root Node of the BST and the range elements low and high as inputs and returns an array that contains the BST elements in the given range low to high (inclusive) in non-decreasing order." }, { "code": null, "e": 1020, "s": 940, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(Height of the BST)." }, { "code": null, "e": 1075, "s": 1020, "text": "Constraints:\n1 ≤ Number of nodes ≤ 104\n1 ≤ l ≤ h ≤ 105" }, { "code": null, "e": 1077, "s": 1075, "text": "0" }, { "code": null, "e": 1101, "s": 1077, "text": "sparhibsp20182 days ago" }, { "code": null, "e": 1144, "s": 1101, "text": "simple c++ solution using another function" }, { "code": null, "e": 1528, "s": 1146, "text": "void fun(Node *root,int low,int high,vector<int> &v) { if(!root) return ; fun(root->left,low,high,v); if(root->data >= low && root->data <= high ) v.push_back(root->data); fun(root->right,low,high,v); } vector<int> printNearNodes(Node *root, int low, int high) { vector<int> v; fun(root,low,high,v); return v; }" }, { "code": null, "e": 1532, "s": 1530, "text": "0" }, { "code": null, "e": 1557, "s": 1532, "text": "kuldeepy104593 weeks ago" }, { "code": null, "e": 2020, "s": 1557, "text": " void inorder(Node * root ,int low ,int high,vector<int>&ans){ if(root==NULL){ return; } inorder(root->left,low,high,ans); if(root->data>=low&&root->data<=high){ ans.push_back(root->data); } inorder(root->right,low,high,ans); } vector<int> printNearNodes(Node *root, int low, int high) { //code here vector<int>ans; inorder(root,low,high,ans); return ans; }" }, { "code": null, "e": 2022, "s": 2020, "text": "0" }, { "code": null, "e": 2048, "s": 2022, "text": "aryankhatana351 month ago" }, { "code": null, "e": 2056, "s": 2048, "text": "C++ sol" }, { "code": null, "e": 2551, "s": 2056, "text": " void inorder(Node *root, vector<int> &a){ if(root==NULL){ return; } inorder(root->left,a); a.push_back(root->data); inorder(root->right,a); } vector<int> printNearNodes(Node *root, int low, int high) { //code here vector<int> ans; inorder(root,ans); vector<int>temp ; for(int i=0;i<ans.size();i++){ if(ans[i]>=low && ans[i]<=high){ temp.push_back(ans[i]); } } return temp; }" }, { "code": null, "e": 2553, "s": 2551, "text": "0" }, { "code": null, "e": 2577, "s": 2553, "text": "chhitizgoyal1 month ago" }, { "code": null, "e": 2592, "s": 2577, "text": "Java Solution." }, { "code": null, "e": 3027, "s": 2592, "text": " public static ArrayList<Integer> printNearNodes(Node root,int low,int high) { ArrayList<Integer> list = new ArrayList<>(); if(root==null){ return list; } if(root.data>=low && root.data<=high){ list.add(root.data); } list.addAll(printNearNodes(root.left, low, high)); list.addAll(printNearNodes(root.right, low, high)); Collections.sort(list); return list; }" }, { "code": null, "e": 3030, "s": 3027, "text": "+1" }, { "code": null, "e": 3052, "s": 3030, "text": "rohanyt742 months ago" }, { "code": null, "e": 3535, "s": 3052, "text": "class Solution { public: void inorder(Node*root,vector<int>&v){ if(root==NULL) return; inorder(root->left,v); v.push_back(root->data); inorder(root->right,v); } vector<int> printNearNodes(Node *root, int low, int high) { //code here vector<int>res; vector<int>res1; inorder(root,res); for(int i=0;i<res.size();i++){ if(res[i]>=low and res[i]<=high) res1.push_back(res[i]); } return res1; }};" }, { "code": null, "e": 3538, "s": 3535, "text": "+1" }, { "code": null, "e": 3570, "s": 3538, "text": "sarthakjagetiya10012 months ago" }, { "code": null, "e": 3597, "s": 3570, "text": "Total Time Taken: 0.2/1.4" }, { "code": null, "e": 3601, "s": 3597, "text": "C++" }, { "code": null, "e": 4127, "s": 3601, "text": "void check(Node* root, int low, int high, vector<int> &ans){\n if(root==NULL){\n return;\n }\n if((root->data >= low) && (root->data <= high)){\n ans.push_back(root->data);\n }\n check(root->left, low, high, ans);\n check(root->right, low, high, ans);\n }\n vector<int> printNearNodes(Node *root, int low, int high) {\n //code here \n vector<int> ans;\n check(root, low, high, ans);\n sort(ans.begin(), ans.end());\n return ans;\n }" }, { "code": null, "e": 4129, "s": 4127, "text": "0" }, { "code": null, "e": 4155, "s": 4129, "text": "patildhiren442 months ago" }, { "code": null, "e": 4169, "s": 4155, "text": "// Java - 1.4" }, { "code": null, "e": 4724, "s": 4169, "text": "static ArrayList<Integer> al = new ArrayList<Integer>();\n \n static void util(Node root, int low, int high){\n if(root==null){\n return ;\n }\n \n util(root.left, low, high);\n \n if(low<=root.data && high>=root.data){\n al.add(root.data);\n }\n \n util(root.right, low, high);\n }\n \n\tpublic static ArrayList<Integer> printNearNodes(Node root,int low,int high) {\n // code here.\n al = new ArrayList<>();\n util(root,low,high);\n return al;\n }" }, { "code": null, "e": 4727, "s": 4724, "text": "+1" }, { "code": null, "e": 4746, "s": 4727, "text": "forcer3 months ago" }, { "code": null, "e": 5102, "s": 4746, "text": "void solve(Node *root,vector<int>&v,int l,int h) { if(!root) return; solve(root->left,v,l,h); if(root->data>=l&&root->data<=h) v.push_back(root->data); solve(root->right,v,l,h); } vector<int> printNearNodes(Node *root, int low, int high) { //code here vector<int>v; solve(root,v,low,high); return v; }" }, { "code": null, "e": 5105, "s": 5102, "text": "+1" }, { "code": null, "e": 5133, "s": 5105, "text": "shyamprakash8073 months ago" }, { "code": null, "e": 5158, "s": 5133, "text": "Simple Python SOlution :" }, { "code": null, "e": 5179, "s": 5158, "text": "Time Taken : 0.8/2.7" }, { "code": null, "e": 5774, "s": 5181, "text": "class Solution: def printNearNodes(self, root, low, high): ans = [] self.find(root, low, high, ans) ans.sort() return ans def find(self, root, low, high, ans): if root==None: return if low<=root.data<=high: ans.append(root.data) if low <= root.data and high <= root.data: self.find(root.left,low, high, ans) elif low >= root.data and high >= root.data: self.find(root.right, low, high, ans) else: self.find(root.left, low, high, ans) self.find(root.right, low, high, ans)" }, { "code": null, "e": 5776, "s": 5774, "text": "0" }, { "code": null, "e": 5803, "s": 5776, "text": "haritasboy12053 months ago" }, { "code": null, "e": 5829, "s": 5803, "text": "C++ || Recursive Solution" }, { "code": null, "e": 6294, "s": 5829, "text": "void solve(Node* root, int low, int high, vector<int> &ans)\n {\n if(root == NULL)\n return;\n solve(root->left,low,high,ans);\n if(root->data >= low && root->data <= high)\n ans.push_back(root->data);\n solve(root->right,low,high,ans); \n }\n vector<int> printNearNodes(Node *root, int low, int high) {\n //code here \n vector<int> ans;\n solve(root,low,high,ans);\n return ans;\n }" }, { "code": null, "e": 6440, "s": 6294, "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": 6476, "s": 6440, "text": " Login to access your submissions. " }, { "code": null, "e": 6486, "s": 6476, "text": "\nProblem\n" }, { "code": null, "e": 6496, "s": 6486, "text": "\nContest\n" }, { "code": null, "e": 6559, "s": 6496, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6707, "s": 6559, "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": 6915, "s": 6707, "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": 7021, "s": 6915, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Recursive function to check if a string is palindrome - GeeksforGeeks
05 Jan, 2022 Given a string, write a recursive function that checks if the given string is a palindrome, else, not a palindrome. Examples: Input : malayalam Output : Yes Reverse of malayalam is also malayalam. Input : max Output : No Reverse of max is not max. We have discussed an iterative function here. The idea of a recursive function is simple: 1) If there is only one character in string return true. 2) Else compare first and last characters and recur for remaining substring. Below is the implementation of the above idea: C++ C Java Python C# PHP Javascript // A recursive C++ program to// check whether a given number// is palindrome or not#include <bits/stdc++.h>using namespace std; // A recursive function that// check a str[s..e] is// palindrome or not.bool isPalRec(char str[], int s, int e){ // If there is only one character if (s == e) return true; // If first and last // characters do not match if (str[s] != str[e]) return false; // If there are more than // two characters, check if // middle substring is also // palindrome or not. if (s < e + 1) return isPalRec(str, s + 1, e - 1); return true;} bool isPalindrome(char str[]){ int n = strlen(str); // An empty string is // considered as palindrome if (n == 0) return true; return isPalRec(str, 0, n - 1);} // Driver Codeint main(){ char str[] = "geeg"; if (isPalindrome(str)) cout << "Yes"; else cout << "No"; return 0;} // This code is contributed by shivanisinghss2110 // A recursive C program to// check whether a given number// is palindrome or not#include <stdio.h>#include <string.h>#include <stdbool.h> // A recursive function that// check a str[s..e] is// palindrome or not.bool isPalRec(char str[], int s, int e){ // If there is only one character if (s == e) return true; // If first and last // characters do not match if (str[s] != str[e]) return false; // If there are more than // two characters, check if // middle substring is also // palindrome or not. if (s < e + 1) return isPalRec(str, s + 1, e - 1); return true;} bool isPalindrome(char str[]){int n = strlen(str); // An empty string is// considered as palindromeif (n == 0) return true; return isPalRec(str, 0, n - 1);} // Driver Codeint main(){ char str[] = "geeg"; if (isPalindrome(str)) printf("Yes"); else printf("No"); return 0;} // A recursive JAVA program to// check whether a given String// is palindrome or notimport java.io.*; class GFG{ // A recursive function that // check a str(s..e) is // palindrome or not. static boolean isPalRec(String str, int s, int e) { // If there is only one character if (s == e) return true; // If first and last // characters do not match if ((str.charAt(s)) != (str.charAt(e))) return false; // If there are more than // two characters, check if // middle substring is also // palindrome or not. if (s < e + 1) return isPalRec(str, s + 1, e - 1); return true; } static boolean isPalindrome(String str) { int n = str.length(); // An empty string is // considered as palindrome if (n == 0) return true; return isPalRec(str, 0, n - 1); } // Driver Code public static void main(String args[]) { String str = "geeg"; if (isPalindrome(str)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed// by Nikita Tiwari # A recursive Python program# to check whether a given# number is palindrome or not # A recursive function that# check a str[s..e] is# palindrome or not.def isPalRec(st, s, e) : # If there is only one character if (s == e): return True # If first and last # characters do not match if (st[s] != st[e]) : return False # If there are more than # two characters, check if # middle substring is also # palindrome or not. if (s < e + 1) : return isPalRec(st, s + 1, e - 1); return True def isPalindrome(st) : n = len(st) # An empty string is # considered as palindrome if (n == 0) : return True return isPalRec(st, 0, n - 1); # Driver Codest = "geeg"if (isPalindrome(st)) : print "Yes"else : print "No" # This code is contributed# by Nikita Tiwari. // A recursive C# program to// check whether a given number// is palindrome or notusing System; class GFG{ // A recursive function that // check a str(s..e) // is palindrome or not. static bool isPalRec(String str, int s, int e) { // If there is only one character if (s == e) return true; // If first and last character // do not match if ((str[s]) != (str[e])) return false; // If there are more than two // characters, check if middle // substring is also // palindrome or not. if (s < e + 1) return isPalRec(str, s + 1, e - 1); return true; } static bool isPalindrome(String str) { int n = str.Length; // An empty string is considered // as palindrome if (n == 0) return true; return isPalRec(str, 0, n - 1); } // Driver Code public static void Main() { String str = "geeg"; if (isPalindrome(str)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by Nitin Mittal. <?php// A recursive php program to// check whether a given number// is palindrome or not // A recursive function that// check a str[s..e] is// palindrome or not.function isPalRec($str, $s,$e){ // If there is only one character if ($s == $e) return true; // If first and last // characters do not match if ($str[$s] != $str[$e]) return false; // If there are more than two // characters, check if middle // substring is also palindrome or not. if ($s < $e + 1) return isPalRec($str, $s + 1, $e - 1); return true;} function isPalindrome($str){$n = strlen($str); // An empty string is// considered as palindromeif ($n == 0) return true; return isPalRec($str, 0, $n - 1);} // Driver Code{ $str = "geeg"; if (isPalindrome($str)) echo("Yes"); else echo("No"); return 0;} // This code is contributed// by nitin mittal.?> <script> // A recursive javascript program to // check whether a given String // is palindrome or not // A recursive function that // check a str(s..e) is // palindrome or not. function isPalRec( str , s , e) { // If there is only one character if (s == e) return true; // If first and last // characters do not match if ((str.charAt(s)) != (str.charAt(e))) return false; // If there are more than // two characters, check if // middle substring is also // palindrome or not. if (s < e + 1) return isPalRec(str, s + 1, e - 1); return true; } function isPalindrome( str) { var n = str.length; // An empty string is // considered as palindrome if (n == 0) return true; return isPalRec(str, 0, n - 1); } // Driver Code var str = "geeg"; if (isPalindrome(str)) document.write("Yes"); else document.write("No"); // This code contributed by gauravrajput1</script> Yes Another Approach : Basically while traversing check whether ith and n-i-1th index are equal or not. If there are not equal return false and if they are equal then continue with the recursion calls. C++ #include <iostream>using namespace std; bool isPalindrome(string s, int i){ if(i > s.size()/2){ return true ; } return s[i] == s[s.size()-i-1] && isPalindrome(s, i+1) ; } int main(){ string str = "geeg" ; if (isPalindrome(str, 0)) cout << "Yes"; else cout << "No"; return 0; } Yes Time Complexity: O(n) Auxiliary Space: O(n) This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal shivanisinghss2110 GauravRajput1 prasanna1995 palindrome Strings Strings palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Different methods to reverse a string in C/C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ Check whether two strings are anagram of each other Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Top 50 String Coding Problems for Interviews
[ { "code": null, "e": 26161, "s": 26133, "text": "\n05 Jan, 2022" }, { "code": null, "e": 26278, "s": 26161, "text": "Given a string, write a recursive function that checks if the given string is a palindrome, else, not a palindrome. " }, { "code": null, "e": 26289, "s": 26278, "text": "Examples: " }, { "code": null, "e": 26413, "s": 26289, "text": "Input : malayalam\nOutput : Yes\nReverse of malayalam is also\nmalayalam.\n\nInput : max\nOutput : No\nReverse of max is not max. " }, { "code": null, "e": 26504, "s": 26413, "text": "We have discussed an iterative function here. The idea of a recursive function is simple: " }, { "code": null, "e": 26644, "s": 26504, "text": "1) If there is only one character in string\n return true.\n2) Else compare first and last characters\n and recur for remaining substring." }, { "code": null, "e": 26692, "s": 26644, "text": "Below is the implementation of the above idea: " }, { "code": null, "e": 26696, "s": 26692, "text": "C++" }, { "code": null, "e": 26698, "s": 26696, "text": "C" }, { "code": null, "e": 26703, "s": 26698, "text": "Java" }, { "code": null, "e": 26710, "s": 26703, "text": "Python" }, { "code": null, "e": 26713, "s": 26710, "text": "C#" }, { "code": null, "e": 26717, "s": 26713, "text": "PHP" }, { "code": null, "e": 26728, "s": 26717, "text": "Javascript" }, { "code": "// A recursive C++ program to// check whether a given number// is palindrome or not#include <bits/stdc++.h>using namespace std; // A recursive function that// check a str[s..e] is// palindrome or not.bool isPalRec(char str[], int s, int e){ // If there is only one character if (s == e) return true; // If first and last // characters do not match if (str[s] != str[e]) return false; // If there are more than // two characters, check if // middle substring is also // palindrome or not. if (s < e + 1) return isPalRec(str, s + 1, e - 1); return true;} bool isPalindrome(char str[]){ int n = strlen(str); // An empty string is // considered as palindrome if (n == 0) return true; return isPalRec(str, 0, n - 1);} // Driver Codeint main(){ char str[] = \"geeg\"; if (isPalindrome(str)) cout << \"Yes\"; else cout << \"No\"; return 0;} // This code is contributed by shivanisinghss2110", "e": 27721, "s": 26728, "text": null }, { "code": "// A recursive C program to// check whether a given number// is palindrome or not#include <stdio.h>#include <string.h>#include <stdbool.h> // A recursive function that// check a str[s..e] is// palindrome or not.bool isPalRec(char str[], int s, int e){ // If there is only one character if (s == e) return true; // If first and last // characters do not match if (str[s] != str[e]) return false; // If there are more than // two characters, check if // middle substring is also // palindrome or not. if (s < e + 1) return isPalRec(str, s + 1, e - 1); return true;} bool isPalindrome(char str[]){int n = strlen(str); // An empty string is// considered as palindromeif (n == 0) return true; return isPalRec(str, 0, n - 1);} // Driver Codeint main(){ char str[] = \"geeg\"; if (isPalindrome(str)) printf(\"Yes\"); else printf(\"No\"); return 0;}", "e": 28638, "s": 27721, "text": null }, { "code": "// A recursive JAVA program to// check whether a given String// is palindrome or notimport java.io.*; class GFG{ // A recursive function that // check a str(s..e) is // palindrome or not. static boolean isPalRec(String str, int s, int e) { // If there is only one character if (s == e) return true; // If first and last // characters do not match if ((str.charAt(s)) != (str.charAt(e))) return false; // If there are more than // two characters, check if // middle substring is also // palindrome or not. if (s < e + 1) return isPalRec(str, s + 1, e - 1); return true; } static boolean isPalindrome(String str) { int n = str.length(); // An empty string is // considered as palindrome if (n == 0) return true; return isPalRec(str, 0, n - 1); } // Driver Code public static void main(String args[]) { String str = \"geeg\"; if (isPalindrome(str)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed// by Nikita Tiwari", "e": 29855, "s": 28638, "text": null }, { "code": "# A recursive Python program# to check whether a given# number is palindrome or not # A recursive function that# check a str[s..e] is# palindrome or not.def isPalRec(st, s, e) : # If there is only one character if (s == e): return True # If first and last # characters do not match if (st[s] != st[e]) : return False # If there are more than # two characters, check if # middle substring is also # palindrome or not. if (s < e + 1) : return isPalRec(st, s + 1, e - 1); return True def isPalindrome(st) : n = len(st) # An empty string is # considered as palindrome if (n == 0) : return True return isPalRec(st, 0, n - 1); # Driver Codest = \"geeg\"if (isPalindrome(st)) : print \"Yes\"else : print \"No\" # This code is contributed# by Nikita Tiwari.", "e": 30704, "s": 29855, "text": null }, { "code": "// A recursive C# program to// check whether a given number// is palindrome or notusing System; class GFG{ // A recursive function that // check a str(s..e) // is palindrome or not. static bool isPalRec(String str, int s, int e) { // If there is only one character if (s == e) return true; // If first and last character // do not match if ((str[s]) != (str[e])) return false; // If there are more than two // characters, check if middle // substring is also // palindrome or not. if (s < e + 1) return isPalRec(str, s + 1, e - 1); return true; } static bool isPalindrome(String str) { int n = str.Length; // An empty string is considered // as palindrome if (n == 0) return true; return isPalRec(str, 0, n - 1); } // Driver Code public static void Main() { String str = \"geeg\"; if (isPalindrome(str)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by Nitin Mittal.", "e": 31937, "s": 30704, "text": null }, { "code": "<?php// A recursive php program to// check whether a given number// is palindrome or not // A recursive function that// check a str[s..e] is// palindrome or not.function isPalRec($str, $s,$e){ // If there is only one character if ($s == $e) return true; // If first and last // characters do not match if ($str[$s] != $str[$e]) return false; // If there are more than two // characters, check if middle // substring is also palindrome or not. if ($s < $e + 1) return isPalRec($str, $s + 1, $e - 1); return true;} function isPalindrome($str){$n = strlen($str); // An empty string is// considered as palindromeif ($n == 0) return true; return isPalRec($str, 0, $n - 1);} // Driver Code{ $str = \"geeg\"; if (isPalindrome($str)) echo(\"Yes\"); else echo(\"No\"); return 0;} // This code is contributed// by nitin mittal.?>", "e": 32817, "s": 31937, "text": null }, { "code": "<script> // A recursive javascript program to // check whether a given String // is palindrome or not // A recursive function that // check a str(s..e) is // palindrome or not. function isPalRec( str , s , e) { // If there is only one character if (s == e) return true; // If first and last // characters do not match if ((str.charAt(s)) != (str.charAt(e))) return false; // If there are more than // two characters, check if // middle substring is also // palindrome or not. if (s < e + 1) return isPalRec(str, s + 1, e - 1); return true; } function isPalindrome( str) { var n = str.length; // An empty string is // considered as palindrome if (n == 0) return true; return isPalRec(str, 0, n - 1); } // Driver Code var str = \"geeg\"; if (isPalindrome(str)) document.write(\"Yes\"); else document.write(\"No\"); // This code contributed by gauravrajput1</script>", "e": 33920, "s": 32817, "text": null }, { "code": null, "e": 33924, "s": 33920, "text": "Yes" }, { "code": null, "e": 33943, "s": 33924, "text": "Another Approach :" }, { "code": null, "e": 34024, "s": 33943, "text": "Basically while traversing check whether ith and n-i-1th index are equal or not." }, { "code": null, "e": 34122, "s": 34024, "text": "If there are not equal return false and if they are equal then continue with the recursion calls." }, { "code": null, "e": 34126, "s": 34122, "text": "C++" }, { "code": "#include <iostream>using namespace std; bool isPalindrome(string s, int i){ if(i > s.size()/2){ return true ; } return s[i] == s[s.size()-i-1] && isPalindrome(s, i+1) ; } int main(){ string str = \"geeg\" ; if (isPalindrome(str, 0)) cout << \"Yes\"; else cout << \"No\"; return 0; }", "e": 34461, "s": 34126, "text": null }, { "code": null, "e": 34465, "s": 34461, "text": "Yes" }, { "code": null, "e": 34487, "s": 34465, "text": "Time Complexity: O(n)" }, { "code": null, "e": 34509, "s": 34487, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 34930, "s": 34509, "text": "This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 34943, "s": 34930, "text": "nitin mittal" }, { "code": null, "e": 34962, "s": 34943, "text": "shivanisinghss2110" }, { "code": null, "e": 34976, "s": 34962, "text": "GauravRajput1" }, { "code": null, "e": 34989, "s": 34976, "text": "prasanna1995" }, { "code": null, "e": 35000, "s": 34989, "text": "palindrome" }, { "code": null, "e": 35008, "s": 35000, "text": "Strings" }, { "code": null, "e": 35016, "s": 35008, "text": "Strings" }, { "code": null, "e": 35027, "s": 35016, "text": "palindrome" }, { "code": null, "e": 35125, "s": 35027, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35200, "s": 35125, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 35257, "s": 35200, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 35293, "s": 35257, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 35340, "s": 35293, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 35393, "s": 35340, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 35429, "s": 35393, "text": "Convert string to char array in C++" }, { "code": null, "e": 35481, "s": 35429, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 35519, "s": 35481, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 35549, "s": 35519, "text": "Caesar Cipher in Cryptography" } ]
Divisibility by 64 with removal of bits allowed - GeeksforGeeks
27 Apr, 2021 Given a binary string, we need to check whether that number is divisible by 64 or not after removing of some bits. If yes then print “possible” else “not possible”. We cannot make number 0 to make it divisible.Example : Input: 100010001 Output: Possible Explanation: We can get string 1 000 000 after removing two ones which is a representation of number 64 in the binary numerical system. Input: 100 Output: Not possible Explanation : The number is 4 which is not divisible by 64 or cannot be made possible my removing some digits. If we have 6 zeros after any one, then we can remove other bits represent it as a multiple of 64. So we just need to check if there is a 1 before six zeros. C++ Java Python3 C# PHP Javascript // CPP program to find if given binary string can// become divisible by 64 after removing some bits.#include <iostream>using namespace std; // function to check if it is possible// to make it a multiple of 64.bool checking(string s){ int c = 0; // counter to count 0's int n = s.length(); // length of the string // loop which traverses right to left and // calculates the number of zeros before 1. for (int i = n - 1; i >= 0; i--) { if (s[i] == '0') c++; if (c >= 6 and s[i] == '1') return true; } return false;} // driver codeint main(){ string s = "100010001"; if (checking(s)) cout << "Possible"; else cout << "Not possible"; return 0;} // Java program to find if// given binary string can// become divisible by// 64 after removing some bitsimport java.io.*; class GFG{ // function to check if it is possible // to make it a multiple of 64. static boolean checking(String s) { // counter to count 0's int c = 0; // length of the string int n = s.length(); // loop which traverses right to left and // calculates the number of zeros before 1. for (int i = n - 1; i >= 0; i--) { if (s.charAt(i) == '0') c++; if (c >= 6 && s.charAt(i) == '1') return true; } return false; } // Driver code public static void main (String[] args) { String s = "100010001"; if (checking(s)) System.out.println ( "Possible"); else System.out.println ( "Not possible"); }} // This code is contributed by vt_m # Python 3 program to find if given binary# string can become divisible by 64 after# removing some bits. # function to check if it is possible# to make it a multiple of 64.def checking(s): c = 0 # counter to count 0's n = len(s) # length of the string # loop which traverses right to left and # calculates the number of zeros before 1. i = n - 1 while(i >= 0): if (s[i] == '0'): c += 1 if (c >= 6 and s[i] == '1'): return True i -= 1 return False # Driver codeif __name__ == '__main__': s = "100010001" if (checking(s)): print("Possible") else: print("Not possible") # This code is contributed by# Surendra_Gangwar // C# program to find if given binary// string can become divisible by 64// after removing some bitsusing System; class GFG { // function to check if it is possible // to make it a multiple of 64. static bool checking(string s) { // counter to count 0's int c = 0; // length of the string int n = s.Length; // loop which traverses right to // left and calculates the number // of zeros before 1. for (int i = n - 1; i >= 0; i--) { if (s[i] == '0') c++; if (c >= 6 && s[i] == '1') return true; } return false; } // Driver code public static void Main () { String s = "100010001"; if (checking(s)) Console.WriteLine ( "Possible"); else Console.WriteLine( "Not possible"); }} // This code is contributed by vt_m. <?php// PHP program to find if// given binary string can// become divisible by 64// after removing some bits. // function to check if// it is possible// to make it a multiple of 64. function checking($s){ // counter to count 0's $c = 0; // length of the string $n = strlen($s); // loop which traverses right // to left and calculates the // number of zeros before 1. for ($i = $n - 1; $i >= 0; $i--) { if ($s[$i] == '0') $c++; if ($c >= 6 and $s[$i] == '1') return true; } return false;} // Driver Code$s = "100010001";if (checking($s)) echo "Possible";else echo "Not possible"; // This code is contributed by ajit?> <script> // Javascript program to find if given binary// string can become divisible by 64// after removing some bits // function to check if it is possible // to make it a multiple of 64. function checking(s) { // counter to count 0's let c = 0; // length of the string let n = s.length; // loop which traverses right to // left and calculates the number // of zeros before 1. for (let i = n - 1; i >= 0; i--) { if (s[i] == '0') c++; if (c >= 6 && s[i] == '1') return true; } return false; } // Driver code let s = "100010001"; if (checking(s)) document.write( "Possible"); else document.write( "Not possible"); // This code is contributed by code_hunt.</script> Output : Possible Time Complexity: O(length of string) YouTubeGeeksforGeeks507K subscribersDivisibility by 64 with removal of bits allowed | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:11•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=9Gq2xPjmXw4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Twinkle Bajaj. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m jit_t SURENDRA_GANGWAR code_hunt binary-string divisibility Bit Magic 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 Find the size of Largest Subset with positive Bitwise AND Check whether bitwise AND of a number with any subset of an array is zero or not Write an Efficient Method to Check if a Number is Multiple of 3 Highest power of 2 less than or equal to given number Swap two nibbles in a byte Swap bits in a given number Check for Integer Overflow Reverse actual bits of the given number Find one extra character in a string
[ { "code": null, "e": 26279, "s": 26251, "text": "\n27 Apr, 2021" }, { "code": null, "e": 26501, "s": 26279, "text": "Given a binary string, we need to check whether that number is divisible by 64 or not after removing of some bits. If yes then print “possible” else “not possible”. We cannot make number 0 to make it divisible.Example : " }, { "code": null, "e": 26821, "s": 26501, "text": "Input: 100010001 \nOutput: Possible\nExplanation: We can get string 1 000 000 \nafter removing two ones which is a \nrepresentation of number 64 in the binary \nnumerical system.\n\nInput: 100\nOutput: Not possible\nExplanation : The number is 4 which is not \ndivisible by 64 or cannot be made possible \nmy removing some digits." }, { "code": null, "e": 26982, "s": 26823, "text": "If we have 6 zeros after any one, then we can remove other bits represent it as a multiple of 64. So we just need to check if there is a 1 before six zeros. " }, { "code": null, "e": 26986, "s": 26982, "text": "C++" }, { "code": null, "e": 26991, "s": 26986, "text": "Java" }, { "code": null, "e": 26999, "s": 26991, "text": "Python3" }, { "code": null, "e": 27002, "s": 26999, "text": "C#" }, { "code": null, "e": 27006, "s": 27002, "text": "PHP" }, { "code": null, "e": 27017, "s": 27006, "text": "Javascript" }, { "code": "// CPP program to find if given binary string can// become divisible by 64 after removing some bits.#include <iostream>using namespace std; // function to check if it is possible// to make it a multiple of 64.bool checking(string s){ int c = 0; // counter to count 0's int n = s.length(); // length of the string // loop which traverses right to left and // calculates the number of zeros before 1. for (int i = n - 1; i >= 0; i--) { if (s[i] == '0') c++; if (c >= 6 and s[i] == '1') return true; } return false;} // driver codeint main(){ string s = \"100010001\"; if (checking(s)) cout << \"Possible\"; else cout << \"Not possible\"; return 0;}", "e": 27744, "s": 27017, "text": null }, { "code": "// Java program to find if// given binary string can// become divisible by// 64 after removing some bitsimport java.io.*; class GFG{ // function to check if it is possible // to make it a multiple of 64. static boolean checking(String s) { // counter to count 0's int c = 0; // length of the string int n = s.length(); // loop which traverses right to left and // calculates the number of zeros before 1. for (int i = n - 1; i >= 0; i--) { if (s.charAt(i) == '0') c++; if (c >= 6 && s.charAt(i) == '1') return true; } return false; } // Driver code public static void main (String[] args) { String s = \"100010001\"; if (checking(s)) System.out.println ( \"Possible\"); else System.out.println ( \"Not possible\"); }} // This code is contributed by vt_m", "e": 28715, "s": 27744, "text": null }, { "code": "# Python 3 program to find if given binary# string can become divisible by 64 after# removing some bits. # function to check if it is possible# to make it a multiple of 64.def checking(s): c = 0 # counter to count 0's n = len(s) # length of the string # loop which traverses right to left and # calculates the number of zeros before 1. i = n - 1 while(i >= 0): if (s[i] == '0'): c += 1 if (c >= 6 and s[i] == '1'): return True i -= 1 return False # Driver codeif __name__ == '__main__': s = \"100010001\" if (checking(s)): print(\"Possible\") else: print(\"Not possible\") # This code is contributed by# Surendra_Gangwar", "e": 29453, "s": 28715, "text": null }, { "code": "// C# program to find if given binary// string can become divisible by 64// after removing some bitsusing System; class GFG { // function to check if it is possible // to make it a multiple of 64. static bool checking(string s) { // counter to count 0's int c = 0; // length of the string int n = s.Length; // loop which traverses right to // left and calculates the number // of zeros before 1. for (int i = n - 1; i >= 0; i--) { if (s[i] == '0') c++; if (c >= 6 && s[i] == '1') return true; } return false; } // Driver code public static void Main () { String s = \"100010001\"; if (checking(s)) Console.WriteLine ( \"Possible\"); else Console.WriteLine( \"Not possible\"); }} // This code is contributed by vt_m.", "e": 30455, "s": 29453, "text": null }, { "code": "<?php// PHP program to find if// given binary string can// become divisible by 64// after removing some bits. // function to check if// it is possible// to make it a multiple of 64. function checking($s){ // counter to count 0's $c = 0; // length of the string $n = strlen($s); // loop which traverses right // to left and calculates the // number of zeros before 1. for ($i = $n - 1; $i >= 0; $i--) { if ($s[$i] == '0') $c++; if ($c >= 6 and $s[$i] == '1') return true; } return false;} // Driver Code$s = \"100010001\";if (checking($s)) echo \"Possible\";else echo \"Not possible\"; // This code is contributed by ajit?>", "e": 31155, "s": 30455, "text": null }, { "code": "<script> // Javascript program to find if given binary// string can become divisible by 64// after removing some bits // function to check if it is possible // to make it a multiple of 64. function checking(s) { // counter to count 0's let c = 0; // length of the string let n = s.length; // loop which traverses right to // left and calculates the number // of zeros before 1. for (let i = n - 1; i >= 0; i--) { if (s[i] == '0') c++; if (c >= 6 && s[i] == '1') return true; } return false; } // Driver code let s = \"100010001\"; if (checking(s)) document.write( \"Possible\"); else document.write( \"Not possible\"); // This code is contributed by code_hunt.</script>", "e": 32116, "s": 31155, "text": null }, { "code": null, "e": 32127, "s": 32116, "text": "Output : " }, { "code": null, "e": 32136, "s": 32127, "text": "Possible" }, { "code": null, "e": 32174, "s": 32136, "text": "Time Complexity: O(length of string) " }, { "code": null, "e": 33020, "s": 32174, "text": "YouTubeGeeksforGeeks507K subscribersDivisibility by 64 with removal of bits allowed | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:11•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=9Gq2xPjmXw4\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 33446, "s": 33020, "text": "This article is contributed by Twinkle Bajaj. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33451, "s": 33446, "text": "vt_m" }, { "code": null, "e": 33457, "s": 33451, "text": "jit_t" }, { "code": null, "e": 33474, "s": 33457, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 33484, "s": 33474, "text": "code_hunt" }, { "code": null, "e": 33498, "s": 33484, "text": "binary-string" }, { "code": null, "e": 33511, "s": 33498, "text": "divisibility" }, { "code": null, "e": 33521, "s": 33511, "text": "Bit Magic" }, { "code": null, "e": 33531, "s": 33521, "text": "Bit Magic" }, { "code": null, "e": 33629, "s": 33531, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33680, "s": 33629, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 33738, "s": 33680, "text": "Find the size of Largest Subset with positive Bitwise AND" }, { "code": null, "e": 33819, "s": 33738, "text": "Check whether bitwise AND of a number with any subset of an array is zero or not" }, { "code": null, "e": 33883, "s": 33819, "text": "Write an Efficient Method to Check if a Number is Multiple of 3" }, { "code": null, "e": 33937, "s": 33883, "text": "Highest power of 2 less than or equal to given number" }, { "code": null, "e": 33964, "s": 33937, "text": "Swap two nibbles in a byte" }, { "code": null, "e": 33992, "s": 33964, "text": "Swap bits in a given number" }, { "code": null, "e": 34019, "s": 33992, "text": "Check for Integer Overflow" }, { "code": null, "e": 34059, "s": 34019, "text": "Reverse actual bits of the given number" } ]
Python | Ways to create a dictionary of Lists - GeeksforGeeks
11 Mar, 2019 Till now, we have seen the ways to creating dictionary in multiple ways and different operations on the key and values in dictionary. Now, let’s see different ways of creating a dictionary of list. Note that the restriction with keys in Python dictionary is only immutable data types can be used as keys, which means we cannot use a dictionary of list as a key. # Creating a dictionarymyDict = {[1, 2]: 'Geeks'} print(myDict) Output: TypeError: unhashable type: 'list' But the same can be done very wisely with values in dictionary. Let’s see all the different ways we can create a dictionary of Lists. Method #1: Using subscript # Creating an empty dictionarymyDict = {} # Adding list as valuemyDict["key1"] = [1, 2]myDict["key2"] = ["Geeks", "For", "Geeks"] print(myDict) Output: {'key2': ['Geeks', 'For', 'Geeks'], 'key1': [1, 2]} Method #2: Adding nested list as value using append() method. Create a new list and we can simply append that list to the value. # Creating an empty dictionarymyDict = {} # Adding list as valuemyDict["key1"] = [1, 2] # creating a listlst = ['Geeks', 'For', 'Geeks'] # Adding this list as sublist in myDictmyDict["key1"].append(lst) print(myDict) Output: {'key1': [1, 2, ['Geeks', 'For', 'Geeks']]} Method #3: Using setdefault() method Iterate the list and keep appending the elements till given range using setdefault() method. # Creating an empty dictmyDict = dict() # Creating a listvalList = ['1', '2', '3'] # Iterating the elements in listfor val in valList: for ele in range(int(val), int(val) + 2): myDict.setdefault(ele, []).append(val) print(myDict) Output: {1: ['1'], 2: ['1', '2'], 3: ['2', '3'], 4: ['3']} Method #4: Using list comprehension # Creating a dictionary of lists# using list comprehensiond = dict((val, range(int(val), int(val) + 2)) for val in ['1', '2', '3']) print(d) Output: {'1': [1, 2], '3': [3, 4], '2': [2, 3]} Method #5: Using defaultdict Note that the same thing can also be done with simple dictionary but using defaultdict is more efficient for such cases. # Importing defaultdictfrom collections import defaultdict lst = [('Geeks', 1), ('For', 2), ('Geeks', 3)]orDict = defaultdict(list) # iterating over list of tuplesfor key, val in lst: orDict[key].append(val) print(orDict) Output: defaultdict(, {'For': [2], 'Geeks': [1, 3]}) Note that there are only two key:value pairs in output dictionary but the input list contains three tuples. The first element(i.e. key) is same for first and third tuple and two keys can never be same. Method #6: Using Json #importing jsonimport json #Initialisation of listlst = [('Geeks', 1), ('For', 2), ('Geeks', 3)] #Initialisation of dictionarydict = {} #using json.dump()hash = json.dumps(lst) #creating a hashdict[hash] = "converted" #Printing dictionaryprint(dict) #Added by Paras Jain(everythingispossible) Output: {'[["Geeks", 1], ["For", 2], ["Geeks", 3]]': 'converted'} everythingispossible Python dictionary-programs Python list-programs python-dict python-list Python python-dict python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python How To Convert Python Dictionary To JSON? sum() function in Python
[ { "code": null, "e": 25488, "s": 25460, "text": "\n11 Mar, 2019" }, { "code": null, "e": 25686, "s": 25488, "text": "Till now, we have seen the ways to creating dictionary in multiple ways and different operations on the key and values in dictionary. Now, let’s see different ways of creating a dictionary of list." }, { "code": null, "e": 25850, "s": 25686, "text": "Note that the restriction with keys in Python dictionary is only immutable data types can be used as keys, which means we cannot use a dictionary of list as a key." }, { "code": "# Creating a dictionarymyDict = {[1, 2]: 'Geeks'} print(myDict)", "e": 25915, "s": 25850, "text": null }, { "code": null, "e": 25923, "s": 25915, "text": "Output:" }, { "code": null, "e": 25958, "s": 25923, "text": "TypeError: unhashable type: 'list'" }, { "code": null, "e": 26092, "s": 25958, "text": "But the same can be done very wisely with values in dictionary. Let’s see all the different ways we can create a dictionary of Lists." }, { "code": null, "e": 26119, "s": 26092, "text": "Method #1: Using subscript" }, { "code": "# Creating an empty dictionarymyDict = {} # Adding list as valuemyDict[\"key1\"] = [1, 2]myDict[\"key2\"] = [\"Geeks\", \"For\", \"Geeks\"] print(myDict)", "e": 26266, "s": 26119, "text": null }, { "code": null, "e": 26274, "s": 26266, "text": "Output:" }, { "code": null, "e": 26326, "s": 26274, "text": "{'key2': ['Geeks', 'For', 'Geeks'], 'key1': [1, 2]}" }, { "code": null, "e": 26389, "s": 26326, "text": " Method #2: Adding nested list as value using append() method." }, { "code": null, "e": 26456, "s": 26389, "text": "Create a new list and we can simply append that list to the value." }, { "code": "# Creating an empty dictionarymyDict = {} # Adding list as valuemyDict[\"key1\"] = [1, 2] # creating a listlst = ['Geeks', 'For', 'Geeks'] # Adding this list as sublist in myDictmyDict[\"key1\"].append(lst) print(myDict)", "e": 26677, "s": 26456, "text": null }, { "code": null, "e": 26685, "s": 26677, "text": "Output:" }, { "code": null, "e": 26729, "s": 26685, "text": "{'key1': [1, 2, ['Geeks', 'For', 'Geeks']]}" }, { "code": null, "e": 26767, "s": 26729, "text": " Method #3: Using setdefault() method" }, { "code": null, "e": 26860, "s": 26767, "text": "Iterate the list and keep appending the elements till given range using setdefault() method." }, { "code": "# Creating an empty dictmyDict = dict() # Creating a listvalList = ['1', '2', '3'] # Iterating the elements in listfor val in valList: for ele in range(int(val), int(val) + 2): myDict.setdefault(ele, []).append(val) print(myDict)", "e": 27104, "s": 26860, "text": null }, { "code": null, "e": 27112, "s": 27104, "text": "Output:" }, { "code": null, "e": 27163, "s": 27112, "text": "{1: ['1'], 2: ['1', '2'], 3: ['2', '3'], 4: ['3']}" }, { "code": null, "e": 27200, "s": 27163, "text": " Method #4: Using list comprehension" }, { "code": "# Creating a dictionary of lists# using list comprehensiond = dict((val, range(int(val), int(val) + 2)) for val in ['1', '2', '3']) print(d)", "e": 27359, "s": 27200, "text": null }, { "code": null, "e": 27367, "s": 27359, "text": "Output:" }, { "code": null, "e": 27407, "s": 27367, "text": "{'1': [1, 2], '3': [3, 4], '2': [2, 3]}" }, { "code": null, "e": 27437, "s": 27407, "text": " Method #5: Using defaultdict" }, { "code": null, "e": 27558, "s": 27437, "text": "Note that the same thing can also be done with simple dictionary but using defaultdict is more efficient for such cases." }, { "code": "# Importing defaultdictfrom collections import defaultdict lst = [('Geeks', 1), ('For', 2), ('Geeks', 3)]orDict = defaultdict(list) # iterating over list of tuplesfor key, val in lst: orDict[key].append(val) print(orDict)", "e": 27786, "s": 27558, "text": null }, { "code": null, "e": 27794, "s": 27786, "text": "Output:" }, { "code": null, "e": 27839, "s": 27794, "text": "defaultdict(, {'For': [2], 'Geeks': [1, 3]})" }, { "code": null, "e": 28063, "s": 27839, "text": "Note that there are only two key:value pairs in output dictionary but the input list contains three tuples. The first element(i.e. key) is same for first and third tuple and two keys can never be same. Method #6: Using Json" }, { "code": "#importing jsonimport json #Initialisation of listlst = [('Geeks', 1), ('For', 2), ('Geeks', 3)] #Initialisation of dictionarydict = {} #using json.dump()hash = json.dumps(lst) #creating a hashdict[hash] = \"converted\" #Printing dictionaryprint(dict) #Added by Paras Jain(everythingispossible)", "e": 28362, "s": 28063, "text": null }, { "code": null, "e": 28370, "s": 28362, "text": "Output:" }, { "code": null, "e": 28428, "s": 28370, "text": "{'[[\"Geeks\", 1], [\"For\", 2], [\"Geeks\", 3]]': 'converted'}" }, { "code": null, "e": 28451, "s": 28430, "text": "everythingispossible" }, { "code": null, "e": 28478, "s": 28451, "text": "Python dictionary-programs" }, { "code": null, "e": 28499, "s": 28478, "text": "Python list-programs" }, { "code": null, "e": 28511, "s": 28499, "text": "python-dict" }, { "code": null, "e": 28523, "s": 28511, "text": "python-list" }, { "code": null, "e": 28530, "s": 28523, "text": "Python" }, { "code": null, "e": 28542, "s": 28530, "text": "python-dict" }, { "code": null, "e": 28554, "s": 28542, "text": "python-list" }, { "code": null, "e": 28652, "s": 28554, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28684, "s": 28652, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28706, "s": 28684, "text": "Enumerate() in Python" }, { "code": null, "e": 28748, "s": 28706, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28774, "s": 28748, "text": "Python String | replace()" }, { "code": null, "e": 28803, "s": 28774, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28840, "s": 28803, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28876, "s": 28840, "text": "Convert integer to string in Python" }, { "code": null, "e": 28918, "s": 28876, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28960, "s": 28918, "text": "How To Convert Python Dictionary To JSON?" } ]
Lagrange Multipliers - GeeksforGeeks
01 Oct, 2019 One of the major problems that engineers face is the problem of optimization of a certain function. Mathematics provides us with a beautiful way to solve such problems. This method is known as the Method of Lagrange Multipliers. So how and when to apply? There are certain conditions.Suppose you have the following problem:Find the coordinates of the point on the plane 2x + 3y – 5z = 1 which is at the least distance from the origin. So the function you want to optimize is, √(x2 + y2 + z2), Let this be f(x, y, z) But we have a constraint;the point should lie on the given plane.Hence this ‘constraint function’ is generally denoted by g(x, y, z).But before applying Lagrange Multiplier method we should make sure that g(x, y, z) = c where ‘c’ is a constant. In this situation, g(x, y, z) = 2x + 3y - 5z It is indeed equal to a constant that is ‘1’. Hence we can apply the method. Now the procedure is to solve this equation: ∇f(x, y, z) = λ∇g(x, y, z) where λ is a real number. This gives us 3 equations and the fourth equation is of course our constraint function g(x, y, z).Solve for x, y, z and λ. An example will make it clear. Example:Find the maximum and minimum values of f(x, y, z) = 3x2 + y subject to the constraint, 4x - 3y = 9 and x2 + z2 = 9 . This example has been deliberately taken to teach you what to do in case of more than one constraint functions. In such cases assume as many arbitrary constants as the number of constraint functions and write the equation in the form: ∇f(x, y, z) = c1∇g(x, y, z) + c2∇h(x, y, z) + c3∇p(x, y, z) ... ... where ci for i=1, 2, 3... are just real numbers and g, h, p are constraint functions. Now if you get more than one triplet, figure out which one represents a maximum and which one represents the minimum by satisfying it in the function to be optimized and compare the values.In this question the answer would be: Maximum for (-2/√13, 3/√13, -2 - 7/√13) and Minimum for (2/√13, -3/√13, -2 + 7/√13) Engineering Mathematics Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Activation Functions Difference between Propositional Logic and Predicate Logic Logic Notations in LaTeX Univariate, Bivariate and Multivariate data and its analysis Z-test Proof that vertex cover is NP complete Brackets in Latex Betweenness Centrality (Centrality Measure) Introduction of Statistics and its Types Mathematics | Introduction of Set theory
[ { "code": null, "e": 26163, "s": 26135, "text": "\n01 Oct, 2019" }, { "code": null, "e": 26392, "s": 26163, "text": "One of the major problems that engineers face is the problem of optimization of a certain function. Mathematics provides us with a beautiful way to solve such problems. This method is known as the Method of Lagrange Multipliers." }, { "code": null, "e": 26598, "s": 26392, "text": "So how and when to apply? There are certain conditions.Suppose you have the following problem:Find the coordinates of the point on the plane 2x + 3y – 5z = 1 which is at the least distance from the origin." }, { "code": null, "e": 26639, "s": 26598, "text": "So the function you want to optimize is," }, { "code": null, "e": 26680, "s": 26639, "text": "√(x2 + y2 + z2),\nLet this be f(x, y, z) " }, { "code": null, "e": 26944, "s": 26680, "text": "But we have a constraint;the point should lie on the given plane.Hence this ‘constraint function’ is generally denoted by g(x, y, z).But before applying Lagrange Multiplier method we should make sure that g(x, y, z) = c where ‘c’ is a constant. In this situation," }, { "code": null, "e": 26970, "s": 26944, "text": "g(x, y, z) = 2x + 3y - 5z" }, { "code": null, "e": 27047, "s": 26970, "text": "It is indeed equal to a constant that is ‘1’. Hence we can apply the method." }, { "code": null, "e": 27092, "s": 27047, "text": "Now the procedure is to solve this equation:" }, { "code": null, "e": 27119, "s": 27092, "text": "∇f(x, y, z) = λ∇g(x, y, z)" }, { "code": null, "e": 27145, "s": 27119, "text": "where λ is a real number." }, { "code": null, "e": 27268, "s": 27145, "text": "This gives us 3 equations and the fourth equation is of course our constraint function g(x, y, z).Solve for x, y, z and λ." }, { "code": null, "e": 27299, "s": 27268, "text": "An example will make it clear." }, { "code": null, "e": 27394, "s": 27299, "text": "Example:Find the maximum and minimum values of f(x, y, z) = 3x2 + y subject to the constraint," }, { "code": null, "e": 27423, "s": 27394, "text": "4x - 3y = 9 \nand x2 + z2 = 9" }, { "code": null, "e": 27425, "s": 27423, "text": "." }, { "code": null, "e": 27660, "s": 27425, "text": "This example has been deliberately taken to teach you what to do in case of more than one constraint functions. In such cases assume as many arbitrary constants as the number of constraint functions and write the equation in the form:" }, { "code": null, "e": 27728, "s": 27660, "text": "∇f(x, y, z) = c1∇g(x, y, z) + c2∇h(x, y, z) + c3∇p(x, y, z) ... ..." }, { "code": null, "e": 27814, "s": 27728, "text": "where ci for i=1, 2, 3... are just real numbers and g, h, p are constraint functions." }, { "code": null, "e": 28041, "s": 27814, "text": "Now if you get more than one triplet, figure out which one represents a maximum and which one represents the minimum by satisfying it in the function to be optimized and compare the values.In this question the answer would be:" }, { "code": null, "e": 28126, "s": 28041, "text": "Maximum for (-2/√13, 3/√13, -2 - 7/√13) and \nMinimum for (2/√13, -3/√13, -2 + 7/√13)" }, { "code": null, "e": 28150, "s": 28126, "text": "Engineering Mathematics" }, { "code": null, "e": 28248, "s": 28150, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28269, "s": 28248, "text": "Activation Functions" }, { "code": null, "e": 28328, "s": 28269, "text": "Difference between Propositional Logic and Predicate Logic" }, { "code": null, "e": 28353, "s": 28328, "text": "Logic Notations in LaTeX" }, { "code": null, "e": 28414, "s": 28353, "text": "Univariate, Bivariate and Multivariate data and its analysis" }, { "code": null, "e": 28421, "s": 28414, "text": "Z-test" }, { "code": null, "e": 28460, "s": 28421, "text": "Proof that vertex cover is NP complete" }, { "code": null, "e": 28478, "s": 28460, "text": "Brackets in Latex" }, { "code": null, "e": 28522, "s": 28478, "text": "Betweenness Centrality (Centrality Measure)" }, { "code": null, "e": 28563, "s": 28522, "text": "Introduction of Statistics and its Types" } ]
How does rem differ from em in CSS ? - GeeksforGeeks
08 Nov, 2021 In this article, we will learn about rem & em in CSS, how they differs from each other. The em and rem are the relative length CSS font-size units that can be used in CSS documents to make a specific element’s font size relative to its parents. The em is a CSS font-size unit relative to its directly linked parent, rem is in relation with the font-size of the root element which is basically the HTML element. There are lots of other CSS Units available as well. Let us understand the difference between em and rem with the help of a suitable example. em CSS Units: The em unit is relative to its parent’s size. 1 em = size of parent 2 em = twice the size of the parent 0.5em = half the size of the parent Example: This example demonstrates the use of the CSS em unit that specifies the font-size relative to the direct or its parent element. HTML <!DOCTYPE html><html> <head> <style> html { font-size: 15px; font-family: 'Courier New', Courier, monospace; } #grandPArent { font-size: 2em; } #parent { font-size: 2em; } #child { font-size: 2em; } #grandChild { font-size: 2em; } </style></head> <body> <p>Great Grand Parent - Base Font Size</p> <ul id="grandParent"> <li>GrandParent 1</li> <ul id="garent"> <li>Parent 1</li> <ul id="child"> <li>Child 1</li> <ul id="grandChild"> <li>GrandChild 1</li> <li>GrandChild 2</li> </ul> <li>Child 2</li> </ul> <li>Parent 2</li> </ul> <li>GrandParent 2</li> </ul></body> </html> Explanation: As the elements get nested into one another, the relative size of elements keeps on growing exponentially at a rate of 2x in the above example. In this example, the child has a relative size of 2em (2x the font size of a parent) with respect to the parent which in turn is 2em (2x parent element’s parent) w.r.t. grandparent and is now 4 times the size of the grandparent. Output: CSS em unit Base Element (GreatGrandParent)’s Size: 15px GrandParent1,2 Size: 30px Parent 1,2 Size: 60px Child 1,2 Size: 120px GrandChild 1,2: 240px rem CSS Units: The rem unit is relative to its base root parent element’s size. 1 rem = size of root parent (HTML element) 2 rem = twice the size of root parent (HTML element) 0.5r em = half the size of root parent (HTML element) In this case, as the elements get nested into one another the relative size of elements remains constant as every element’s size is proportional to the root HTML element and not its direct parent and hence properties are not transferred lower down to children and grandchildren elements. In this particular example, the parent has a relative size of 2rem (2x the font size of the root HTML element) w.r.t. root element which is the same as its child and its grandchild element and hence the size even after nesting at multiple levels remains constant. Example: This example demonstrates the use of the CSS rem unit that specifies the font-size relative to the root element. HTML <!DOCTYPE html><html> <head> <style> html { font-size: 15px; font-family: 'Courier New', Courier, monospace; } #grandParent { font-size: 2rem; } #parent { font-size: 2rem; } #child { font-size: 2rem; } #grandChild { font-size: 2rem; } </style></head> <body> <p>Great Grand Parent - Base Font Size</p> <ul id="grandParent"> <li>GrandParent 1</li> <ul id="garent"> <li>Parent 1</li> <ul id="child"> <li>Child 1</li> <ul id="grandChild"> <li>GrandChild 1</li> <li>GrandChild 2</li> </ul> <li>Child 2</li> </ul> <li>Parent 2</li> </ul> <li>GrandParent 2</li> </ul></body> </html> Output: CSS rem unit Base( GreatGrandParent)’s Font Size : 15px GrandParent1,2/Parent1,2/Child1,2/GrandChild1,2 Font Size = 30px Note: Please notice the output of both the above examples to know the difference. Advantages of using rem over em: While scaling our application to responsive layout using media query functionality, we can directly alter the base font-size of the root element and every child can directly scale altogether with just one media query on the root element. When the user has altered the default base font-size of any browser, our application scales well in this case with the usage of CSS rem units. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. bhaskargeeksforgeeks CSS-Basics CSS-Properties CSS-Questions CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery How to style a checkbox using CSS? Search Bar using HTML, CSS and JavaScript How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26621, "s": 26593, "text": "\n08 Nov, 2021" }, { "code": null, "e": 26866, "s": 26621, "text": "In this article, we will learn about rem & em in CSS, how they differs from each other. The em and rem are the relative length CSS font-size units that can be used in CSS documents to make a specific element’s font size relative to its parents." }, { "code": null, "e": 27032, "s": 26866, "text": "The em is a CSS font-size unit relative to its directly linked parent, rem is in relation with the font-size of the root element which is basically the HTML element." }, { "code": null, "e": 27174, "s": 27032, "text": "There are lots of other CSS Units available as well. Let us understand the difference between em and rem with the help of a suitable example." }, { "code": null, "e": 27234, "s": 27174, "text": "em CSS Units: The em unit is relative to its parent’s size." }, { "code": null, "e": 27257, "s": 27234, "text": "1 em = size of parent" }, { "code": null, "e": 27294, "s": 27257, "text": "2 em = twice the size of the parent" }, { "code": null, "e": 27330, "s": 27294, "text": "0.5em = half the size of the parent" }, { "code": null, "e": 27467, "s": 27330, "text": "Example: This example demonstrates the use of the CSS em unit that specifies the font-size relative to the direct or its parent element." }, { "code": null, "e": 27472, "s": 27467, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> html { font-size: 15px; font-family: 'Courier New', Courier, monospace; } #grandPArent { font-size: 2em; } #parent { font-size: 2em; } #child { font-size: 2em; } #grandChild { font-size: 2em; } </style></head> <body> <p>Great Grand Parent - Base Font Size</p> <ul id=\"grandParent\"> <li>GrandParent 1</li> <ul id=\"garent\"> <li>Parent 1</li> <ul id=\"child\"> <li>Child 1</li> <ul id=\"grandChild\"> <li>GrandChild 1</li> <li>GrandChild 2</li> </ul> <li>Child 2</li> </ul> <li>Parent 2</li> </ul> <li>GrandParent 2</li> </ul></body> </html>", "e": 28323, "s": 27472, "text": null }, { "code": null, "e": 28480, "s": 28323, "text": "Explanation: As the elements get nested into one another, the relative size of elements keeps on growing exponentially at a rate of 2x in the above example." }, { "code": null, "e": 28709, "s": 28480, "text": "In this example, the child has a relative size of 2em (2x the font size of a parent) with respect to the parent which in turn is 2em (2x parent element’s parent) w.r.t. grandparent and is now 4 times the size of the grandparent." }, { "code": null, "e": 28717, "s": 28709, "text": "Output:" }, { "code": null, "e": 28729, "s": 28717, "text": "CSS em unit" }, { "code": null, "e": 28774, "s": 28729, "text": "Base Element (GreatGrandParent)’s Size: 15px" }, { "code": null, "e": 28800, "s": 28774, "text": "GrandParent1,2 Size: 30px" }, { "code": null, "e": 28822, "s": 28800, "text": "Parent 1,2 Size: 60px" }, { "code": null, "e": 28844, "s": 28822, "text": "Child 1,2 Size: 120px" }, { "code": null, "e": 28866, "s": 28844, "text": "GrandChild 1,2: 240px" }, { "code": null, "e": 28946, "s": 28866, "text": "rem CSS Units: The rem unit is relative to its base root parent element’s size." }, { "code": null, "e": 28990, "s": 28946, "text": "1 rem = size of root parent (HTML element)" }, { "code": null, "e": 29045, "s": 28990, "text": "2 rem = twice the size of root parent (HTML element)" }, { "code": null, "e": 29099, "s": 29045, "text": "0.5r em = half the size of root parent (HTML element)" }, { "code": null, "e": 29387, "s": 29099, "text": "In this case, as the elements get nested into one another the relative size of elements remains constant as every element’s size is proportional to the root HTML element and not its direct parent and hence properties are not transferred lower down to children and grandchildren elements." }, { "code": null, "e": 29651, "s": 29387, "text": "In this particular example, the parent has a relative size of 2rem (2x the font size of the root HTML element) w.r.t. root element which is the same as its child and its grandchild element and hence the size even after nesting at multiple levels remains constant." }, { "code": null, "e": 29773, "s": 29651, "text": "Example: This example demonstrates the use of the CSS rem unit that specifies the font-size relative to the root element." }, { "code": null, "e": 29778, "s": 29773, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> html { font-size: 15px; font-family: 'Courier New', Courier, monospace; } #grandParent { font-size: 2rem; } #parent { font-size: 2rem; } #child { font-size: 2rem; } #grandChild { font-size: 2rem; } </style></head> <body> <p>Great Grand Parent - Base Font Size</p> <ul id=\"grandParent\"> <li>GrandParent 1</li> <ul id=\"garent\"> <li>Parent 1</li> <ul id=\"child\"> <li>Child 1</li> <ul id=\"grandChild\"> <li>GrandChild 1</li> <li>GrandChild 2</li> </ul> <li>Child 2</li> </ul> <li>Parent 2</li> </ul> <li>GrandParent 2</li> </ul></body> </html>", "e": 30633, "s": 29778, "text": null }, { "code": null, "e": 30642, "s": 30633, "text": "Output: " }, { "code": null, "e": 30655, "s": 30642, "text": "CSS rem unit" }, { "code": null, "e": 30698, "s": 30655, "text": "Base( GreatGrandParent)’s Font Size : 15px" }, { "code": null, "e": 30763, "s": 30698, "text": "GrandParent1,2/Parent1,2/Child1,2/GrandChild1,2 Font Size = 30px" }, { "code": null, "e": 30845, "s": 30763, "text": "Note: Please notice the output of both the above examples to know the difference." }, { "code": null, "e": 30878, "s": 30845, "text": "Advantages of using rem over em:" }, { "code": null, "e": 31116, "s": 30878, "text": "While scaling our application to responsive layout using media query functionality, we can directly alter the base font-size of the root element and every child can directly scale altogether with just one media query on the root element." }, { "code": null, "e": 31259, "s": 31116, "text": "When the user has altered the default base font-size of any browser, our application scales well in this case with the usage of CSS rem units." }, { "code": null, "e": 31396, "s": 31259, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 31417, "s": 31396, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 31428, "s": 31417, "text": "CSS-Basics" }, { "code": null, "e": 31443, "s": 31428, "text": "CSS-Properties" }, { "code": null, "e": 31457, "s": 31443, "text": "CSS-Questions" }, { "code": null, "e": 31461, "s": 31457, "text": "CSS" }, { "code": null, "e": 31466, "s": 31461, "text": "HTML" }, { "code": null, "e": 31483, "s": 31466, "text": "Web Technologies" }, { "code": null, "e": 31488, "s": 31483, "text": "HTML" }, { "code": null, "e": 31586, "s": 31488, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31625, "s": 31586, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 31662, "s": 31625, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 31691, "s": 31662, "text": "Form validation using jQuery" }, { "code": null, "e": 31726, "s": 31691, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 31768, "s": 31726, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 31828, "s": 31768, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 31881, "s": 31828, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 31942, "s": 31881, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 31966, "s": 31942, "text": "REST API (Introduction)" } ]
Solidity - Inheritance - GeeksforGeeks
11 May, 2022 Inheritance is one of the most important features of the object-oriented programming language. It is a way of extending the functionality of a program, used to separate the code, reduces the dependency, and increases the re-usability of the existing code. Solidity supports inheritance between smart contracts, where multiple contracts can be inherited into a single contract. The contract from which other contracts inherit features is known as a base contract, while the contract which inherits the features is called a derived contract. Simply, they are referred to as parent-child contracts. The scope of inheritance in Solidity is limited to public and internal modifiers only. Some of the key highlights of Solidity are: A derived contract can access all non-private members including state variables and internal methods. But using this is not allowed. Function overriding is allowed provided function signature remains the same. In case of the difference of output parameters, the compilation will fail. We can call a super contract’s function using a super keyword or using a super contract name. In the case of multiple inheritances, function calls using super gives preference to most derived contracts. Solidity provides different types of inheritance. In Single or single level inheritance the functions and variables of one base contract are inherited to only one derived contract. Example: In the below example, the contract parent is inherited by the contract child, to demonstrate Single Inheritance. Solidity // Solidity program to// demonstrate// Single Inheritancepragma solidity >=0.4.22 <0.6.0; // Defining contract contract parent{ // Declaring internal // state variable uint internal sum; // Defining external function // to set value of internal // state variable sum function setValue() external { uint a = 10; uint b = 20; sum = a + b; } } // Defining child contract contract child is parent{ // Defining external function // to return value of // internal state variable sum function getValue( ) external view returns(uint) { return sum; } } // Defining calling contractcontract caller { // Creating child contract object child cc = new child(); // Defining function to call // setValue and getValue functions function testInheritance( ) public returns (uint) { cc.setValue(); return cc.getValue(); } } Output : It is very similar to single inheritance, but the difference is that it has levels of the relationship between the parent and the child. The child contract derived from a parent also acts as a parent for the contract which is derived from it. Example: In the below example, contract A is inherited by contract B, contract B is inherited by contract C, to demonstrate Multi-level Inheritance. Solidity // Solidity program to// demonstrate Multi-Level// Inheritancepragma solidity >=0.4.22 <0.6.0; // Defining parent contract Acontract A { // Declaring state variables string internal x; string a = "Geeks" ; string b = "For"; // Defining external function // to return concatenated string function getA() external{ x = string(abi.encodePacked(a, b)); } } // Defining child contract B// inheriting parent contract Acontract B is A { // Declaring state variables // of child contract B string public y; string c = "Geeks"; // Defining external function to // return concatenated string function getB() external payable returns( string memory){ y = string(abi.encodePacked(x, c)); } } // Defining child contract C// inheriting parent contract Acontract C is B { // Defining external function // returning concatenated string // generated in child contract B function getC() external view returns( string memory){ return y; } } // Defining calling contract contract caller { // Creating object of child C C cc = new C(); // Defining public function to // return final concatenated string function testInheritance( ) public returns ( string memory) { cc.getA(); cc.getB(); return cc.getC(); } } Output : In Hierarchical inheritance, a parent contract has more than one child contracts. It is mostly used when a common functionality is to be used in different places. Example: In the below example, contract A is inherited by contract B, contract A is inherited by contract C, thus demonstrating Hierarchical Inheritance. Solidity // Solidity program to demonstrate// Hierarchical Inheritancepragma solidity >=0.4.22 <0.6.0; // Defining parent contract A contract A { // Declaring internal // state variable string internal x; // Defining external function // to set value of // internalstate variable function getA() external { x = "GeeksForGeeks"; } // Declaring internal // state variable uint internal sum; // Defining external function // to set the value of // internal state variable sum function setA() external { uint a = 10; uint b = 20; sum = a + b; }} // Defining child contract B// inheriting parent contract Acontract B is A { // Defining external function to // return state variable x function getAstr( ) external view returns(string memory){ return x; } } // Defining child contract C// inheriting parent contract Acontract C is A { // Defining external function to // return state variable sum function getAValue( ) external view returns(uint){ return sum; } } // Defining calling contract contract caller { // Creating object of contract B B contractB = new B(); // Creating object of contract C C contractC = new C(); // Defining public function to // return values of state variables // x and sum function testInheritance( ) public returns ( string memory, uint) { return ( contractB.getAstr(), contractC.getAValue()); } } Output : In Multiple Inheritance, a single contract can be inherited from many contracts. A parent contract can have more than one child while a child contract can have more than one parent. Example: In the below example, contract A is inherited by contract B, contract C is inheriting contract A, and contract B, thus demonstrating Multiple Inheritance. Solidity // Solidity program to// demonstrate// Multiple Inheritancepragma solidity >=0.4.22 <0.6.0; // Defining contract A contract A { // Declaring internal // state variable string internal x; // Defining external function // to set value of // internal state variable x function setA() external { x = "GeeksForGeeks"; }} // Defining contract B contract B { // Declaring internal // state variable uint internal pow; // Defining external function // to set value of internal // state variable pow function setB() external { uint a = 2; uint b = 20; pow = a ** b; }} // Defining child contract C// inheriting parent contract// A and Bcontract C is A, B { // Defining external function // to return state variable x function getStr( ) external returns(string memory) { return x; } // Defining external function // to return state variable pow function getPow( ) external returns(uint) { return pow; } } // Defining calling contractcontract caller { // Creating object of contract C C contractC = new C(); // Defining public function to // return values from functions // getStr and getPow function testInheritance( ) public returns(string memory, uint) { contractC.setA(); contractC.setB(); return ( contractC.getStr(), contractC.getPow()); } } Output : adnanirshad158 sagartomar9927 Solidity OOPs-Concepts Blockchain Solidity Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Storage vs Memory in Solidity How to connect ReactJS with MetaMask ? How to Become a Blockchain Developer? Proof of Work (PoW) Consensus Difference between Public and Private blockchain Storage vs Memory in Solidity Mathematical Operations in Solidity How to Install Solidity in Windows? Introduction to Solidity Dynamic Arrays and its Operations in Solidity
[ { "code": null, "e": 25625, "s": 25597, "text": "\n11 May, 2022" }, { "code": null, "e": 26353, "s": 25625, "text": "Inheritance is one of the most important features of the object-oriented programming language. It is a way of extending the functionality of a program, used to separate the code, reduces the dependency, and increases the re-usability of the existing code. Solidity supports inheritance between smart contracts, where multiple contracts can be inherited into a single contract. The contract from which other contracts inherit features is known as a base contract, while the contract which inherits the features is called a derived contract. Simply, they are referred to as parent-child contracts. The scope of inheritance in Solidity is limited to public and internal modifiers only. Some of the key highlights of Solidity are: " }, { "code": null, "e": 26486, "s": 26353, "text": "A derived contract can access all non-private members including state variables and internal methods. But using this is not allowed." }, { "code": null, "e": 26638, "s": 26486, "text": "Function overriding is allowed provided function signature remains the same. In case of the difference of output parameters, the compilation will fail." }, { "code": null, "e": 26732, "s": 26638, "text": "We can call a super contract’s function using a super keyword or using a super contract name." }, { "code": null, "e": 26841, "s": 26732, "text": "In the case of multiple inheritances, function calls using super gives preference to most derived contracts." }, { "code": null, "e": 26891, "s": 26841, "text": "Solidity provides different types of inheritance." }, { "code": null, "e": 27022, "s": 26891, "text": "In Single or single level inheritance the functions and variables of one base contract are inherited to only one derived contract." }, { "code": null, "e": 27144, "s": 27022, "text": "Example: In the below example, the contract parent is inherited by the contract child, to demonstrate Single Inheritance." }, { "code": null, "e": 27153, "s": 27144, "text": "Solidity" }, { "code": "// Solidity program to// demonstrate// Single Inheritancepragma solidity >=0.4.22 <0.6.0; // Defining contract contract parent{ // Declaring internal // state variable uint internal sum; // Defining external function // to set value of internal // state variable sum function setValue() external { uint a = 10; uint b = 20; sum = a + b; } } // Defining child contract contract child is parent{ // Defining external function // to return value of // internal state variable sum function getValue( ) external view returns(uint) { return sum; } } // Defining calling contractcontract caller { // Creating child contract object child cc = new child(); // Defining function to call // setValue and getValue functions function testInheritance( ) public returns (uint) { cc.setValue(); return cc.getValue(); } }", "e": 28100, "s": 27153, "text": null }, { "code": null, "e": 28110, "s": 28100, "text": "Output : " }, { "code": null, "e": 28353, "s": 28110, "text": "It is very similar to single inheritance, but the difference is that it has levels of the relationship between the parent and the child. The child contract derived from a parent also acts as a parent for the contract which is derived from it." }, { "code": null, "e": 28502, "s": 28353, "text": "Example: In the below example, contract A is inherited by contract B, contract B is inherited by contract C, to demonstrate Multi-level Inheritance." }, { "code": null, "e": 28511, "s": 28502, "text": "Solidity" }, { "code": "// Solidity program to// demonstrate Multi-Level// Inheritancepragma solidity >=0.4.22 <0.6.0; // Defining parent contract Acontract A { // Declaring state variables string internal x; string a = \"Geeks\" ; string b = \"For\"; // Defining external function // to return concatenated string function getA() external{ x = string(abi.encodePacked(a, b)); } } // Defining child contract B// inheriting parent contract Acontract B is A { // Declaring state variables // of child contract B string public y; string c = \"Geeks\"; // Defining external function to // return concatenated string function getB() external payable returns( string memory){ y = string(abi.encodePacked(x, c)); } } // Defining child contract C// inheriting parent contract Acontract C is B { // Defining external function // returning concatenated string // generated in child contract B function getC() external view returns( string memory){ return y; } } // Defining calling contract contract caller { // Creating object of child C C cc = new C(); // Defining public function to // return final concatenated string function testInheritance( ) public returns ( string memory) { cc.getA(); cc.getB(); return cc.getC(); } }", "e": 29883, "s": 28511, "text": null }, { "code": null, "e": 29893, "s": 29883, "text": "Output : " }, { "code": null, "e": 30056, "s": 29893, "text": "In Hierarchical inheritance, a parent contract has more than one child contracts. It is mostly used when a common functionality is to be used in different places." }, { "code": null, "e": 30210, "s": 30056, "text": "Example: In the below example, contract A is inherited by contract B, contract A is inherited by contract C, thus demonstrating Hierarchical Inheritance." }, { "code": null, "e": 30219, "s": 30210, "text": "Solidity" }, { "code": "// Solidity program to demonstrate// Hierarchical Inheritancepragma solidity >=0.4.22 <0.6.0; // Defining parent contract A contract A { // Declaring internal // state variable string internal x; // Defining external function // to set value of // internalstate variable function getA() external { x = \"GeeksForGeeks\"; } // Declaring internal // state variable uint internal sum; // Defining external function // to set the value of // internal state variable sum function setA() external { uint a = 10; uint b = 20; sum = a + b; }} // Defining child contract B// inheriting parent contract Acontract B is A { // Defining external function to // return state variable x function getAstr( ) external view returns(string memory){ return x; } } // Defining child contract C// inheriting parent contract Acontract C is A { // Defining external function to // return state variable sum function getAValue( ) external view returns(uint){ return sum; } } // Defining calling contract contract caller { // Creating object of contract B B contractB = new B(); // Creating object of contract C C contractC = new C(); // Defining public function to // return values of state variables // x and sum function testInheritance( ) public returns ( string memory, uint) { return ( contractB.getAstr(), contractC.getAValue()); } }", "e": 31766, "s": 30219, "text": null }, { "code": null, "e": 31776, "s": 31766, "text": "Output : " }, { "code": null, "e": 31958, "s": 31776, "text": "In Multiple Inheritance, a single contract can be inherited from many contracts. A parent contract can have more than one child while a child contract can have more than one parent." }, { "code": null, "e": 32122, "s": 31958, "text": "Example: In the below example, contract A is inherited by contract B, contract C is inheriting contract A, and contract B, thus demonstrating Multiple Inheritance." }, { "code": null, "e": 32131, "s": 32122, "text": "Solidity" }, { "code": "// Solidity program to// demonstrate// Multiple Inheritancepragma solidity >=0.4.22 <0.6.0; // Defining contract A contract A { // Declaring internal // state variable string internal x; // Defining external function // to set value of // internal state variable x function setA() external { x = \"GeeksForGeeks\"; }} // Defining contract B contract B { // Declaring internal // state variable uint internal pow; // Defining external function // to set value of internal // state variable pow function setB() external { uint a = 2; uint b = 20; pow = a ** b; }} // Defining child contract C// inheriting parent contract// A and Bcontract C is A, B { // Defining external function // to return state variable x function getStr( ) external returns(string memory) { return x; } // Defining external function // to return state variable pow function getPow( ) external returns(uint) { return pow; } } // Defining calling contractcontract caller { // Creating object of contract C C contractC = new C(); // Defining public function to // return values from functions // getStr and getPow function testInheritance( ) public returns(string memory, uint) { contractC.setA(); contractC.setB(); return ( contractC.getStr(), contractC.getPow()); } }", "e": 33570, "s": 32131, "text": null }, { "code": null, "e": 33580, "s": 33570, "text": "Output : " }, { "code": null, "e": 33595, "s": 33580, "text": "adnanirshad158" }, { "code": null, "e": 33610, "s": 33595, "text": "sagartomar9927" }, { "code": null, "e": 33633, "s": 33610, "text": "Solidity OOPs-Concepts" }, { "code": null, "e": 33644, "s": 33633, "text": "Blockchain" }, { "code": null, "e": 33653, "s": 33644, "text": "Solidity" }, { "code": null, "e": 33751, "s": 33653, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33781, "s": 33751, "text": "Storage vs Memory in Solidity" }, { "code": null, "e": 33820, "s": 33781, "text": "How to connect ReactJS with MetaMask ?" }, { "code": null, "e": 33858, "s": 33820, "text": "How to Become a Blockchain Developer?" }, { "code": null, "e": 33888, "s": 33858, "text": "Proof of Work (PoW) Consensus" }, { "code": null, "e": 33937, "s": 33888, "text": "Difference between Public and Private blockchain" }, { "code": null, "e": 33967, "s": 33937, "text": "Storage vs Memory in Solidity" }, { "code": null, "e": 34003, "s": 33967, "text": "Mathematical Operations in Solidity" }, { "code": null, "e": 34039, "s": 34003, "text": "How to Install Solidity in Windows?" }, { "code": null, "e": 34064, "s": 34039, "text": "Introduction to Solidity" } ]
Multidimensional Arrays in C / C++ - GeeksforGeeks
20 Oct, 2021 Array- Basics In C/C++, we can define multidimensional arrays in simple words as an array of arrays. Data in multidimensional arrays are stored in tabular form (in row-major order). The general form of declaring N-dimensional arrays: data_type array_name[size1][size2]....[sizeN]; data_type: Type of data to be stored in the array. Here data_type is valid C/C++ data type array_name: Name of the array size1, size2,... ,sizeN: Sizes of the dimensions Examples: Two dimensional array: int two_d[10][20]; Three dimensional array: int three_d[10][20][30]; Size of multidimensional arrays The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int x[10][20] can store total (10*20) = 200 elements. Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements. 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. Two – dimensional array is the simplest form of a multidimensional array. We can see a two – dimensional array as an array of one – dimensional array for easier understanding. The basic form of declaring a two-dimensional array of size x, y: Syntax: data_type array_name[x][y]; data_type: Type of data to be stored. Valid C/C++ data type. We can declare a two-dimensional integer array say ‘x’ of size 10,20 as: int x[10][20]; Elements in two-dimensional arrays are commonly referred to by x[i][j] where i is the row number and ‘j’ is the column number. A two – dimensional array can be seen as a table with ‘x’ rows and ‘y’ columns where the row number ranges from 0 to (x-1) and column number ranges from 0 to (y-1). A two – dimensional array ‘x’ with 3 rows and 3 columns is shown below: Initializing Two – Dimensional Arrays: There are two ways in which a Two-Dimensional array can be initialized. First Method: int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11} The above array has 3 rows and 4 columns. The elements in the braces from left to right are stored in the table also from left to right. The elements will be filled in the array in order, the first 4 elements from the left in the first row, the next 4 elements in the second row, and so on.Better Method: int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}}; This type of initialization makes use of nested braces. Each set of inner braces represents one row. In the above example, there is a total of three rows so there are three sets of inner braces.Accessing Elements of Two-Dimensional Arrays: Elements in Two-Dimensional arrays are accessed using the row indexes and column indexes. Example: int x[2][1]; The above example represents the element present in the third row and second column.Note: In arrays, if the size of an array is N. Its index will be from 0 to N-1. Therefore, for row index 2 row number is 2+1 = 3.To output all the elements of a Two-Dimensional array we can use nested for loops. We will require two for loops. One to traverse the rows and another to traverse columns. CPP // C++ Program to print the elements of a// Two-Dimensional array#include<iostream>using namespace std; int main(){ // an array with 3 rows and 2 columns. int x[3][2] = {{0,1}, {2,3}, {4,5}}; // output each array element's value for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { cout << "Element at x[" << i << "][" << j << "]: "; cout << x[i][j]<<endl; } } return 0;} Output: Element at x[0][0]: 0 Element at x[0][1]: 1 Element at x[1][0]: 2 Element at x[1][1]: 3 Element at x[2][0]: 4 Element at x[2][1]: 5 Initializing Three-Dimensional Array: Initialization in a Three-Dimensional array is the same as that of Two-dimensional arrays. The difference is as the number of dimensions increases so the number of nested braces will also increase. Method 1: int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23}; Better Method: int x[2][3][4] = { { {0,1,2,3}, {4,5,6,7}, {8,9,10,11} }, { {12,13,14,15}, {16,17,18,19}, {20,21,22,23} } }; Accessing elements in Three-Dimensional Arrays: Accessing elements in Three-Dimensional Arrays is also similar to that of Two-Dimensional Arrays. The difference is we have to use three loops instead of two loops for one additional dimension in Three-dimensional Arrays. CPP // C++ program to print elements of Three-Dimensional// Array#include<iostream>using namespace std; int main(){ // initializing the 3-dimensional array int x[2][3][2] = { { {0,1}, {2,3}, {4,5} }, { {6,7}, {8,9}, {10,11} } }; // output each element's value for (int i = 0; i < 2; ++i) { for (int j = 0; j < 3; ++j) { for (int k = 0; k < 2; ++k) { cout << "Element at x[" << i << "][" << j << "][" << k << "] = " << x[i][j][k] << endl; } } } return 0;} Output: Element at x[0][0][0] = 0 Element at x[0][0][1] = 1 Element at x[0][1][0] = 2 Element at x[0][1][1] = 3 Element at x[0][2][0] = 4 Element at x[0][2][1] = 5 Element at x[1][0][0] = 6 Element at x[1][0][1] = 7 Element at x[1][1][0] = 8 Element at x[1][1][1] = 9 Element at x[1][2][0] = 10 Element at x[1][2][1] = 11 In similar ways, we can create arrays with any number of dimensions. However, the complexity also increases as the number of dimensions increases. The most used multidimensional array is the Two-Dimensional Array. YouTubeGeeksforGeeks507K subscribersC++ Programming Language Tutorial | Multidimensional Arrays in C++ | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:42•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=eVSbSeJPkDA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ?list=PLqM7alHXFySGg6GSRmE2INI4k8fPH5qVB This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Ansh Khurana RishabhPrabhu pujasingg43 CBSE - Class 11 school-programming C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. std::sort() in C++ STL Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() Bitwise Operators in C/C++ Substring in C++ Converting Strings to Numbers in C/C++ Vector in C++ STL Initialize a vector in C++ (6 different ways) std::sort() in C++ STL Bitwise Operators in C/C++ Virtual Function in C++
[ { "code": null, "e": 28205, "s": 28177, "text": "\n20 Oct, 2021" }, { "code": null, "e": 28441, "s": 28205, "text": "Array- Basics In C/C++, we can define multidimensional arrays in simple words as an array of arrays. Data in multidimensional arrays are stored in tabular form (in row-major order). The general form of declaring N-dimensional arrays: " }, { "code": null, "e": 28672, "s": 28441, "text": "data_type array_name[size1][size2]....[sizeN];\n\ndata_type: Type of data to be stored in the array. \n Here data_type is valid C/C++ data type\narray_name: Name of the array\nsize1, size2,... ,sizeN: Sizes of the dimensions" }, { "code": null, "e": 28684, "s": 28672, "text": "Examples: " }, { "code": null, "e": 28777, "s": 28684, "text": "Two dimensional array:\nint two_d[10][20];\n\nThree dimensional array:\nint three_d[10][20][30];" }, { "code": null, "e": 28811, "s": 28779, "text": "Size of multidimensional arrays" }, { "code": null, "e": 29106, "s": 28811, "text": "The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int x[10][20] can store total (10*20) = 200 elements. Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements. " }, { "code": null, "e": 29115, "s": 29106, "text": "Chapters" }, { "code": null, "e": 29142, "s": 29115, "text": "descriptions off, selected" }, { "code": null, "e": 29192, "s": 29142, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 29215, "s": 29192, "text": "captions off, selected" }, { "code": null, "e": 29223, "s": 29215, "text": "English" }, { "code": null, "e": 29247, "s": 29223, "text": "This is a modal window." }, { "code": null, "e": 29316, "s": 29247, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 29338, "s": 29316, "text": "End of dialog window." }, { "code": null, "e": 29516, "s": 29338, "text": "Two – dimensional array is the simplest form of a multidimensional array. We can see a two – dimensional array as an array of one – dimensional array for easier understanding. " }, { "code": null, "e": 29592, "s": 29516, "text": "The basic form of declaring a two-dimensional array of size x, y: Syntax: " }, { "code": null, "e": 29681, "s": 29592, "text": "data_type array_name[x][y];\ndata_type: Type of data to be stored. Valid C/C++ data type." }, { "code": null, "e": 29756, "s": 29681, "text": "We can declare a two-dimensional integer array say ‘x’ of size 10,20 as: " }, { "code": null, "e": 29771, "s": 29756, "text": "int x[10][20];" }, { "code": null, "e": 29898, "s": 29771, "text": "Elements in two-dimensional arrays are commonly referred to by x[i][j] where i is the row number and ‘j’ is the column number." }, { "code": null, "e": 30137, "s": 29898, "text": "A two – dimensional array can be seen as a table with ‘x’ rows and ‘y’ columns where the row number ranges from 0 to (x-1) and column number ranges from 0 to (y-1). A two – dimensional array ‘x’ with 3 rows and 3 columns is shown below: " }, { "code": null, "e": 30266, "s": 30139, "text": "Initializing Two – Dimensional Arrays: There are two ways in which a Two-Dimensional array can be initialized. First Method: " }, { "code": null, "e": 30326, "s": 30266, "text": "int x[3][4] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 , 9 , 10 , 11}" }, { "code": null, "e": 30633, "s": 30326, "text": "The above array has 3 rows and 4 columns. The elements in the braces from left to right are stored in the table also from left to right. The elements will be filled in the array in order, the first 4 elements from the left in the first row, the next 4 elements in the second row, and so on.Better Method: " }, { "code": null, "e": 30684, "s": 30633, "text": "int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};" }, { "code": null, "e": 31025, "s": 30684, "text": "This type of initialization makes use of nested braces. Each set of inner braces represents one row. In the above example, there is a total of three rows so there are three sets of inner braces.Accessing Elements of Two-Dimensional Arrays: Elements in Two-Dimensional arrays are accessed using the row indexes and column indexes. Example: " }, { "code": null, "e": 31038, "s": 31025, "text": "int x[2][1];" }, { "code": null, "e": 31425, "s": 31038, "text": "The above example represents the element present in the third row and second column.Note: In arrays, if the size of an array is N. Its index will be from 0 to N-1. Therefore, for row index 2 row number is 2+1 = 3.To output all the elements of a Two-Dimensional array we can use nested for loops. We will require two for loops. One to traverse the rows and another to traverse columns. " }, { "code": null, "e": 31429, "s": 31425, "text": "CPP" }, { "code": "// C++ Program to print the elements of a// Two-Dimensional array#include<iostream>using namespace std; int main(){ // an array with 3 rows and 2 columns. int x[3][2] = {{0,1}, {2,3}, {4,5}}; // output each array element's value for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { cout << \"Element at x[\" << i << \"][\" << j << \"]: \"; cout << x[i][j]<<endl; } } return 0;}", "e": 31890, "s": 31429, "text": null }, { "code": null, "e": 31900, "s": 31890, "text": "Output: " }, { "code": null, "e": 32032, "s": 31900, "text": "Element at x[0][0]: 0\nElement at x[0][1]: 1\nElement at x[1][0]: 2\nElement at x[1][1]: 3\nElement at x[2][0]: 4\nElement at x[2][1]: 5" }, { "code": null, "e": 32284, "s": 32036, "text": "Initializing Three-Dimensional Array: Initialization in a Three-Dimensional array is the same as that of Two-dimensional arrays. The difference is as the number of dimensions increases so the number of nested braces will also increase. Method 1: " }, { "code": null, "e": 32424, "s": 32284, "text": "int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, \n 11, 12, 13, 14, 15, 16, 17, 18, 19,\n 20, 21, 22, 23};" }, { "code": null, "e": 32441, "s": 32424, "text": "Better Method: " }, { "code": null, "e": 32560, "s": 32441, "text": "int x[2][3][4] = \n { \n { {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },\n { {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }\n };" }, { "code": null, "e": 32832, "s": 32560, "text": "Accessing elements in Three-Dimensional Arrays: Accessing elements in Three-Dimensional Arrays is also similar to that of Two-Dimensional Arrays. The difference is we have to use three loops instead of two loops for one additional dimension in Three-dimensional Arrays. " }, { "code": null, "e": 32836, "s": 32832, "text": "CPP" }, { "code": "// C++ program to print elements of Three-Dimensional// Array#include<iostream>using namespace std; int main(){ // initializing the 3-dimensional array int x[2][3][2] = { { {0,1}, {2,3}, {4,5} }, { {6,7}, {8,9}, {10,11} } }; // output each element's value for (int i = 0; i < 2; ++i) { for (int j = 0; j < 3; ++j) { for (int k = 0; k < 2; ++k) { cout << \"Element at x[\" << i << \"][\" << j << \"][\" << k << \"] = \" << x[i][j][k] << endl; } } } return 0;}", "e": 33438, "s": 32836, "text": null }, { "code": null, "e": 33448, "s": 33438, "text": "Output: " }, { "code": null, "e": 33762, "s": 33448, "text": "Element at x[0][0][0] = 0\nElement at x[0][0][1] = 1\nElement at x[0][1][0] = 2\nElement at x[0][1][1] = 3\nElement at x[0][2][0] = 4\nElement at x[0][2][1] = 5\nElement at x[1][0][0] = 6\nElement at x[1][0][1] = 7\nElement at x[1][1][0] = 8\nElement at x[1][1][1] = 9\nElement at x[1][2][0] = 10\nElement at x[1][2][1] = 11" }, { "code": null, "e": 33978, "s": 33762, "text": "In similar ways, we can create arrays with any number of dimensions. However, the complexity also increases as the number of dimensions increases. The most used multidimensional array is the Two-Dimensional Array. " }, { "code": null, "e": 34843, "s": 33978, "text": "YouTubeGeeksforGeeks507K subscribersC++ Programming Language Tutorial | Multidimensional Arrays in C++ | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:42•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=eVSbSeJPkDA\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 34886, "s": 34843, "text": "?list=PLqM7alHXFySGg6GSRmE2INI4k8fPH5qVB " }, { "code": null, "e": 35184, "s": 34886, "text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 35311, "s": 35184, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 35326, "s": 35313, "text": "Ansh Khurana" }, { "code": null, "e": 35340, "s": 35326, "text": "RishabhPrabhu" }, { "code": null, "e": 35352, "s": 35340, "text": "pujasingg43" }, { "code": null, "e": 35368, "s": 35352, "text": "CBSE - Class 11" }, { "code": null, "e": 35387, "s": 35368, "text": "school-programming" }, { "code": null, "e": 35398, "s": 35387, "text": "C Language" }, { "code": null, "e": 35402, "s": 35398, "text": "C++" }, { "code": null, "e": 35406, "s": 35402, "text": "CPP" }, { "code": null, "e": 35504, "s": 35406, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35527, "s": 35504, "text": "std::sort() in C++ STL" }, { "code": null, "e": 35605, "s": 35527, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 35632, "s": 35605, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 35649, "s": 35632, "text": "Substring in C++" }, { "code": null, "e": 35688, "s": 35649, "text": "Converting Strings to Numbers in C/C++" }, { "code": null, "e": 35706, "s": 35688, "text": "Vector in C++ STL" }, { "code": null, "e": 35752, "s": 35706, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 35775, "s": 35752, "text": "std::sort() in C++ STL" }, { "code": null, "e": 35802, "s": 35775, "text": "Bitwise Operators in C/C++" } ]
java.rmi.RMISecurityManager Class in Java - GeeksforGeeks
16 Sep, 2021 The RMISecurityManager enforces the security policy for classes that are loaded as stubs for remote objects, by overriding all of the relevant access-check methods from the SecurityManager. By default, stub objects are only allowed to perform class definition and class access operations. Note: If the local security manager is not an RMISecurityManager using the System.setSecurityManager() method Then stub classes will only be loadable from the local file system. java.lang.Object java.lang.SecurityManager java.rmi.RMISecurityManager Syntax: public class RMISecurityManager extends SecurityManager Note: A subclass of SecurityManager used by RMI applications that use downloaded code. RMI’s class loader will not download any classes from remote locations if no security manager has been set. RMISecurityManager does not apply to applets, which run under the protection of their browser’s security manager. RMISecurityManager implements a policy that is no different than the policy implemented by SecurityManager. Therefore an RMI application should use the SecurityManager class or another application-specific SecurityManager implementation instead of this class. How to incorporate the Security Manager class? To use a SecurityManager in your application, add the following statement to your code (it needs to be executed before RMI can download code from remote hosts, so it most likely needs to appear in the main method of your application) Syntax: System.setSecurityManager(new SecurityManager()); RMISecurityManager implements a policy identical to the policy implemented by SecurityManager. RMI applications should use the SecurityManager class or another appropriate SecurityManager implementation instead of this class. RMI’s class loader will download classes from remote locations only if a security manager has been set. Now let us move forward with the constructor of this class as follows: RMISecurityManager(): Constructs a new RMISecurityManager Implementation: if (System.getSecurityManager() == null) { // Setting the RMISecurityManager on System System.setSecurityManager(new SecurityManager()); } Applets typically run in a container that already has a security manager, so there is generally no need for applets to set a security manager. If you have a standalone application, you might need to set a SecurityManager in order to enable class downloading. This can be done by adding the following to your code. (It needs to be executed before RMI can download code from remote hosts, so it most likely needs to appear in the main method of your application as can better be perceived from the below illustrations. Illustration 1: // Protected synchronized method protected static synchronized void setSecurityManager() { if (System.getSecurityManager() == null) { // Setting the RMISecurityManager on System System.setSecurityManager(new RMISecurityManager()); } } Illustration 2: // Synchronized method synchronized static void ensureSecurityManager() { if (System.getSecurityManager() == null) { // Setting the RMISecurityManager on System System.setSecurityManager(new RMISecurityManager()); } } Illustration 3: // Protected synchronized method protected static synchronized void setSecurityManager() { if (System.getSecurityManager() == null) { // Setting the RMISecurityManager on System System.setSecurityManager(new RMISecurityManager()); } } Example Java // Java Program to Illustrate RMISecurityManager Class// Via creating Registry and Rebinding Service // Importing required classesimport java.lang.Object;import java.lang.SecurityManager;import java.rmi.RMISecurityManager; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Setting the RMISecurityManager on System System.setSecurityManager( new RMISecurityManager()); RmiService service = new RmiServiceImpl(); // First we will be creating registry // using createRegistry() method LocateRegistry.createRegistry(6600); // Now rebinding the service // using rebind method Naming.rebind( "rmi://127.0.0.1:6600/PersonService", service); // Display message on the console for // successful execution of the program System.out.println("Service Start!"); } // Catch block to handle exceptions catch (Exception e) { // Printing the line number where exception // occured using printStackTrace() method e.printStackTrace(); } }} Output: Service Start! On console, we will land up to a display message as shown above. Java-Classes Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n16 Sep, 2021" }, { "code": null, "e": 25515, "s": 25225, "text": "The RMISecurityManager enforces the security policy for classes that are loaded as stubs for remote objects, by overriding all of the relevant access-check methods from the SecurityManager. By default, stub objects are only allowed to perform class definition and class access operations. " }, { "code": null, "e": 25522, "s": 25515, "text": "Note: " }, { "code": null, "e": 25626, "s": 25522, "text": "If the local security manager is not an RMISecurityManager using the System.setSecurityManager() method" }, { "code": null, "e": 25694, "s": 25626, "text": "Then stub classes will only be loadable from the local file system." }, { "code": null, "e": 25765, "s": 25694, "text": "java.lang.Object\njava.lang.SecurityManager\njava.rmi.RMISecurityManager" }, { "code": null, "e": 25773, "s": 25765, "text": "Syntax:" }, { "code": null, "e": 25830, "s": 25773, "text": "public class RMISecurityManager \nextends SecurityManager" }, { "code": null, "e": 25918, "s": 25830, "text": "Note: A subclass of SecurityManager used by RMI applications that use downloaded code. " }, { "code": null, "e": 26400, "s": 25918, "text": "RMI’s class loader will not download any classes from remote locations if no security manager has been set. RMISecurityManager does not apply to applets, which run under the protection of their browser’s security manager. RMISecurityManager implements a policy that is no different than the policy implemented by SecurityManager. Therefore an RMI application should use the SecurityManager class or another application-specific SecurityManager implementation instead of this class." }, { "code": null, "e": 26448, "s": 26400, "text": "How to incorporate the Security Manager class? " }, { "code": null, "e": 26682, "s": 26448, "text": "To use a SecurityManager in your application, add the following statement to your code (it needs to be executed before RMI can download code from remote hosts, so it most likely needs to appear in the main method of your application)" }, { "code": null, "e": 26690, "s": 26682, "text": "Syntax:" }, { "code": null, "e": 26740, "s": 26690, "text": "System.setSecurityManager(new SecurityManager());" }, { "code": null, "e": 27070, "s": 26740, "text": "RMISecurityManager implements a policy identical to the policy implemented by SecurityManager. RMI applications should use the SecurityManager class or another appropriate SecurityManager implementation instead of this class. RMI’s class loader will download classes from remote locations only if a security manager has been set." }, { "code": null, "e": 27141, "s": 27070, "text": "Now let us move forward with the constructor of this class as follows:" }, { "code": null, "e": 27199, "s": 27141, "text": "RMISecurityManager(): Constructs a new RMISecurityManager" }, { "code": null, "e": 27215, "s": 27199, "text": "Implementation:" }, { "code": null, "e": 27364, "s": 27215, "text": "if (System.getSecurityManager() == null) \n{\n // Setting the RMISecurityManager on System\n System.setSecurityManager(new SecurityManager());\n} " }, { "code": null, "e": 27881, "s": 27364, "text": "Applets typically run in a container that already has a security manager, so there is generally no need for applets to set a security manager. If you have a standalone application, you might need to set a SecurityManager in order to enable class downloading. This can be done by adding the following to your code. (It needs to be executed before RMI can download code from remote hosts, so it most likely needs to appear in the main method of your application as can better be perceived from the below illustrations." }, { "code": null, "e": 27897, "s": 27881, "text": "Illustration 1:" }, { "code": null, "e": 28162, "s": 27897, "text": "// Protected synchronized method\nprotected static synchronized void setSecurityManager() \n{\n if (System.getSecurityManager() == null) \n {\n // Setting the RMISecurityManager on System\n System.setSecurityManager(new RMISecurityManager());\n }\n}" }, { "code": null, "e": 28178, "s": 28162, "text": "Illustration 2:" }, { "code": null, "e": 28426, "s": 28178, "text": "// Synchronized method\nsynchronized static void ensureSecurityManager() \n{\n if (System.getSecurityManager() == null) \n {\n // Setting the RMISecurityManager on System\n System.setSecurityManager(new RMISecurityManager());\n }\n}" }, { "code": null, "e": 28444, "s": 28426, "text": "Illustration 3: " }, { "code": null, "e": 28709, "s": 28444, "text": "// Protected synchronized method\nprotected static synchronized void setSecurityManager() \n{\n if (System.getSecurityManager() == null) \n {\n // Setting the RMISecurityManager on System\n System.setSecurityManager(new RMISecurityManager());\n }\n}" }, { "code": null, "e": 28717, "s": 28709, "text": "Example" }, { "code": null, "e": 28722, "s": 28717, "text": "Java" }, { "code": "// Java Program to Illustrate RMISecurityManager Class// Via creating Registry and Rebinding Service // Importing required classesimport java.lang.Object;import java.lang.SecurityManager;import java.rmi.RMISecurityManager; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Setting the RMISecurityManager on System System.setSecurityManager( new RMISecurityManager()); RmiService service = new RmiServiceImpl(); // First we will be creating registry // using createRegistry() method LocateRegistry.createRegistry(6600); // Now rebinding the service // using rebind method Naming.rebind( \"rmi://127.0.0.1:6600/PersonService\", service); // Display message on the console for // successful execution of the program System.out.println(\"Service Start!\"); } // Catch block to handle exceptions catch (Exception e) { // Printing the line number where exception // occured using printStackTrace() method e.printStackTrace(); } }}", "e": 30009, "s": 28722, "text": null }, { "code": null, "e": 30018, "s": 30009, "text": "Output: " }, { "code": null, "e": 30033, "s": 30018, "text": "Service Start!" }, { "code": null, "e": 30098, "s": 30033, "text": "On console, we will land up to a display message as shown above." }, { "code": null, "e": 30111, "s": 30098, "text": "Java-Classes" }, { "code": null, "e": 30118, "s": 30111, "text": "Picked" }, { "code": null, "e": 30123, "s": 30118, "text": "Java" }, { "code": null, "e": 30128, "s": 30123, "text": "Java" }, { "code": null, "e": 30226, "s": 30128, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30241, "s": 30226, "text": "Stream In Java" }, { "code": null, "e": 30262, "s": 30241, "text": "Constructors in Java" }, { "code": null, "e": 30281, "s": 30262, "text": "Exceptions in Java" }, { "code": null, "e": 30311, "s": 30281, "text": "Functional Interfaces in Java" }, { "code": null, "e": 30357, "s": 30311, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 30374, "s": 30357, "text": "Generics in Java" }, { "code": null, "e": 30395, "s": 30374, "text": "Introduction to Java" }, { "code": null, "e": 30438, "s": 30395, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 30474, "s": 30438, "text": "Internal Working of HashMap in Java" } ]
Python - Validate String date format - GeeksforGeeks
11 Aug, 2021 Given a date format and a string date, the task is to write a python program to check if the date is valid and matches the format. Examples: Input : test_str = ’04-01-1997′, format = “%d-%m-%Y” Output : True Explanation : Formats match with date. Input : test_str = ’04-14-1997′, format = “%d-%m-%Y” Output : False Explanation : Month cannot be 14. In this, the function, strptime usually used for conversion of string date to datetime object, is used as when it doesn’t match the format or date, raises the ValueError, and hence can be used to compute for validity. Python3 # Python3 code to demonstrate working of# Validate String date format# Using strptime()from datetime import datetime # initializing stringtest_str = '04-01-1997' # printing original stringprint("The original string is : " + str(test_str)) # initializing formatformat = "%d-%m-%Y" # checking if format matches the dateres = True # using try-except to check for truth valuetry: res = bool(datetime.strptime(test_str, format))except ValueError: res = False # printing resultprint("Does date match format? : " + str(res)) Output: The original string is : 04-01-1997 Does date match format? : True In this, we check for validated format using different inbuilt function, dateutil.parser. This doesn’t need the format to detect for a date. Python3 # Python3 code to demonstrate working of# Validate String date format# Using dateutil.parser.parsefrom dateutil import parser # initializing stringtest_str = '04-01-1997' # printing original stringprint("The original string is : " + str(test_str)) # initializing formatformat = "%d-%m-%Y" # checking if format matches the dateres = True # using try-except to check for truth valuetry: res = bool(parser.parse(test_str))except ValueError: res = False # printing resultprint("Does date match format? : " + str(res)) Output: The original string is : 04-01-1997 Does date match format? : True kk773572498 Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n11 Aug, 2021" }, { "code": null, "e": 25668, "s": 25537, "text": "Given a date format and a string date, the task is to write a python program to check if the date is valid and matches the format." }, { "code": null, "e": 25678, "s": 25668, "text": "Examples:" }, { "code": null, "e": 25731, "s": 25678, "text": "Input : test_str = ’04-01-1997′, format = “%d-%m-%Y”" }, { "code": null, "e": 25745, "s": 25731, "text": "Output : True" }, { "code": null, "e": 25784, "s": 25745, "text": "Explanation : Formats match with date." }, { "code": null, "e": 25837, "s": 25784, "text": "Input : test_str = ’04-14-1997′, format = “%d-%m-%Y”" }, { "code": null, "e": 25852, "s": 25837, "text": "Output : False" }, { "code": null, "e": 25886, "s": 25852, "text": "Explanation : Month cannot be 14." }, { "code": null, "e": 26104, "s": 25886, "text": "In this, the function, strptime usually used for conversion of string date to datetime object, is used as when it doesn’t match the format or date, raises the ValueError, and hence can be used to compute for validity." }, { "code": null, "e": 26112, "s": 26104, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Validate String date format# Using strptime()from datetime import datetime # initializing stringtest_str = '04-01-1997' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing formatformat = \"%d-%m-%Y\" # checking if format matches the dateres = True # using try-except to check for truth valuetry: res = bool(datetime.strptime(test_str, format))except ValueError: res = False # printing resultprint(\"Does date match format? : \" + str(res))", "e": 26636, "s": 26112, "text": null }, { "code": null, "e": 26644, "s": 26636, "text": "Output:" }, { "code": null, "e": 26711, "s": 26644, "text": "The original string is : 04-01-1997\nDoes date match format? : True" }, { "code": null, "e": 26852, "s": 26711, "text": "In this, we check for validated format using different inbuilt function, dateutil.parser. This doesn’t need the format to detect for a date." }, { "code": null, "e": 26860, "s": 26852, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Validate String date format# Using dateutil.parser.parsefrom dateutil import parser # initializing stringtest_str = '04-01-1997' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing formatformat = \"%d-%m-%Y\" # checking if format matches the dateres = True # using try-except to check for truth valuetry: res = bool(parser.parse(test_str))except ValueError: res = False # printing resultprint(\"Does date match format? : \" + str(res))", "e": 27380, "s": 26860, "text": null }, { "code": null, "e": 27388, "s": 27380, "text": "Output:" }, { "code": null, "e": 27455, "s": 27388, "text": "The original string is : 04-01-1997\nDoes date match format? : True" }, { "code": null, "e": 27467, "s": 27455, "text": "kk773572498" }, { "code": null, "e": 27474, "s": 27467, "text": "Python" }, { "code": null, "e": 27490, "s": 27474, "text": "Python Programs" }, { "code": null, "e": 27588, "s": 27490, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27620, "s": 27588, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27662, "s": 27620, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27704, "s": 27662, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27760, "s": 27704, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27787, "s": 27760, "text": "Python Classes and Objects" }, { "code": null, "e": 27809, "s": 27787, "text": "Defaultdict in Python" }, { "code": null, "e": 27848, "s": 27809, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27894, "s": 27848, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27932, "s": 27894, "text": "Python | Convert a list to dictionary" } ]
Find the integer points (x, y) with Manhattan distance atleast N - GeeksforGeeks
03 Mar, 2022 Given a number N, the task is to find the integer points (x, y) such that 0 <= x, y <= N and Manhattan distance between any two points will be atleast N.Examples: Input: N = 3 Output: (0, 0) (0, 3) (3, 0) (3, 3) Input: N = 4 Output: (0, 0) (0, 4) (4, 0) (4, 4) (2, 2) Approach: Manhattan Distance between two points (x1, y1) and (x2, y2) is: |x1 – x2| + |y1 – y2| Here for all pair of points this distance will be atleast N. As 0 <= x <= N and 0 <= y <= N so we can imagine a square of side length N whose bottom left corner is (0, 0) and top right corner is (N, N). So if we place 4 points in this corner then Manhattan distance will be atleast N. Now as we have to maximize the number of the point we have to check is there any available point inside the square. If N is even then middle point of the square which is (N/2, N/2) is integer point, otherwise, it will be float value as N/2 is not a integer when N is odd. So the only available position is the middle point and we can put a point there only if N is even. So number of points will be 4 if N is odd and if N is even then the number of points will be 5. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ code to Find the integer points (x, y)// with Manhattan distance atleast N #include <bits/stdc++.h>using namespace std; // C++ function to find all possible pointvector<pair<int, int> > FindPoints(int n){ vector<pair<int, int> > v; // Find all 4 corners of the square // whose side length is n v.push_back({ 0, 0 }); v.push_back({ 0, n }); v.push_back({ n, 0 }); v.push_back({ n, n }); // If n is even then the middle point // of the square will be an integer, // so we will take that point if (n % 2 == 0) v.push_back({ n / 2, n / 2 }); return v;} // Driver Codeint main(){ int N = 8; vector<pair<int, int> > v = FindPoints(N); // Printing all possible points for (auto i : v) { cout << "(" << i.first << ", " << i.second << ") "; } return 0;} // Java code to Find the integer points (x, y)// with Manhattan distance atleast Nimport java.util.*; class GFG{ static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // Java function to find all possible pointstatic Vector<pair> FindPoints(int n){ Vector<pair> v = new Vector<pair>(); // Find all 4 corners of the square // whose side length is n v.add(new pair( 0, 0 )); v.add(new pair( 0, n )); v.add(new pair( n, 0 )); v.add(new pair( n, n )); // If n is even then the middle point // of the square will be an integer, // so we will take that point if (n % 2 == 0) v.add(new pair( n / 2, n / 2 )); return v;} // Driver Codepublic static void main(String[] args){ int N = 8; Vector<pair > v = FindPoints(N); // Printing all possible points for (pair i : v) { System.out.print("(" + i.first + ", " + i.second + ") "); }}} // This code is contributed by PrinciRaj1992 # Python3 code to Find the integer points (x, y)# with Manhattan distance atleast N # function to find all possible pointdef FindPoints(n) : v = []; # Find all 4 corners of the square # whose side length is n v.append([ 0, 0 ]); v.append([ 0, n ]); v.append([ n, 0 ]); v.append([ n, n ]); # If n is even then the middle point # of the square will be an integer, # so we will take that point if (n % 2 == 0) : v.append([ n // 2, n // 2 ]); return v; # Driver Codeif __name__ == "__main__" : N = 8; v = FindPoints(N); # Printing all possible points for element in v : print("(", element[0], ",", element[1], ")", end = " "); # This code is contributed by AnkitRai01 // C# code to Find the integer points (x, y)// with Manhattan distance atleast Nusing System;using System.Collections.Generic; class GFG{ class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // Function to find all possible pointstatic List<pair> FindPoints(int n){ List<pair> v = new List<pair>(); // Find all 4 corners of the square // whose side length is n v.Add(new pair( 0, 0 )); v.Add(new pair( 0, n )); v.Add(new pair( n, 0 )); v.Add(new pair( n, n )); // If n is even then the middle point // of the square will be an integer, // so we will take that point if (n % 2 == 0) v.Add(new pair( n / 2, n / 2 )); return v;} // Driver Codepublic static void Main(String[] args){ int N = 8; List<pair > v = FindPoints(N); // Printing all possible points foreach (pair i in v) { Console.Write("(" + i.first + ", " + i.second + ") "); }}} // This code is contributed by Rajput-Ji <script> // Javascript code to Find the integer points (x, y)// with Manhattan distance atleast N // C++ function to find all possible pointfunction FindPoints(n){ var v = []; // Find all 4 corners of the square // whose side length is n v.push([ 0, 0 ]); v.push([ 0, n ]); v.push([ n, 0 ]); v.push([ n, n ]); // If n is even then the middle point // of the square will be an integer, // so we will take that point if (n % 2 == 0) v.push([ n / 2, n / 2 ]); return v;} // Driver Codevar N = 8;var v = FindPoints(N);// Printing all possible pointsv.forEach(i => { document.write( "(" + i[0] + ", " + i[1] + ") ");}); // This code is contributed by rrrtnx.</script> (0, 0) (0, 8) (8, 0) (8, 8) (4, 4) Time Complexity: O(1) Auxiliary Space: O(1) ankthon princiraj1992 Rajput-Ji rrrtnx subhammahato348 Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convex Hull | Set 2 (Graham Scan) Check whether a given point lies inside a triangle or not Optimum location of point to minimize total distance Given n line segments, find if any two segments intersect Convex Hull using Divide and Conquer Algorithm 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": 27059, "s": 27031, "text": "\n03 Mar, 2022" }, { "code": null, "e": 27224, "s": 27059, "text": "Given a number N, the task is to find the integer points (x, y) such that 0 <= x, y <= N and Manhattan distance between any two points will be atleast N.Examples: " }, { "code": null, "e": 27330, "s": 27224, "text": "Input: N = 3\nOutput: (0, 0) (0, 3) (3, 0) (3, 3)\n\nInput: N = 4\nOutput: (0, 0) (0, 4) (4, 0) (4, 4) (2, 2)" }, { "code": null, "e": 27344, "s": 27332, "text": "Approach: " }, { "code": null, "e": 27430, "s": 27344, "text": "Manhattan Distance between two points (x1, y1) and (x2, y2) is: |x1 – x2| + |y1 – y2|" }, { "code": null, "e": 27491, "s": 27430, "text": "Here for all pair of points this distance will be atleast N." }, { "code": null, "e": 27633, "s": 27491, "text": "As 0 <= x <= N and 0 <= y <= N so we can imagine a square of side length N whose bottom left corner is (0, 0) and top right corner is (N, N)." }, { "code": null, "e": 27715, "s": 27633, "text": "So if we place 4 points in this corner then Manhattan distance will be atleast N." }, { "code": null, "e": 27831, "s": 27715, "text": "Now as we have to maximize the number of the point we have to check is there any available point inside the square." }, { "code": null, "e": 27987, "s": 27831, "text": "If N is even then middle point of the square which is (N/2, N/2) is integer point, otherwise, it will be float value as N/2 is not a integer when N is odd." }, { "code": null, "e": 28086, "s": 27987, "text": "So the only available position is the middle point and we can put a point there only if N is even." }, { "code": null, "e": 28182, "s": 28086, "text": "So number of points will be 4 if N is odd and if N is even then the number of points will be 5." }, { "code": null, "e": 28235, "s": 28182, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 28239, "s": 28235, "text": "C++" }, { "code": null, "e": 28244, "s": 28239, "text": "Java" }, { "code": null, "e": 28252, "s": 28244, "text": "Python3" }, { "code": null, "e": 28255, "s": 28252, "text": "C#" }, { "code": null, "e": 28266, "s": 28255, "text": "Javascript" }, { "code": "// C++ code to Find the integer points (x, y)// with Manhattan distance atleast N #include <bits/stdc++.h>using namespace std; // C++ function to find all possible pointvector<pair<int, int> > FindPoints(int n){ vector<pair<int, int> > v; // Find all 4 corners of the square // whose side length is n v.push_back({ 0, 0 }); v.push_back({ 0, n }); v.push_back({ n, 0 }); v.push_back({ n, n }); // If n is even then the middle point // of the square will be an integer, // so we will take that point if (n % 2 == 0) v.push_back({ n / 2, n / 2 }); return v;} // Driver Codeint main(){ int N = 8; vector<pair<int, int> > v = FindPoints(N); // Printing all possible points for (auto i : v) { cout << \"(\" << i.first << \", \" << i.second << \") \"; } return 0;}", "e": 29112, "s": 28266, "text": null }, { "code": "// Java code to Find the integer points (x, y)// with Manhattan distance atleast Nimport java.util.*; class GFG{ static class pair{ int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // Java function to find all possible pointstatic Vector<pair> FindPoints(int n){ Vector<pair> v = new Vector<pair>(); // Find all 4 corners of the square // whose side length is n v.add(new pair( 0, 0 )); v.add(new pair( 0, n )); v.add(new pair( n, 0 )); v.add(new pair( n, n )); // If n is even then the middle point // of the square will be an integer, // so we will take that point if (n % 2 == 0) v.add(new pair( n / 2, n / 2 )); return v;} // Driver Codepublic static void main(String[] args){ int N = 8; Vector<pair > v = FindPoints(N); // Printing all possible points for (pair i : v) { System.out.print(\"(\" + i.first + \", \" + i.second + \") \"); }}} // This code is contributed by PrinciRaj1992", "e": 30176, "s": 29112, "text": null }, { "code": "# Python3 code to Find the integer points (x, y)# with Manhattan distance atleast N # function to find all possible pointdef FindPoints(n) : v = []; # Find all 4 corners of the square # whose side length is n v.append([ 0, 0 ]); v.append([ 0, n ]); v.append([ n, 0 ]); v.append([ n, n ]); # If n is even then the middle point # of the square will be an integer, # so we will take that point if (n % 2 == 0) : v.append([ n // 2, n // 2 ]); return v; # Driver Codeif __name__ == \"__main__\" : N = 8; v = FindPoints(N); # Printing all possible points for element in v : print(\"(\", element[0], \",\", element[1], \")\", end = \" \"); # This code is contributed by AnkitRai01", "e": 30922, "s": 30176, "text": null }, { "code": "// C# code to Find the integer points (x, y)// with Manhattan distance atleast Nusing System;using System.Collections.Generic; class GFG{ class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // Function to find all possible pointstatic List<pair> FindPoints(int n){ List<pair> v = new List<pair>(); // Find all 4 corners of the square // whose side length is n v.Add(new pair( 0, 0 )); v.Add(new pair( 0, n )); v.Add(new pair( n, 0 )); v.Add(new pair( n, n )); // If n is even then the middle point // of the square will be an integer, // so we will take that point if (n % 2 == 0) v.Add(new pair( n / 2, n / 2 )); return v;} // Driver Codepublic static void Main(String[] args){ int N = 8; List<pair > v = FindPoints(N); // Printing all possible points foreach (pair i in v) { Console.Write(\"(\" + i.first + \", \" + i.second + \") \"); }}} // This code is contributed by Rajput-Ji", "e": 31993, "s": 30922, "text": null }, { "code": "<script> // Javascript code to Find the integer points (x, y)// with Manhattan distance atleast N // C++ function to find all possible pointfunction FindPoints(n){ var v = []; // Find all 4 corners of the square // whose side length is n v.push([ 0, 0 ]); v.push([ 0, n ]); v.push([ n, 0 ]); v.push([ n, n ]); // If n is even then the middle point // of the square will be an integer, // so we will take that point if (n % 2 == 0) v.push([ n / 2, n / 2 ]); return v;} // Driver Codevar N = 8;var v = FindPoints(N);// Printing all possible pointsv.forEach(i => { document.write( \"(\" + i[0] + \", \" + i[1] + \") \");}); // This code is contributed by rrrtnx.</script>", "e": 32714, "s": 31993, "text": null }, { "code": null, "e": 32749, "s": 32714, "text": "(0, 0) (0, 8) (8, 0) (8, 8) (4, 4)" }, { "code": null, "e": 32773, "s": 32751, "text": "Time Complexity: O(1)" }, { "code": null, "e": 32795, "s": 32773, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 32803, "s": 32795, "text": "ankthon" }, { "code": null, "e": 32817, "s": 32803, "text": "princiraj1992" }, { "code": null, "e": 32827, "s": 32817, "text": "Rajput-Ji" }, { "code": null, "e": 32834, "s": 32827, "text": "rrrtnx" }, { "code": null, "e": 32850, "s": 32834, "text": "subhammahato348" }, { "code": null, "e": 32860, "s": 32850, "text": "Geometric" }, { "code": null, "e": 32873, "s": 32860, "text": "Mathematical" }, { "code": null, "e": 32886, "s": 32873, "text": "Mathematical" }, { "code": null, "e": 32896, "s": 32886, "text": "Geometric" }, { "code": null, "e": 32994, "s": 32896, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33028, "s": 32994, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 33086, "s": 33028, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 33139, "s": 33086, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 33197, "s": 33139, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 33244, "s": 33197, "text": "Convex Hull using Divide and Conquer Algorithm" }, { "code": null, "e": 33274, "s": 33244, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 33334, "s": 33274, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 33349, "s": 33334, "text": "C++ Data Types" }, { "code": null, "e": 33392, "s": 33349, "text": "Set in C++ Standard Template Library (STL)" } ]
HTML | DOM Input FileUpload value Property - GeeksforGeeks
11 Oct, 2019 The Input FileUpload value Property is used to returns the path or the name of the file selected with the element.This property is used to return the name of the selected file with a fake path in IE, Google Chrome, and Opera, and return the name of the selected file in Firefox and Safari. This property is read-only, because of security reasons. Syntax: fileuploadObject.value Example: Return the “path”. <!DOCTYPE html><html> <head> <title> HTML DOM Input FileUpload value </title> <style> h1 { color: green; } </style></head> <body> <center> <h1> Geeks for Geeks </h1> <input type="file" id="myFile" required> <p id="demo"></p> <button onclick="myFunction()"> Click </button> <script> function myFunction() { var x = document.getElementById( "myFile").value; document.getElementById( "demo").innerHTML = x; } </script> </center></body> </html> Output:Before Clicking the Button: After Clicking the Button: Supported Browsers: Google Chrome Mozilla Firefox Edge 10.0 Opera Apple Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. shubham_singh HTML-DOM HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26088, "s": 26060, "text": "\n11 Oct, 2019" }, { "code": null, "e": 26435, "s": 26088, "text": "The Input FileUpload value Property is used to returns the path or the name of the file selected with the element.This property is used to return the name of the selected file with a fake path in IE, Google Chrome, and Opera, and return the name of the selected file in Firefox and Safari. This property is read-only, because of security reasons." }, { "code": null, "e": 26443, "s": 26435, "text": "Syntax:" }, { "code": null, "e": 26466, "s": 26443, "text": "fileuploadObject.value" }, { "code": null, "e": 26494, "s": 26466, "text": "Example: Return the “path”." }, { "code": "<!DOCTYPE html><html> <head> <title> HTML DOM Input FileUpload value </title> <style> h1 { color: green; } </style></head> <body> <center> <h1> Geeks for Geeks </h1> <input type=\"file\" id=\"myFile\" required> <p id=\"demo\"></p> <button onclick=\"myFunction()\"> Click </button> <script> function myFunction() { var x = document.getElementById( \"myFile\").value; document.getElementById( \"demo\").innerHTML = x; } </script> </center></body> </html>", "e": 27215, "s": 26494, "text": null }, { "code": null, "e": 27250, "s": 27215, "text": "Output:Before Clicking the Button:" }, { "code": null, "e": 27277, "s": 27250, "text": "After Clicking the Button:" }, { "code": null, "e": 27297, "s": 27277, "text": "Supported Browsers:" }, { "code": null, "e": 27311, "s": 27297, "text": "Google Chrome" }, { "code": null, "e": 27327, "s": 27311, "text": "Mozilla Firefox" }, { "code": null, "e": 27337, "s": 27327, "text": "Edge 10.0" }, { "code": null, "e": 27343, "s": 27337, "text": "Opera" }, { "code": null, "e": 27356, "s": 27343, "text": "Apple Safari" }, { "code": null, "e": 27493, "s": 27356, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27507, "s": 27493, "text": "shubham_singh" }, { "code": null, "e": 27516, "s": 27507, "text": "HTML-DOM" }, { "code": null, "e": 27521, "s": 27516, "text": "HTML" }, { "code": null, "e": 27538, "s": 27521, "text": "Web Technologies" }, { "code": null, "e": 27543, "s": 27538, "text": "HTML" }, { "code": null, "e": 27641, "s": 27543, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27689, "s": 27641, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27713, "s": 27689, "text": "REST API (Introduction)" }, { "code": null, "e": 27763, "s": 27713, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27813, "s": 27763, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 27850, "s": 27813, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27890, "s": 27850, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27923, "s": 27890, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27968, "s": 27923, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28011, "s": 27968, "text": "How to fetch data from an API in ReactJS ?" } ]
Implement Secure Hashing Algorithm - 512 ( SHA-512 ) as Functional Programming Paradigm - GeeksforGeeks
24 Mar, 2022 Given a string S of length N, the task is to find the SHA-512 Hash Value of the given string S. Examples: Input: S = “GeeksforGeeks”Output: acc10c4e0b38617f59e88e49215e2e894afaee5ec948c2af6f44039f03c9fe47a9210e01d5cd926c142bdc9179c2ad30f927a8faf69421ff60a5eaddcf8cb9c Input: S = “hello world”Output:309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bcd3ca86d4cd86f989dd35bc5ff499670da34255b45b0cfd830e81f605dcf7dc5542e93ae9cd76f Approach: Follow the steps below to solve the problem: Convert the given string into the binary form. Append ‘1’ to the string and then ‘0’ continuously until length of the string is < (N%(1024 – 128)). Add the 128-bit binary representation of N in the string S. Find the number of chunks of the size of 1024 and store it in a variable, say chunks as N/1024. Divide the string S into 16 chunks of 64 characters. Extend the number of chunks to 80 by performing the following operations:Iterate over the range [16, 80] and then find 4 values say WordA, WordB, WordC, WordD as:WordA = rotate_right(Message[g – 2], 19) ^ rotate_right(Message[g – 2], 61) ^ shift_right(Message[g – 2], 6).WordB = Message[g – 7].WordC = rotate_right(Message[g – 15], 1) ^ rotate_right(Message[g – 15], 8) ^ shift_right(Message[g – 15], 7).WordD = Message[g – 16].Update the value of Message[g] as (WordA + WordB + WordC + WordD). Iterate over the range [16, 80] and then find 4 values say WordA, WordB, WordC, WordD as:WordA = rotate_right(Message[g – 2], 19) ^ rotate_right(Message[g – 2], 61) ^ shift_right(Message[g – 2], 6).WordB = Message[g – 7].WordC = rotate_right(Message[g – 15], 1) ^ rotate_right(Message[g – 15], 8) ^ shift_right(Message[g – 15], 7).WordD = Message[g – 16]. WordA = rotate_right(Message[g – 2], 19) ^ rotate_right(Message[g – 2], 61) ^ shift_right(Message[g – 2], 6). WordB = Message[g – 7]. WordC = rotate_right(Message[g – 15], 1) ^ rotate_right(Message[g – 15], 8) ^ shift_right(Message[g – 15], 7). WordD = Message[g – 16]. Update the value of Message[g] as (WordA + WordB + WordC + WordD). Initialize 8 variables say A, B, C, D, E, F, G, H of type 64-bit to store the final hash value of the given string S. Traverse the array Block[] and perform the following steps:Update the value of A, B, C, D, E, F, G, H using the Hash Function till 80 iterations by rotating one by one.Now, update the value of A, B, C, D, E, F, G, H by the summation of previous values of A, B, C, D, E, F, G, H and the newly updated value of A, B, C, D, E, F, G, H. Update the value of A, B, C, D, E, F, G, H using the Hash Function till 80 iterations by rotating one by one. Now, update the value of A, B, C, D, E, F, G, H by the summation of previous values of A, B, C, D, E, F, G, H and the newly updated value of A, B, C, D, E, F, G, H. After completing the above steps, print the hexadecimal values of A, B, C, D, E, F, G, H to get the Hash Value of the given string. Below is the implementation of the above approach: C++14 // C++ program for the above approach#include <bits/stdc++.h>using namespace std;typedef unsigned long long int int64; int64 Message[80]; // Stores the hexadecimal values for// calculating hash valuesconst int64 Constants[80] = { 0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817 }; // Function to convert a binary string// to hexa-decimal valuestring gethex(string bin){ if (bin == "0000") return "0"; if (bin == "0001") return "1"; if (bin == "0010") return "2"; if (bin == "0011") return "3"; if (bin == "0100") return "4"; if (bin == "0101") return "5"; if (bin == "0110") return "6"; if (bin == "0111") return "7"; if (bin == "1000") return "8"; if (bin == "1001") return "9"; if (bin == "1010") return "a"; if (bin == "1011") return "b"; if (bin == "1100") return "c"; if (bin == "1101") return "d"; if (bin == "1110") return "e"; if (bin == "1111") return "f";} // Function to convert a decimal value// to hexa decimal valuestring decimaltohex(int64 deci){ // Stores the value as string string EQBIN = bitset<64>(deci).to_string(); // Stores the equivalent hexa decimal string hexstring = ""; string temp; // Traverse the string EQBIN for (unsigned int i = 0; i < EQBIN.length(); i += 4) { temp = EQBIN.substr(i, 4); hexstring += gethex(temp); } // Return the hexstring return hexstring;} // Function to convert a binary// string to decimal valueint64 BintoDec(string bin){ int64 value = bitset<64>(bin) .to_ullong(); return value;} // Function to right rotate x by n bitsint64 rotate_right(int64 x, int n){ return (x >> n) | (x << (64 - n));} // Function to right shift x by n bitsint64 shift_right(int64 x, int n){ return (x >> n);} // Function to divide the string// into chunksvoid separator(string getBlock){ // Stores the size of chunks int chunknum = 0; // Traverse the string S for (unsigned int i = 0; i < getBlock.length(); i += 64, ++chunknum) { // Update the Message[chunknum] Message[chunknum] = BintoDec(getBlock.substr(i, 64)); } // Iterate over the range [16, 80] for (int g = 16; g < 80; ++g) { // Find the WordA int64 WordA = rotate_right(Message[g - 2], 19) ^ rotate_right(Message[g - 2], 61) ^ shift_right(Message[g - 2], 6); // Find the WordB int64 WordB = Message[g - 7]; // Find the WordC int64 WordC = rotate_right(Message[g - 15], 1) ^ rotate_right(Message[g - 15], 8) ^ shift_right(Message[g - 15], 7); // Find the WordD int64 WordD = Message[g - 16]; // Find the resultant code int64 T = WordA + WordB + WordC + WordD; // Return the resultant Hash Code Message[g] = T; }} // Function to find the major of a, b, cint64 maj(int64 a, int64 b, int64 c){ return (a & b) ^ (b & c) ^ (c & a);} // Function to find the ch value of a,// b, and cint64 Ch(int64 e, int64 f, int64 g){ return (e & f) ^ (~e & g);} // Function to find the Bitwise XOR with// the right rotate over 14, 18, and 41int64 sigmaE(int64 e){ // Return the resultant value return rotate_right(e, 14) ^ rotate_right(e, 18) ^ rotate_right(e, 41);} // Function to find the Bitwise XOR with// the right rotate over 28, 34, and 39int64 sigmaA(int64 a){ // Return the resultant value return rotate_right(a, 28) ^ rotate_right(a, 34) ^ rotate_right(a, 39);} // Function to generate the hash codevoid Func(int64 a, int64 b, int64 c, int64& d, int64 e, int64 f, int64 g, int64& h, int K){ // Find the Hash Code int64 T1 = h + Ch(e, f, g) + sigmaE(e) + Message[K] + Constants[K]; int64 T2 = sigmaA(a) + maj(a, b, c); d = d + T1; h = T1 + T2;} // Function to convert the hash value// of a given stringstring SHA512(string myString){ // Stores the 8 blocks of size 64 int64 A = 0x6a09e667f3bcc908; int64 B = 0xbb67ae8584caa73b; int64 C = 0x3c6ef372fe94f82b; int64 D = 0xa54ff53a5f1d36f1; int64 E = 0x510e527fade682d1; int64 F = 0x9b05688c2b3e6c1f; int64 G = 0x1f83d9abfb41bd6b; int64 H = 0x5be0cd19137e2179; int64 AA, BB, CC, DD, EE, FF, GG, HH; stringstream fixedstream; // Traverse the string S for (int i = 0; i < myString.size(); ++i) { // Add the character to stream fixedstream << bitset<8>(myString[i]); } // Stores string of size 1024 string s1024; // Stores the string in the // fixedstream s1024 = fixedstream.str(); // Stores the length of string int orilen = s1024.length(); int tobeadded; // Find modded string length int modded = s1024.length() % 1024; // If 1024-128 is greater than modded if (1024 - modded >= 128) { tobeadded = 1024 - modded; } // Else if 1024-128 is less than modded else if (1024 - modded < 128) { tobeadded = 2048 - modded; } // Append 1 to string s1024 += "1"; // Append tobeadded-129 zeros // in the string for (int y = 0; y < tobeadded - 129; y++) { s1024 += "0"; } // Stores the binary representation // of string length string lengthbits = std::bitset<128>(orilen).to_string(); // Append the lengthbits to string s1024 += lengthbits; // Find the count of chunks of // size 1024 each int blocksnumber = s1024.length() / 1024; // Stores the numbering of chunks int chunknum = 0; // Stores hash value of each blocks string Blocks[blocksnumber]; // Traverse the string s1024 for (int i = 0; i < s1024.length(); i += 1024, ++chunknum) { Blocks[chunknum] = s1024.substr(i, 1024); } // Traverse tha array Blocks[] for (int letsgo = 0; letsgo < blocksnumber; ++letsgo) { // Divide the current string // into 80 blocks size 16 each separator(Blocks[letsgo]); AA = A; BB = B; CC = C; DD = D; EE = E; FF = F; GG = G; HH = H; int count = 0; // Find hash values for (int i = 0; i < 10; i++) { // Find the Hash Values Func(A, B, C, D, E, F, G, H, count); count++; Func(H, A, B, C, D, E, F, G, count); count++; Func(G, H, A, B, C, D, E, F, count); count++; Func(F, G, H, A, B, C, D, E, count); count++; Func(E, F, G, H, A, B, C, D, count); count++; Func(D, E, F, G, H, A, B, C, count); count++; Func(C, D, E, F, G, H, A, B, count); count++; Func(B, C, D, E, F, G, H, A, count); count++; } // Update the value of A, B, C, // D, E, F, G, H A += AA; B += BB; C += CC; D += DD; E += EE; F += FF; G += GG; H += HH; } stringstream output; // Print the hexadecimal value of // strings as the resultant SHA-512 output << decimaltohex(A); output << decimaltohex(B); output << decimaltohex(C); output << decimaltohex(D); output << decimaltohex(E); output << decimaltohex(F); output << decimaltohex(G); output << decimaltohex(H); // Return the string return output.str();} // Driver Codeint main(){ // Input string S = "GeeksForGeeks"; // Function Call cout << S << ": " << SHA512(S); return 0;} GeeksForGeeks: 0acc10c4e0b38617f59e88e49215e2e894afaee5ec948c2af6f44039f03c9fe47a9210e01d5cd926c142bdc9179c2ad30f927a8faf69421ff60a5eaddcf8cb9c Time Complexity: O(N)Auxiliary Space: O(1) anikakapoor sumitgumber28 simranarora5sos rkbhola5 cryptography Java-Functional Programming Algorithms Computer Networks Hash Hash cryptography Algorithms Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? Difference between Algorithm, Pseudocode and Program K means Clustering - Introduction Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Layers of OSI Model TCP/IP Model RSA Algorithm in Cryptography Differences between TCP and UDP TCP Server-Client implementation in C
[ { "code": null, "e": 25942, "s": 25914, "text": "\n24 Mar, 2022" }, { "code": null, "e": 26038, "s": 25942, "text": "Given a string S of length N, the task is to find the SHA-512 Hash Value of the given string S." }, { "code": null, "e": 26048, "s": 26038, "text": "Examples:" }, { "code": null, "e": 26210, "s": 26048, "text": "Input: S = “GeeksforGeeks”Output: acc10c4e0b38617f59e88e49215e2e894afaee5ec948c2af6f44039f03c9fe47a9210e01d5cd926c142bdc9179c2ad30f927a8faf69421ff60a5eaddcf8cb9c" }, { "code": null, "e": 26370, "s": 26210, "text": "Input: S = “hello world”Output:309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bcd3ca86d4cd86f989dd35bc5ff499670da34255b45b0cfd830e81f605dcf7dc5542e93ae9cd76f" }, { "code": null, "e": 26425, "s": 26370, "text": "Approach: Follow the steps below to solve the problem:" }, { "code": null, "e": 26472, "s": 26425, "text": "Convert the given string into the binary form." }, { "code": null, "e": 26573, "s": 26472, "text": "Append ‘1’ to the string and then ‘0’ continuously until length of the string is < (N%(1024 – 128))." }, { "code": null, "e": 26633, "s": 26573, "text": "Add the 128-bit binary representation of N in the string S." }, { "code": null, "e": 26729, "s": 26633, "text": "Find the number of chunks of the size of 1024 and store it in a variable, say chunks as N/1024." }, { "code": null, "e": 26782, "s": 26729, "text": "Divide the string S into 16 chunks of 64 characters." }, { "code": null, "e": 27277, "s": 26782, "text": "Extend the number of chunks to 80 by performing the following operations:Iterate over the range [16, 80] and then find 4 values say WordA, WordB, WordC, WordD as:WordA = rotate_right(Message[g – 2], 19) ^ rotate_right(Message[g – 2], 61) ^ shift_right(Message[g – 2], 6).WordB = Message[g – 7].WordC = rotate_right(Message[g – 15], 1) ^ rotate_right(Message[g – 15], 8) ^ shift_right(Message[g – 15], 7).WordD = Message[g – 16].Update the value of Message[g] as (WordA + WordB + WordC + WordD)." }, { "code": null, "e": 27633, "s": 27277, "text": "Iterate over the range [16, 80] and then find 4 values say WordA, WordB, WordC, WordD as:WordA = rotate_right(Message[g – 2], 19) ^ rotate_right(Message[g – 2], 61) ^ shift_right(Message[g – 2], 6).WordB = Message[g – 7].WordC = rotate_right(Message[g – 15], 1) ^ rotate_right(Message[g – 15], 8) ^ shift_right(Message[g – 15], 7).WordD = Message[g – 16]." }, { "code": null, "e": 27743, "s": 27633, "text": "WordA = rotate_right(Message[g – 2], 19) ^ rotate_right(Message[g – 2], 61) ^ shift_right(Message[g – 2], 6)." }, { "code": null, "e": 27767, "s": 27743, "text": "WordB = Message[g – 7]." }, { "code": null, "e": 27878, "s": 27767, "text": "WordC = rotate_right(Message[g – 15], 1) ^ rotate_right(Message[g – 15], 8) ^ shift_right(Message[g – 15], 7)." }, { "code": null, "e": 27903, "s": 27878, "text": "WordD = Message[g – 16]." }, { "code": null, "e": 27970, "s": 27903, "text": "Update the value of Message[g] as (WordA + WordB + WordC + WordD)." }, { "code": null, "e": 28088, "s": 27970, "text": "Initialize 8 variables say A, B, C, D, E, F, G, H of type 64-bit to store the final hash value of the given string S." }, { "code": null, "e": 28421, "s": 28088, "text": "Traverse the array Block[] and perform the following steps:Update the value of A, B, C, D, E, F, G, H using the Hash Function till 80 iterations by rotating one by one.Now, update the value of A, B, C, D, E, F, G, H by the summation of previous values of A, B, C, D, E, F, G, H and the newly updated value of A, B, C, D, E, F, G, H." }, { "code": null, "e": 28531, "s": 28421, "text": "Update the value of A, B, C, D, E, F, G, H using the Hash Function till 80 iterations by rotating one by one." }, { "code": null, "e": 28696, "s": 28531, "text": "Now, update the value of A, B, C, D, E, F, G, H by the summation of previous values of A, B, C, D, E, F, G, H and the newly updated value of A, B, C, D, E, F, G, H." }, { "code": null, "e": 28828, "s": 28696, "text": "After completing the above steps, print the hexadecimal values of A, B, C, D, E, F, G, H to get the Hash Value of the given string." }, { "code": null, "e": 28879, "s": 28828, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28885, "s": 28879, "text": "C++14" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std;typedef unsigned long long int int64; int64 Message[80]; // Stores the hexadecimal values for// calculating hash valuesconst int64 Constants[80] = { 0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817 }; // Function to convert a binary string// to hexa-decimal valuestring gethex(string bin){ if (bin == \"0000\") return \"0\"; if (bin == \"0001\") return \"1\"; if (bin == \"0010\") return \"2\"; if (bin == \"0011\") return \"3\"; if (bin == \"0100\") return \"4\"; if (bin == \"0101\") return \"5\"; if (bin == \"0110\") return \"6\"; if (bin == \"0111\") return \"7\"; if (bin == \"1000\") return \"8\"; if (bin == \"1001\") return \"9\"; if (bin == \"1010\") return \"a\"; if (bin == \"1011\") return \"b\"; if (bin == \"1100\") return \"c\"; if (bin == \"1101\") return \"d\"; if (bin == \"1110\") return \"e\"; if (bin == \"1111\") return \"f\";} // Function to convert a decimal value// to hexa decimal valuestring decimaltohex(int64 deci){ // Stores the value as string string EQBIN = bitset<64>(deci).to_string(); // Stores the equivalent hexa decimal string hexstring = \"\"; string temp; // Traverse the string EQBIN for (unsigned int i = 0; i < EQBIN.length(); i += 4) { temp = EQBIN.substr(i, 4); hexstring += gethex(temp); } // Return the hexstring return hexstring;} // Function to convert a binary// string to decimal valueint64 BintoDec(string bin){ int64 value = bitset<64>(bin) .to_ullong(); return value;} // Function to right rotate x by n bitsint64 rotate_right(int64 x, int n){ return (x >> n) | (x << (64 - n));} // Function to right shift x by n bitsint64 shift_right(int64 x, int n){ return (x >> n);} // Function to divide the string// into chunksvoid separator(string getBlock){ // Stores the size of chunks int chunknum = 0; // Traverse the string S for (unsigned int i = 0; i < getBlock.length(); i += 64, ++chunknum) { // Update the Message[chunknum] Message[chunknum] = BintoDec(getBlock.substr(i, 64)); } // Iterate over the range [16, 80] for (int g = 16; g < 80; ++g) { // Find the WordA int64 WordA = rotate_right(Message[g - 2], 19) ^ rotate_right(Message[g - 2], 61) ^ shift_right(Message[g - 2], 6); // Find the WordB int64 WordB = Message[g - 7]; // Find the WordC int64 WordC = rotate_right(Message[g - 15], 1) ^ rotate_right(Message[g - 15], 8) ^ shift_right(Message[g - 15], 7); // Find the WordD int64 WordD = Message[g - 16]; // Find the resultant code int64 T = WordA + WordB + WordC + WordD; // Return the resultant Hash Code Message[g] = T; }} // Function to find the major of a, b, cint64 maj(int64 a, int64 b, int64 c){ return (a & b) ^ (b & c) ^ (c & a);} // Function to find the ch value of a,// b, and cint64 Ch(int64 e, int64 f, int64 g){ return (e & f) ^ (~e & g);} // Function to find the Bitwise XOR with// the right rotate over 14, 18, and 41int64 sigmaE(int64 e){ // Return the resultant value return rotate_right(e, 14) ^ rotate_right(e, 18) ^ rotate_right(e, 41);} // Function to find the Bitwise XOR with// the right rotate over 28, 34, and 39int64 sigmaA(int64 a){ // Return the resultant value return rotate_right(a, 28) ^ rotate_right(a, 34) ^ rotate_right(a, 39);} // Function to generate the hash codevoid Func(int64 a, int64 b, int64 c, int64& d, int64 e, int64 f, int64 g, int64& h, int K){ // Find the Hash Code int64 T1 = h + Ch(e, f, g) + sigmaE(e) + Message[K] + Constants[K]; int64 T2 = sigmaA(a) + maj(a, b, c); d = d + T1; h = T1 + T2;} // Function to convert the hash value// of a given stringstring SHA512(string myString){ // Stores the 8 blocks of size 64 int64 A = 0x6a09e667f3bcc908; int64 B = 0xbb67ae8584caa73b; int64 C = 0x3c6ef372fe94f82b; int64 D = 0xa54ff53a5f1d36f1; int64 E = 0x510e527fade682d1; int64 F = 0x9b05688c2b3e6c1f; int64 G = 0x1f83d9abfb41bd6b; int64 H = 0x5be0cd19137e2179; int64 AA, BB, CC, DD, EE, FF, GG, HH; stringstream fixedstream; // Traverse the string S for (int i = 0; i < myString.size(); ++i) { // Add the character to stream fixedstream << bitset<8>(myString[i]); } // Stores string of size 1024 string s1024; // Stores the string in the // fixedstream s1024 = fixedstream.str(); // Stores the length of string int orilen = s1024.length(); int tobeadded; // Find modded string length int modded = s1024.length() % 1024; // If 1024-128 is greater than modded if (1024 - modded >= 128) { tobeadded = 1024 - modded; } // Else if 1024-128 is less than modded else if (1024 - modded < 128) { tobeadded = 2048 - modded; } // Append 1 to string s1024 += \"1\"; // Append tobeadded-129 zeros // in the string for (int y = 0; y < tobeadded - 129; y++) { s1024 += \"0\"; } // Stores the binary representation // of string length string lengthbits = std::bitset<128>(orilen).to_string(); // Append the lengthbits to string s1024 += lengthbits; // Find the count of chunks of // size 1024 each int blocksnumber = s1024.length() / 1024; // Stores the numbering of chunks int chunknum = 0; // Stores hash value of each blocks string Blocks[blocksnumber]; // Traverse the string s1024 for (int i = 0; i < s1024.length(); i += 1024, ++chunknum) { Blocks[chunknum] = s1024.substr(i, 1024); } // Traverse tha array Blocks[] for (int letsgo = 0; letsgo < blocksnumber; ++letsgo) { // Divide the current string // into 80 blocks size 16 each separator(Blocks[letsgo]); AA = A; BB = B; CC = C; DD = D; EE = E; FF = F; GG = G; HH = H; int count = 0; // Find hash values for (int i = 0; i < 10; i++) { // Find the Hash Values Func(A, B, C, D, E, F, G, H, count); count++; Func(H, A, B, C, D, E, F, G, count); count++; Func(G, H, A, B, C, D, E, F, count); count++; Func(F, G, H, A, B, C, D, E, count); count++; Func(E, F, G, H, A, B, C, D, count); count++; Func(D, E, F, G, H, A, B, C, count); count++; Func(C, D, E, F, G, H, A, B, count); count++; Func(B, C, D, E, F, G, H, A, count); count++; } // Update the value of A, B, C, // D, E, F, G, H A += AA; B += BB; C += CC; D += DD; E += EE; F += FF; G += GG; H += HH; } stringstream output; // Print the hexadecimal value of // strings as the resultant SHA-512 output << decimaltohex(A); output << decimaltohex(B); output << decimaltohex(C); output << decimaltohex(D); output << decimaltohex(E); output << decimaltohex(F); output << decimaltohex(G); output << decimaltohex(H); // Return the string return output.str();} // Driver Codeint main(){ // Input string S = \"GeeksForGeeks\"; // Function Call cout << S << \": \" << SHA512(S); return 0;}", "e": 38393, "s": 28885, "text": null }, { "code": null, "e": 38537, "s": 38393, "text": "GeeksForGeeks: 0acc10c4e0b38617f59e88e49215e2e894afaee5ec948c2af6f44039f03c9fe47a9210e01d5cd926c142bdc9179c2ad30f927a8faf69421ff60a5eaddcf8cb9c" }, { "code": null, "e": 38582, "s": 38539, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 38594, "s": 38582, "text": "anikakapoor" }, { "code": null, "e": 38608, "s": 38594, "text": "sumitgumber28" }, { "code": null, "e": 38624, "s": 38608, "text": "simranarora5sos" }, { "code": null, "e": 38633, "s": 38624, "text": "rkbhola5" }, { "code": null, "e": 38646, "s": 38633, "text": "cryptography" }, { "code": null, "e": 38674, "s": 38646, "text": "Java-Functional Programming" }, { "code": null, "e": 38685, "s": 38674, "text": "Algorithms" }, { "code": null, "e": 38703, "s": 38685, "text": "Computer Networks" }, { "code": null, "e": 38708, "s": 38703, "text": "Hash" }, { "code": null, "e": 38713, "s": 38708, "text": "Hash" }, { "code": null, "e": 38726, "s": 38713, "text": "cryptography" }, { "code": null, "e": 38737, "s": 38726, "text": "Algorithms" }, { "code": null, "e": 38755, "s": 38737, "text": "Computer Networks" }, { "code": null, "e": 38853, "s": 38755, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38878, "s": 38853, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 38905, "s": 38878, "text": "How to Start Learning DSA?" }, { "code": null, "e": 38958, "s": 38905, "text": "Difference between Algorithm, Pseudocode and Program" }, { "code": null, "e": 38992, "s": 38958, "text": "K means Clustering - Introduction" }, { "code": null, "e": 39059, "s": 38992, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 39079, "s": 39059, "text": "Layers of OSI Model" }, { "code": null, "e": 39092, "s": 39079, "text": "TCP/IP Model" }, { "code": null, "e": 39122, "s": 39092, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 39154, "s": 39122, "text": "Differences between TCP and UDP" } ]
Difference between var keyword and short declaration operator in Golang - GeeksforGeeks
11 Jun, 2020 A variable is a storage location or place holder used for holding the value. It allows us to manipulate and retrieve the stored information. There are two ways to declare the variables in Golan which are as follows: Using var keyword Using a short declaration operator (:=) Example 1: In this program you can see the myvariable1 is declared using var keyword and it has local scope. myvariable2 is also declared using var keyword along with type int but there is no initialization has been done. So it will take the default value of int type i.e. zero(you can see in the output). myvariable3 is declared and initialized using short variable declaration operator and it has local scope. // Go program to show the use of var lexical // keyword and short declaration operatorpackage main import ( "fmt") func main() { // using var keyword to declare // and initialize the variablevar myvariable1 = 100 fmt.Println(myvariable1) // using var keyword to declare // the variable along with typevar myvariable2 int fmt.Println(myvariable2) // using short variable declarationmyvariable3 := 200 fmt.Println(myvariable3) } Output: 100 0 200 Example 2: In this program you can see the myvariable1 is declared using var keyword and it has global scope. myvariable2 is also declared using var keyword along with type int but there is no initialization has been done. So it will take the default value of int type i.e. zero(you can see in the output). myvariable3 is declared and initialized using short variable declaration operator and it has local scope. // Go program to show the use of var lexical // keyword and short declaration operatorpackage main import ( "fmt") // using var keyword to declare // and initialize the variable// it is package or you can say // global level scopevar myvariable1 = 100 func main() { // accessing myvariable1 inside the functionfmt.Println(myvariable1) // using var keyword to declare // the variable along with typevar myvariable2 int fmt.Println(myvariable2) // using short variable declarationmyvariable3 := 200 fmt.Println(myvariable3) } Output: 100 0 200 Example 3: In this program you can see the myvariable1 is declared using var keyword and it has global scope. myvariable2 is also declared using var keyword along with type int but there is no initialization has been done. So it will take the default value of int type i.e. zero(you can see in the output). myvariable3 is declared and initialized using short variable declaration operator outside the function which is not allowed and hence gives error. // Go program to show the use of var lexical // keyword and short declaration operatorpackage main import ( "fmt") // using var keyword to declare // and initialize the variable// it is package or you can say // global level scopevar myvariable1 = 100 // using short variable declaration// it will give an error as it is not // allowed outside the functionmyvariable3 := 200 func main() { // accessing myvariable1 inside the functionfmt.Println(myvariable1) // using var keyword to declare // the variable along with typevar myvariable2 int fmt.Println(myvariable2) fmt.Println(myvariable3) } Error: ./prog.go:18:1: syntax error: non-declaration statement outside function body Akanksha_Rai shubham_singh Go-Keywords Go-Operators Golang Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 6 Best Books to Learn Go Programming Language Arrays in Go strings.Replace() Function in Golang With Examples fmt.Sprintf() Function in Golang With Examples How to Split a String in Golang? Slices in Golang Golang Maps Different Ways to Find the Type of Variable in Golang Inheritance in GoLang Interfaces in Golang
[ { "code": null, "e": 25663, "s": 25635, "text": "\n11 Jun, 2020" }, { "code": null, "e": 25879, "s": 25663, "text": "A variable is a storage location or place holder used for holding the value. It allows us to manipulate and retrieve the stored information. There are two ways to declare the variables in Golan which are as follows:" }, { "code": null, "e": 25897, "s": 25879, "text": "Using var keyword" }, { "code": null, "e": 25937, "s": 25897, "text": "Using a short declaration operator (:=)" }, { "code": null, "e": 26349, "s": 25937, "text": "Example 1: In this program you can see the myvariable1 is declared using var keyword and it has local scope. myvariable2 is also declared using var keyword along with type int but there is no initialization has been done. So it will take the default value of int type i.e. zero(you can see in the output). myvariable3 is declared and initialized using short variable declaration operator and it has local scope." }, { "code": "// Go program to show the use of var lexical // keyword and short declaration operatorpackage main import ( \"fmt\") func main() { // using var keyword to declare // and initialize the variablevar myvariable1 = 100 fmt.Println(myvariable1) // using var keyword to declare // the variable along with typevar myvariable2 int fmt.Println(myvariable2) // using short variable declarationmyvariable3 := 200 fmt.Println(myvariable3) }", "e": 26792, "s": 26349, "text": null }, { "code": null, "e": 26800, "s": 26792, "text": "Output:" }, { "code": null, "e": 26811, "s": 26800, "text": "100\n0\n200\n" }, { "code": null, "e": 27224, "s": 26811, "text": "Example 2: In this program you can see the myvariable1 is declared using var keyword and it has global scope. myvariable2 is also declared using var keyword along with type int but there is no initialization has been done. So it will take the default value of int type i.e. zero(you can see in the output). myvariable3 is declared and initialized using short variable declaration operator and it has local scope." }, { "code": "// Go program to show the use of var lexical // keyword and short declaration operatorpackage main import ( \"fmt\") // using var keyword to declare // and initialize the variable// it is package or you can say // global level scopevar myvariable1 = 100 func main() { // accessing myvariable1 inside the functionfmt.Println(myvariable1) // using var keyword to declare // the variable along with typevar myvariable2 int fmt.Println(myvariable2) // using short variable declarationmyvariable3 := 200 fmt.Println(myvariable3) }", "e": 27764, "s": 27224, "text": null }, { "code": null, "e": 27772, "s": 27764, "text": "Output:" }, { "code": null, "e": 27783, "s": 27772, "text": "100\n0\n200\n" }, { "code": null, "e": 28237, "s": 27783, "text": "Example 3: In this program you can see the myvariable1 is declared using var keyword and it has global scope. myvariable2 is also declared using var keyword along with type int but there is no initialization has been done. So it will take the default value of int type i.e. zero(you can see in the output). myvariable3 is declared and initialized using short variable declaration operator outside the function which is not allowed and hence gives error." }, { "code": "// Go program to show the use of var lexical // keyword and short declaration operatorpackage main import ( \"fmt\") // using var keyword to declare // and initialize the variable// it is package or you can say // global level scopevar myvariable1 = 100 // using short variable declaration// it will give an error as it is not // allowed outside the functionmyvariable3 := 200 func main() { // accessing myvariable1 inside the functionfmt.Println(myvariable1) // using var keyword to declare // the variable along with typevar myvariable2 int fmt.Println(myvariable2) fmt.Println(myvariable3) }", "e": 28848, "s": 28237, "text": null }, { "code": null, "e": 28855, "s": 28848, "text": "Error:" }, { "code": null, "e": 28933, "s": 28855, "text": "./prog.go:18:1: syntax error: non-declaration statement outside function body" }, { "code": null, "e": 28946, "s": 28933, "text": "Akanksha_Rai" }, { "code": null, "e": 28960, "s": 28946, "text": "shubham_singh" }, { "code": null, "e": 28972, "s": 28960, "text": "Go-Keywords" }, { "code": null, "e": 28985, "s": 28972, "text": "Go-Operators" }, { "code": null, "e": 28992, "s": 28985, "text": "Golang" }, { "code": null, "e": 29004, "s": 28992, "text": "Go Language" }, { "code": null, "e": 29102, "s": 29004, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29148, "s": 29102, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 29161, "s": 29148, "text": "Arrays in Go" }, { "code": null, "e": 29212, "s": 29161, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 29259, "s": 29212, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 29292, "s": 29259, "text": "How to Split a String in Golang?" }, { "code": null, "e": 29309, "s": 29292, "text": "Slices in Golang" }, { "code": null, "e": 29321, "s": 29309, "text": "Golang Maps" }, { "code": null, "e": 29375, "s": 29321, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 29397, "s": 29375, "text": "Inheritance in GoLang" } ]
Kotlin mutableListOf() - GeeksforGeeks
04 Jul, 2020 In Kotlin, mutableListOf() method is used to instantiate MutableList Interface. MutableList class is used to create mutable lists in which the elements can be added or removed. The method mutableListOf() returns an instance of MutableList Interface and takes the array of a particular type or mixed (depends on the type of MutableList instance) elements or it can be null also. Syntax: fun <T> mutableListOf( vararg elements: T): MutableList <T> Parameters:It takes array of particular type or mixed type or null parameters. Null parameters is used when there is a need to create empty instance of MutableList. Returns: It returns the instance of MutableList Interface. Kotlin program to demonstrate mutableListOf() – fun main(args: Array<String>) { //declaring a mutable list of integers val mutableListA = mutableListOf<Int>( 1 , 2 , 3 , 4 , 3); println(mutableListA) //declaring a mutable list of strings val mutableListB = mutableListOf<String>("Geeks","for" , "geeks"); println(mutableListB) //declaring an empty mutable list of integers val mutableListC = mutableSetOf<Int>() println("Empty list "+mutableListC ) } Output: [1, 2, 3, 4, 3] [Geeks, for, geeks] Empty list [] We can add elements in a mutable list using the add() function, and remove an elements using remove () function. Kotlin program to demonstrate mutableListOf() – fun main(args: Array<String>) { var mutablelist=mutableListOf("Geeks", "For"); //adding string elements mutablelist.add("Geeks") for(i in mutablelist) println(i) println("... after removing \"For\" ...") //removing "For" mutablelist.remove("For") for(i in mutablelist) println(i)} Output: Geeks For Geeks ... after removing "For" ... Geeks Geeks Using index functions indexOf() , lastIndexOf() we can get the index of the specified element. And we can also find the elements at some specific index using elementAt() function. Kotlin program of using index – fun main(args: Array<String>){ val captains = mutableListOf("Kohli","Smith","Root","Rohit","Dhawan") println("The element at index 2 is: "+captains.elementAt(2)) println("The index of element is: "+captains.indexOf("Smith")) println("The last index of element is: "+captains.lastIndexOf("Rohit"))} Output: The element at index 2 is: Root The index of element is: 1 The last index of element is: 3 We can get the first and element of a list using first() and last() functions. fun main(args: Array<String>){ val captains = mutableListOf(1,2,3,4,"Kohli","Smith", "Root","Malinga","Dhawan","Rohit") println("The first element of the list is: "+captains.first()) println("The last element of the list is: "+captains.last())} Output: The first element of the list is: 1 The last element of the list is: Rohit We can run a for loop with an iterator which traverse all the items in the list. fun main(args: Array<String>){ //declaring a mutable list of integers val seta = mutableListOf( 1 , 2 , 3 , 4 ); //traversal of seta using an iterator 'item' for(item in seta) println( item )} Output: 1 2 3 4 Both the methods are used to check whether an element is present in the list or not? Kotlin program of using contains() and containsAll() function – fun main(args: Array<String>){ val captains = mutableListOf(1,2,3,4,"Kohli","Smith", "Root","Malinga","Rohit","Dhawan") var name = "Dhawan" println("The list contains the element $name or not?" + " "+captains.contains(name)) var num = 5 println("The list contains the element $num or not?" + " "+captains.contains(num)) println("The list contains the given elements or not?" + " "+captains.containsAll(setOf(1,3,"Root")))} Output: The list contains the element Dhawan or not? true The list contains the element 5 or not? false The list contains the given elements or not? true amanmalakar007 Kotlin Collections Picked Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Retrofit with Kotlin Coroutine in Android How to Build a Weather App in Android? How to Get Current Location in Android? ImageView in Android with Example ScrollView in Android Kotlin Coroutines on Android Kotlin extension function Suspend Function In Kotlin Coroutines How to Send Data From Activity to Fragment in Android? Notifications in Android with Example
[ { "code": null, "e": 24518, "s": 24490, "text": "\n04 Jul, 2020" }, { "code": null, "e": 24896, "s": 24518, "text": "In Kotlin, mutableListOf() method is used to instantiate MutableList Interface. MutableList class is used to create mutable lists in which the elements can be added or removed. The method mutableListOf() returns an instance of MutableList Interface and takes the array of a particular type or mixed (depends on the type of MutableList instance) elements or it can be null also." }, { "code": null, "e": 24904, "s": 24896, "text": "Syntax:" }, { "code": null, "e": 24966, "s": 24904, "text": " fun <T> mutableListOf( vararg elements: T): MutableList <T>" }, { "code": null, "e": 25131, "s": 24966, "text": "Parameters:It takes array of particular type or mixed type or null parameters. Null parameters is used when there is a need to create empty instance of MutableList." }, { "code": null, "e": 25140, "s": 25131, "text": "Returns:" }, { "code": null, "e": 25190, "s": 25140, "text": "It returns the instance of MutableList Interface." }, { "code": null, "e": 25238, "s": 25190, "text": "Kotlin program to demonstrate mutableListOf() –" }, { "code": "fun main(args: Array<String>) { //declaring a mutable list of integers val mutableListA = mutableListOf<Int>( 1 , 2 , 3 , 4 , 3); println(mutableListA) //declaring a mutable list of strings val mutableListB = mutableListOf<String>(\"Geeks\",\"for\" , \"geeks\"); println(mutableListB) //declaring an empty mutable list of integers val mutableListC = mutableSetOf<Int>() println(\"Empty list \"+mutableListC ) }", "e": 25714, "s": 25238, "text": null }, { "code": null, "e": 25722, "s": 25714, "text": "Output:" }, { "code": null, "e": 25773, "s": 25722, "text": "[1, 2, 3, 4, 3]\n[Geeks, for, geeks]\nEmpty list []\n" }, { "code": null, "e": 25886, "s": 25773, "text": "We can add elements in a mutable list using the add() function, and remove an elements using remove () function." }, { "code": null, "e": 25934, "s": 25886, "text": "Kotlin program to demonstrate mutableListOf() –" }, { "code": "fun main(args: Array<String>) { var mutablelist=mutableListOf(\"Geeks\", \"For\"); //adding string elements mutablelist.add(\"Geeks\") for(i in mutablelist) println(i) println(\"... after removing \\\"For\\\" ...\") //removing \"For\" mutablelist.remove(\"For\") for(i in mutablelist) println(i)}", "e": 26253, "s": 25934, "text": null }, { "code": null, "e": 26261, "s": 26253, "text": "Output:" }, { "code": null, "e": 26319, "s": 26261, "text": "Geeks\nFor\nGeeks\n... after removing \"For\" ...\nGeeks\nGeeks\n" }, { "code": null, "e": 26499, "s": 26319, "text": "Using index functions indexOf() , lastIndexOf() we can get the index of the specified element. And we can also find the elements at some specific index using elementAt() function." }, { "code": null, "e": 26531, "s": 26499, "text": "Kotlin program of using index –" }, { "code": "fun main(args: Array<String>){ val captains = mutableListOf(\"Kohli\",\"Smith\",\"Root\",\"Rohit\",\"Dhawan\") println(\"The element at index 2 is: \"+captains.elementAt(2)) println(\"The index of element is: \"+captains.indexOf(\"Smith\")) println(\"The last index of element is: \"+captains.lastIndexOf(\"Rohit\"))}", "e": 26847, "s": 26531, "text": null }, { "code": null, "e": 26855, "s": 26847, "text": "Output:" }, { "code": null, "e": 26946, "s": 26855, "text": "The element at index 2 is: Root\nThe index of element is: 1\nThe last index of element is: 3" }, { "code": null, "e": 27025, "s": 26946, "text": "We can get the first and element of a list using first() and last() functions." }, { "code": "fun main(args: Array<String>){ val captains = mutableListOf(1,2,3,4,\"Kohli\",\"Smith\", \"Root\",\"Malinga\",\"Dhawan\",\"Rohit\") println(\"The first element of the list is: \"+captains.first()) println(\"The last element of the list is: \"+captains.last())}", "e": 27290, "s": 27025, "text": null }, { "code": null, "e": 27298, "s": 27290, "text": "Output:" }, { "code": null, "e": 27374, "s": 27298, "text": "The first element of the list is: 1\nThe last element of the list is: Rohit\n" }, { "code": null, "e": 27455, "s": 27374, "text": "We can run a for loop with an iterator which traverse all the items in the list." }, { "code": "fun main(args: Array<String>){ //declaring a mutable list of integers val seta = mutableListOf( 1 , 2 , 3 , 4 ); //traversal of seta using an iterator 'item' for(item in seta) println( item )}", "e": 27669, "s": 27455, "text": null }, { "code": null, "e": 27677, "s": 27669, "text": "Output:" }, { "code": null, "e": 27686, "s": 27677, "text": "1\n2\n3\n4\n" }, { "code": null, "e": 27771, "s": 27686, "text": "Both the methods are used to check whether an element is present in the list or not?" }, { "code": null, "e": 27835, "s": 27771, "text": "Kotlin program of using contains() and containsAll() function –" }, { "code": "fun main(args: Array<String>){ val captains = mutableListOf(1,2,3,4,\"Kohli\",\"Smith\", \"Root\",\"Malinga\",\"Rohit\",\"Dhawan\") var name = \"Dhawan\" println(\"The list contains the element $name or not?\" + \" \"+captains.contains(name)) var num = 5 println(\"The list contains the element $num or not?\" + \" \"+captains.contains(num)) println(\"The list contains the given elements or not?\" + \" \"+captains.containsAll(setOf(1,3,\"Root\")))}", "e": 28330, "s": 27835, "text": null }, { "code": null, "e": 28338, "s": 28330, "text": "Output:" }, { "code": null, "e": 28491, "s": 28338, "text": "The list contains the element Dhawan or not? true\nThe list contains the element 5 or not? false\nThe list contains the given elements or not? true\n" }, { "code": null, "e": 28506, "s": 28491, "text": "amanmalakar007" }, { "code": null, "e": 28525, "s": 28506, "text": "Kotlin Collections" }, { "code": null, "e": 28532, "s": 28525, "text": "Picked" }, { "code": null, "e": 28539, "s": 28532, "text": "Kotlin" }, { "code": null, "e": 28637, "s": 28539, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28646, "s": 28637, "text": "Comments" }, { "code": null, "e": 28659, "s": 28646, "text": "Old Comments" }, { "code": null, "e": 28701, "s": 28659, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 28740, "s": 28701, "text": "How to Build a Weather App in Android?" }, { "code": null, "e": 28780, "s": 28740, "text": "How to Get Current Location in Android?" }, { "code": null, "e": 28814, "s": 28780, "text": "ImageView in Android with Example" }, { "code": null, "e": 28836, "s": 28814, "text": "ScrollView in Android" }, { "code": null, "e": 28865, "s": 28836, "text": "Kotlin Coroutines on Android" }, { "code": null, "e": 28891, "s": 28865, "text": "Kotlin extension function" }, { "code": null, "e": 28929, "s": 28891, "text": "Suspend Function In Kotlin Coroutines" }, { "code": null, "e": 28984, "s": 28929, "text": "How to Send Data From Activity to Fragment in Android?" } ]
Highest Rated ML Projects on Github | by Rishi Sidhu | Towards Data Science
Machine learning, as a field, is growing at a breakneck speed. Github is that whiteboard which the whole world is watching. Top quality code is being regularly posted on that infinite board of wisdom. It is obviously impossible to track all things that go on in the world of machine learning but Github has a star-rating for each project. Basically, if you star a repository, you show your appreciation for the project as well as keep track of repositories that you find interesting. This star rating then can be one of the good metrics to know the most followed projects. Let’s take a look at 5 highly rated ones. The world’s simplest tool for facial recognition. It provides an application programming interface (API) for Python and the command line. It is useful for recognising and manipulating faces in images. It is built using dlib’s state-of-the-art face recognition algorithm. The deep-learning model has an accuracy of 99.38% on the Labeled Faces in the Wild dataset. It also provides a simple face_recognition command line tool that lets you do face recognition on a folder of images from the command line itself! This library can also handle real-time face recognition fastText is an open source and free library by Facebook team for efficient learning of word representations. It is lightweight and allows users to learn text representations and sentence classifiers. It works on standard, generic hardware. Models can be reduced in size to even fit on mobile devices. Text classification is a core problem to many applications, like spam detection, sentiment analysis or smart replies. The goal of text classification is to assign documents (such as emails, posts, text messages, product reviews, etc...) to multiple categories. It is a very useful resource for NLP enthusiasts. This is a collection of resources that help you understand and utilise TensorFlow. The github repo contains a curated list of awesome TensorFlow experiments, libraries, and projects. TensorFlow is an end-to-end open source platform for machine learning designed by Google. It has a comprehensive ecosystem of tools, libraries and community resources that lets researchers create the state-of-the-art in ML. Using it developers can easily build and deploy ML powered applications. Apache PredictionIO is an open source machine learning framework for developers, data scientists, and end users. Users can use this framework to build real-world ML apps, deploy and test them. It even supports event collection, evaluation, and querying predictive results. It is based on scalable open source services like Hadoop, HBase etc. It basically takes the load off of a developer’s mind as far as Machine Learning is concerned. This repository is slightly different from all of the above as it has been shut down due to lack of funds! It is quite an interesting concept where AI is used to color images. They claimStyle2paints V4 as the current best AI driven Line-Art colorization tool. They claim that it is different from previous end-to-end image-to-image translation methods because it is the first system to colorize a line-art in real-life human workflow. Most human artists are familiar with this workflow sketching -> color filling/flattening -> gradients/details adding -> shading Style2Paints is designed according to this flow. Such a flow produces the middle image from the leftmost image in just 2 clicks. And in just 4 more clicks this is what you get Internet is an ocean and machine learning is a river that flows into it. The stars on Github are a good metric to sift through this river of treasure.
[ { "code": null, "e": 373, "s": 172, "text": "Machine learning, as a field, is growing at a breakneck speed. Github is that whiteboard which the whole world is watching. Top quality code is being regularly posted on that infinite board of wisdom." }, { "code": null, "e": 656, "s": 373, "text": "It is obviously impossible to track all things that go on in the world of machine learning but Github has a star-rating for each project. Basically, if you star a repository, you show your appreciation for the project as well as keep track of repositories that you find interesting." }, { "code": null, "e": 787, "s": 656, "text": "This star rating then can be one of the good metrics to know the most followed projects. Let’s take a look at 5 highly rated ones." }, { "code": null, "e": 1150, "s": 787, "text": "The world’s simplest tool for facial recognition. It provides an application programming interface (API) for Python and the command line. It is useful for recognising and manipulating faces in images. It is built using dlib’s state-of-the-art face recognition algorithm. The deep-learning model has an accuracy of 99.38% on the Labeled Faces in the Wild dataset." }, { "code": null, "e": 1297, "s": 1150, "text": "It also provides a simple face_recognition command line tool that lets you do face recognition on a folder of images from the command line itself!" }, { "code": null, "e": 1353, "s": 1297, "text": "This library can also handle real-time face recognition" }, { "code": null, "e": 1654, "s": 1353, "text": "fastText is an open source and free library by Facebook team for efficient learning of word representations. It is lightweight and allows users to learn text representations and sentence classifiers. It works on standard, generic hardware. Models can be reduced in size to even fit on mobile devices." }, { "code": null, "e": 1915, "s": 1654, "text": "Text classification is a core problem to many applications, like spam detection, sentiment analysis or smart replies. The goal of text classification is to assign documents (such as emails, posts, text messages, product reviews, etc...) to multiple categories." }, { "code": null, "e": 1965, "s": 1915, "text": "It is a very useful resource for NLP enthusiasts." }, { "code": null, "e": 2148, "s": 1965, "text": "This is a collection of resources that help you understand and utilise TensorFlow. The github repo contains a curated list of awesome TensorFlow experiments, libraries, and projects." }, { "code": null, "e": 2445, "s": 2148, "text": "TensorFlow is an end-to-end open source platform for machine learning designed by Google. It has a comprehensive ecosystem of tools, libraries and community resources that lets researchers create the state-of-the-art in ML. Using it developers can easily build and deploy ML powered applications." }, { "code": null, "e": 2638, "s": 2445, "text": "Apache PredictionIO is an open source machine learning framework for developers, data scientists, and end users. Users can use this framework to build real-world ML apps, deploy and test them." }, { "code": null, "e": 2787, "s": 2638, "text": "It even supports event collection, evaluation, and querying predictive results. It is based on scalable open source services like Hadoop, HBase etc." }, { "code": null, "e": 2882, "s": 2787, "text": "It basically takes the load off of a developer’s mind as far as Machine Learning is concerned." }, { "code": null, "e": 3058, "s": 2882, "text": "This repository is slightly different from all of the above as it has been shut down due to lack of funds! It is quite an interesting concept where AI is used to color images." }, { "code": null, "e": 3142, "s": 3058, "text": "They claimStyle2paints V4 as the current best AI driven Line-Art colorization tool." }, { "code": null, "e": 3368, "s": 3142, "text": "They claim that it is different from previous end-to-end image-to-image translation methods because it is the first system to colorize a line-art in real-life human workflow. Most human artists are familiar with this workflow" }, { "code": null, "e": 3445, "s": 3368, "text": "sketching -> color filling/flattening -> gradients/details adding -> shading" }, { "code": null, "e": 3574, "s": 3445, "text": "Style2Paints is designed according to this flow. Such a flow produces the middle image from the leftmost image in just 2 clicks." }, { "code": null, "e": 3621, "s": 3574, "text": "And in just 4 more clicks this is what you get" } ]
C# | Dictionary.Remove Method - GeeksforGeeks
01 Feb, 2019 This method is used to remove the value with the specified key from the Dictionary<TKey,TValue>. Syntax: public bool Remove (TKey key); Return Value: This method returns true if the element is successfully found and removed; otherwise it returns false. This method returns false if key is not found in the Dictionary. Exception: This method will give ArgumentNullException if the key is null. Below are the programs to illustrate the use of above-discussed method: Example 1: // C# code to remove the entry with// the specified key from the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add("Australia", "Canberra"); myDict.Add("Belgium", "Brussels"); myDict.Add("Netherlands", "Amsterdam"); myDict.Add("China", "Beijing"); myDict.Add("Russia", "Moscow"); myDict.Add("India", "New Delhi"); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs"+ " in myDict are : " + myDict.Count); // Remove the entry with the specified // key from the Dictionary myDict.Remove("Russia"); Console.WriteLine("After remove operation"); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs"+ " in myDict are : " + myDict.Count); }} Total key/value pairs in myDict are : 6 After remove operation Total key/value pairs in myDict are : 5 Example 2: // C# code to remove the entry with// the specified key from the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<int, int> myDict = new Dictionary<int, int>(); // Adding key/value pairs in myDict myDict.Add(9, 8); myDict.Add(3, 4); myDict.Add(4, 7); myDict.Add(1, 7); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs "+ "in myDict are : " + myDict.Count); // Remove the entry with the specified // key from the Dictionary myDict.Remove(9); Console.WriteLine("After remove operation"); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs in"+ " myDict are : " + myDict.Count); }} Total key/value pairs in myDict are : 4 After remove operation Total key/value pairs in myDict are : 3 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.remove?view=netframework-4.7.2 CSharp Dictionary Class CSharp-Generic-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Method Overriding C# Dictionary with examples Difference between Ref and Out keywords in C# C# | Delegates Top 50 C# Interview Questions & Answers C# | Constructors Extension Method in C# Introduction to .NET Framework C# | Abstract Classes C# | Class and Object
[ { "code": null, "e": 24717, "s": 24689, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24814, "s": 24717, "text": "This method is used to remove the value with the specified key from the Dictionary<TKey,TValue>." }, { "code": null, "e": 24822, "s": 24814, "text": "Syntax:" }, { "code": null, "e": 24854, "s": 24822, "text": "public bool Remove (TKey key);\n" }, { "code": null, "e": 25036, "s": 24854, "text": "Return Value: This method returns true if the element is successfully found and removed; otherwise it returns false. This method returns false if key is not found in the Dictionary." }, { "code": null, "e": 25111, "s": 25036, "text": "Exception: This method will give ArgumentNullException if the key is null." }, { "code": null, "e": 25183, "s": 25111, "text": "Below are the programs to illustrate the use of above-discussed method:" }, { "code": null, "e": 25194, "s": 25183, "text": "Example 1:" }, { "code": "// C# code to remove the entry with// the specified key from the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add(\"Australia\", \"Canberra\"); myDict.Add(\"Belgium\", \"Brussels\"); myDict.Add(\"Netherlands\", \"Amsterdam\"); myDict.Add(\"China\", \"Beijing\"); myDict.Add(\"Russia\", \"Moscow\"); myDict.Add(\"India\", \"New Delhi\"); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs\"+ \" in myDict are : \" + myDict.Count); // Remove the entry with the specified // key from the Dictionary myDict.Remove(\"Russia\"); Console.WriteLine(\"After remove operation\"); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs\"+ \" in myDict are : \" + myDict.Count); }}", "e": 26326, "s": 25194, "text": null }, { "code": null, "e": 26430, "s": 26326, "text": "Total key/value pairs in myDict are : 6\nAfter remove operation\nTotal key/value pairs in myDict are : 5\n" }, { "code": null, "e": 26441, "s": 26430, "text": "Example 2:" }, { "code": "// C# code to remove the entry with// the specified key from the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<int, int> myDict = new Dictionary<int, int>(); // Adding key/value pairs in myDict myDict.Add(9, 8); myDict.Add(3, 4); myDict.Add(4, 7); myDict.Add(1, 7); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs \"+ \"in myDict are : \" + myDict.Count); // Remove the entry with the specified // key from the Dictionary myDict.Remove(9); Console.WriteLine(\"After remove operation\"); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs in\"+ \" myDict are : \" + myDict.Count); }}", "e": 27410, "s": 26441, "text": null }, { "code": null, "e": 27514, "s": 27410, "text": "Total key/value pairs in myDict are : 4\nAfter remove operation\nTotal key/value pairs in myDict are : 3\n" }, { "code": null, "e": 27525, "s": 27514, "text": "Reference:" }, { "code": null, "e": 27640, "s": 27525, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.remove?view=netframework-4.7.2" }, { "code": null, "e": 27664, "s": 27640, "text": "CSharp Dictionary Class" }, { "code": null, "e": 27689, "s": 27664, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 27703, "s": 27689, "text": "CSharp-method" }, { "code": null, "e": 27706, "s": 27703, "text": "C#" }, { "code": null, "e": 27804, "s": 27706, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27813, "s": 27804, "text": "Comments" }, { "code": null, "e": 27826, "s": 27813, "text": "Old Comments" }, { "code": null, "e": 27849, "s": 27826, "text": "C# | Method Overriding" }, { "code": null, "e": 27877, "s": 27849, "text": "C# Dictionary with examples" }, { "code": null, "e": 27923, "s": 27877, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 27938, "s": 27923, "text": "C# | Delegates" }, { "code": null, "e": 27978, "s": 27938, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27996, "s": 27978, "text": "C# | Constructors" }, { "code": null, "e": 28019, "s": 27996, "text": "Extension Method in C#" }, { "code": null, "e": 28050, "s": 28019, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28072, "s": 28050, "text": "C# | Abstract Classes" } ]
Running Chi-Square Tests with Die Roll Data in Python | by Jake Huneycutt | Towards Data Science
Sometime in the early part of this decade, I caught onto the board gaming craze. Every month or so, I’d scour through BoardGameGeek’s (“BGG”) highest rated games for new board games to buy. There are literally tens of thousands of board games listed BGG, many with reviews and critiques. My favorite strategy game is not an unusual pick. Rather, it’s currently the #4 rated game of all-time on BGG and a former #1. That game is Twilight Struggle. Twilight Struggle is a card-driven 2-player strategy game with a “Cold War” theme. It some ways, it feels like a combination of chess and poker. One side plays the United States and the other side plays the Soviet Union. The game has the same paranoid feel as the real Cold War, as you’re constantly having to guess which cards your opponent might have and how they can harm you with those cards. While skill is very important in TS, luck also plays a heavy role in outcomes. The game includes coups, realignments, war cards, and a space race, all of which are determined by die rolls. A few years ago, after a successful crowd-funding campaign, an online version of Twilight Struggle was released for PCs and Macs (available on Steam). After playing a few hundred online games, I decided I wanted to try to create a luck-measurement system to evaluate my own results. In the process, I started collecting the results for die rolls on “coups” and “war cards”. And this is where things get interesting: my die roll samples had surprising distributions. After 279 rolls, my average roll was 3.254. After 303 rolls, my opponent’s average roll was 3.855. I wanted to know how unusual this distribution was, so I conducted some chi-square tests in Python. Understanding Chi-Square Tests Before we look at those tests, however, I’ll explain chi-square in more detail. The chi-square statistical test is used to determine whether there’s a significant difference between an expected distribution and an actual distribution. It’s typically used with categorical data such as educational attainment, colors, or gender. Dice rolls are a great example of data suited for chi-square testing. If we roll a standard 6-sided die a thousand times, we know that each number should come up approximately 1/6 of the time (i.e. 16.66667%). A chi-square test can help determine whether a die is ‘fair’ or if die-roll generators (such as those used in software) are generating ‘random’ results. However, die rolls are an example of a variable where the ‘expected distribution’ is known. This isn’t always the case. Sometimes, our ‘expected distribution’ is estimated through data. Let’s pretend for a second we don’t know the expected frequency of die rolls. We’d have to estimate the expected frequency through data samples. Let’s conduct a few samples to try to ascertain the frequency of each roll. I decided to do 4 samples of die rolls manually (i.e. with actual dice), the first 3 samples were 35 rolls each, and the last sample as 45 rolls. These are smaller samples than we prefer, but I wanted to give us some real data to work with. Here is my distribution of rolls, with the four samples denoted by letters ‘a’, ‘b’, ‘c’, and ‘d’. Given what we know about probability, with 150 rolls, we should expect each number to come up approximately 25 times (i.e. 1/6 of 150). We can see that this happened for 1, 5, and 6, but 4 came up quite a bit more than expected, and 2 and 3 were a bit underrepresented. This is likely due to our relatively small sample size (see “law of large numbers”), but we’ll work with it. Let’s run a chi-square test for independence for variables in a contingency table on this data set. First I’ll input the data. import numpy as npa1 = [6, 4, 5, 10]a2 = [8, 5, 3, 3]a3 = [5, 4, 8, 4]a4 = [4, 11, 7, 13]a5 = [5, 8, 7, 6]a6 = [7, 3, 5, 9]dice = np.array([a1, a2, a3, a4, a5, a6]) Then, I ran the test using SciPy Stats library from scipy import statsstats.chi2_contingency(dice) Unfortunately, while it’s a very useful tool, SciPy does not provide the results in the prettiest fashion. I’ll explain what all of this means. The first value (16.49) is the chi-square statistic. Skip down to the third number in the output; that’s ‘degrees of freedom.’ This can be calculated by taking the number of rows minus one and multiplying this result by the number of columns minus one. In this instance: Rows = 6 [die rolls 1–6] Columns = 4 [samples] So we take (6–1) and multiply by (4–1) to get 15 degrees of freedom. With the chi-square stat and the degrees of freedoms, we can find the p-value. The p-value is what we use to determine significance (or independence in this case). Depending on the test, we are generally looking for a threshold at either 0.05 or 0.01. Our test is significant (i.e. we reject the null hypothesis) if we get a p-value below our threshold. For our purposes, we’ll use 0.01 as the threshold. In this particular example, the p-value (the second number in our output: 0.3502) is far 0.01, and thus we have not met the threshold for statistical significance. Now that I’ve explained what everything means, we can create easier-to-read output code in SciPy. chi2_stat, p_val, dof, ex = stats.chi2_contingency(dice2)print("===Chi2 Stat===")print(chi2_stat)print("\n")print("===Degrees of Freedom===")print(dof)print("\n")print("===P-Value===")print(p_val)print("\n")print("===Contingency Table===")print(ex) This will produce a much more coherent output: Finally, the array at the end of the output is the contingency table with expected values based on all of our samples. Note in this case, our contingency table produced values that are, in some cases, quite a bit off of what we know we should expect with die rolls. This is because we are using too small of a sample to accurate measure the population. Running a Large Sample to Get Expected Population Distribution We can run a much larger sample to see how this methodology can work better. Since I’m not willing to hand-roll a die thousands of times, we’ll use Python to do this. We need np.random.randint and np.unique. I did 5 samples of 1,000 die rolls each. r1 = np.random.randint(1,7,1000)r2 = np.random.randint(1,7,1000)r3 = np.random.randint(1,7,1000)r4 = np.random.randint(1,7,1000)r5 = np.random.randint(1,7,1000) Then saved the results via np.unique. unique, counts1 = np.unique(r1, return_counts=True)unique, counts2 = np.unique(r2, return_counts=True)unique, counts3 = np.unique(r3, return_counts=True)unique, counts4 = np.unique(r4, return_counts=True)unique, counts5 = np.unique(r5, return_counts=True) Now, we combine our arrays to run stats.chi2_contingency: dice = np.array([counts1, counts2, counts3, counts4, counts5]) And let’s the run the test. chi2_stat, p_val, dof, ex = stats.chi2_contingency(dice) Here were the results. Notice our contingency table now produces a more uniform expected distribution. It’s still slightly off (we should expect each number to come up about 166.7 times in a sample of 1,000 die rolls), but we’re getting very close to that distribution. I decided to run the test one more time, this time with 5 samples of 10,000 die rolls. We can see our distribution closes in even more on the known population distribution (16.667% chance for each number or 1,666.7 out of 10,000 rolls in sample). The interesting thing about this is that since we know the real expected distribution, we can see how samples allow us to estimate the population distribution. Twilight Struggle Dice Chi-Square Test Now, let’s jump into our online Twilight Struggle dice data. For our actual test, we don’t need the contingency table. We know the expected distribution. For a 6 sided die, each number is expected to come up approximately 1/6 of the time. Since we know the expected distribution, we can use scipy.stats.chisquare rather than chi2_contingency. For my Twilight Struggle dice data, I have two samples: die rolls for myself and die rolls for my opponents. Our null hypothesis is that the die rolls are randomly distributed (and hence, evenly distributed). For my data, I rolled 279 times. We divide by 6 to find the expected distribution (46.5 for each number). When running scipy.stats.chisquare, be careful to get the order of the arguments correct; otherwise, you’ll get inaccurate results. The first argument (f_obs) is for the ‘actual results’ while the second argument (f_exp) is for ‘expected results’. my_rolls_expected = [46.5, 46.5, 46.5, 46.5, 46.5, 46.5]my_rolls_actual = [59, 63, 37, 38, 32, 50]stats.chisquare(my_rolls_actual, my_rolls_expected) Running this test, we come up with a p-value of 0.0037. This is below 0.01 and statistically significant. This means there’s only about a 0.4% chance that we’d see this result if the dice were truly random. Next let’s look at my opponent die rolls. My opponents rolled 303 times. Once again, we divide by 6 to find the expected distribution of 50.5. We compare to the actual distribution. opp_rolls_expected = [50.5,50.5,50.5,50.5,50.5,50.5]opp_rolls_actual = [39,39,46,54,53,72]stats.chisquare(opp_rolls_actual, opp_rolls_expected) We find a similar result. Our p-value is 0.0097, which is also below 0.01, indicating that there’s slightly less than a 1% chance that we’d observe this distribution if the dice rolls were truly randomized. While I’ve anecdotally noticed odd patterns in the die rolls (which I had previously waived off as ‘observation bias’), I’m actually a little bit surprised by these results. For both my die rolls and opponent die rolls in our 2 random samples, we can reject the null hypothesis that the dice are truly random. This is interesting and I’ve decided I’m going to continue collecting data to see if I can replicate the results in the future. Unfortunately, it will likely take me a couple more months to build up a few more meaningful data samples. Conclusions Chi-square is a great tool to compare results involving categorical data. We can see how a sample deviates from the expected distribution. Python’s SciPy library provides great tools for running chi-square tests. Further Resources To understand chi-square better, I recommend Khan Academy’s excellent series of videos.
[ { "code": null, "e": 618, "s": 171, "text": "Sometime in the early part of this decade, I caught onto the board gaming craze. Every month or so, I’d scour through BoardGameGeek’s (“BGG”) highest rated games for new board games to buy. There are literally tens of thousands of board games listed BGG, many with reviews and critiques. My favorite strategy game is not an unusual pick. Rather, it’s currently the #4 rated game of all-time on BGG and a former #1. That game is Twilight Struggle." }, { "code": null, "e": 1015, "s": 618, "text": "Twilight Struggle is a card-driven 2-player strategy game with a “Cold War” theme. It some ways, it feels like a combination of chess and poker. One side plays the United States and the other side plays the Soviet Union. The game has the same paranoid feel as the real Cold War, as you’re constantly having to guess which cards your opponent might have and how they can harm you with those cards." }, { "code": null, "e": 1204, "s": 1015, "text": "While skill is very important in TS, luck also plays a heavy role in outcomes. The game includes coups, realignments, war cards, and a space race, all of which are determined by die rolls." }, { "code": null, "e": 1670, "s": 1204, "text": "A few years ago, after a successful crowd-funding campaign, an online version of Twilight Struggle was released for PCs and Macs (available on Steam). After playing a few hundred online games, I decided I wanted to try to create a luck-measurement system to evaluate my own results. In the process, I started collecting the results for die rolls on “coups” and “war cards”. And this is where things get interesting: my die roll samples had surprising distributions." }, { "code": null, "e": 1869, "s": 1670, "text": "After 279 rolls, my average roll was 3.254. After 303 rolls, my opponent’s average roll was 3.855. I wanted to know how unusual this distribution was, so I conducted some chi-square tests in Python." }, { "code": null, "e": 1900, "s": 1869, "text": "Understanding Chi-Square Tests" }, { "code": null, "e": 1980, "s": 1900, "text": "Before we look at those tests, however, I’ll explain chi-square in more detail." }, { "code": null, "e": 2228, "s": 1980, "text": "The chi-square statistical test is used to determine whether there’s a significant difference between an expected distribution and an actual distribution. It’s typically used with categorical data such as educational attainment, colors, or gender." }, { "code": null, "e": 2591, "s": 2228, "text": "Dice rolls are a great example of data suited for chi-square testing. If we roll a standard 6-sided die a thousand times, we know that each number should come up approximately 1/6 of the time (i.e. 16.66667%). A chi-square test can help determine whether a die is ‘fair’ or if die-roll generators (such as those used in software) are generating ‘random’ results." }, { "code": null, "e": 2777, "s": 2591, "text": "However, die rolls are an example of a variable where the ‘expected distribution’ is known. This isn’t always the case. Sometimes, our ‘expected distribution’ is estimated through data." }, { "code": null, "e": 3338, "s": 2777, "text": "Let’s pretend for a second we don’t know the expected frequency of die rolls. We’d have to estimate the expected frequency through data samples. Let’s conduct a few samples to try to ascertain the frequency of each roll. I decided to do 4 samples of die rolls manually (i.e. with actual dice), the first 3 samples were 35 rolls each, and the last sample as 45 rolls. These are smaller samples than we prefer, but I wanted to give us some real data to work with. Here is my distribution of rolls, with the four samples denoted by letters ‘a’, ‘b’, ‘c’, and ‘d’." }, { "code": null, "e": 3717, "s": 3338, "text": "Given what we know about probability, with 150 rolls, we should expect each number to come up approximately 25 times (i.e. 1/6 of 150). We can see that this happened for 1, 5, and 6, but 4 came up quite a bit more than expected, and 2 and 3 were a bit underrepresented. This is likely due to our relatively small sample size (see “law of large numbers”), but we’ll work with it." }, { "code": null, "e": 3844, "s": 3717, "text": "Let’s run a chi-square test for independence for variables in a contingency table on this data set. First I’ll input the data." }, { "code": null, "e": 4009, "s": 3844, "text": "import numpy as npa1 = [6, 4, 5, 10]a2 = [8, 5, 3, 3]a3 = [5, 4, 8, 4]a4 = [4, 11, 7, 13]a5 = [5, 8, 7, 6]a6 = [7, 3, 5, 9]dice = np.array([a1, a2, a3, a4, a5, a6])" }, { "code": null, "e": 4056, "s": 4009, "text": "Then, I ran the test using SciPy Stats library" }, { "code": null, "e": 4108, "s": 4056, "text": "from scipy import statsstats.chi2_contingency(dice)" }, { "code": null, "e": 4215, "s": 4108, "text": "Unfortunately, while it’s a very useful tool, SciPy does not provide the results in the prettiest fashion." }, { "code": null, "e": 4505, "s": 4215, "text": "I’ll explain what all of this means. The first value (16.49) is the chi-square statistic. Skip down to the third number in the output; that’s ‘degrees of freedom.’ This can be calculated by taking the number of rows minus one and multiplying this result by the number of columns minus one." }, { "code": null, "e": 4523, "s": 4505, "text": "In this instance:" }, { "code": null, "e": 4548, "s": 4523, "text": "Rows = 6 [die rolls 1–6]" }, { "code": null, "e": 4570, "s": 4548, "text": "Columns = 4 [samples]" }, { "code": null, "e": 4639, "s": 4570, "text": "So we take (6–1) and multiply by (4–1) to get 15 degrees of freedom." }, { "code": null, "e": 4993, "s": 4639, "text": "With the chi-square stat and the degrees of freedoms, we can find the p-value. The p-value is what we use to determine significance (or independence in this case). Depending on the test, we are generally looking for a threshold at either 0.05 or 0.01. Our test is significant (i.e. we reject the null hypothesis) if we get a p-value below our threshold." }, { "code": null, "e": 5208, "s": 4993, "text": "For our purposes, we’ll use 0.01 as the threshold. In this particular example, the p-value (the second number in our output: 0.3502) is far 0.01, and thus we have not met the threshold for statistical significance." }, { "code": null, "e": 5306, "s": 5208, "text": "Now that I’ve explained what everything means, we can create easier-to-read output code in SciPy." }, { "code": null, "e": 5555, "s": 5306, "text": "chi2_stat, p_val, dof, ex = stats.chi2_contingency(dice2)print(\"===Chi2 Stat===\")print(chi2_stat)print(\"\\n\")print(\"===Degrees of Freedom===\")print(dof)print(\"\\n\")print(\"===P-Value===\")print(p_val)print(\"\\n\")print(\"===Contingency Table===\")print(ex)" }, { "code": null, "e": 5602, "s": 5555, "text": "This will produce a much more coherent output:" }, { "code": null, "e": 5955, "s": 5602, "text": "Finally, the array at the end of the output is the contingency table with expected values based on all of our samples. Note in this case, our contingency table produced values that are, in some cases, quite a bit off of what we know we should expect with die rolls. This is because we are using too small of a sample to accurate measure the population." }, { "code": null, "e": 6018, "s": 5955, "text": "Running a Large Sample to Get Expected Population Distribution" }, { "code": null, "e": 6267, "s": 6018, "text": "We can run a much larger sample to see how this methodology can work better. Since I’m not willing to hand-roll a die thousands of times, we’ll use Python to do this. We need np.random.randint and np.unique. I did 5 samples of 1,000 die rolls each." }, { "code": null, "e": 6428, "s": 6267, "text": "r1 = np.random.randint(1,7,1000)r2 = np.random.randint(1,7,1000)r3 = np.random.randint(1,7,1000)r4 = np.random.randint(1,7,1000)r5 = np.random.randint(1,7,1000)" }, { "code": null, "e": 6466, "s": 6428, "text": "Then saved the results via np.unique." }, { "code": null, "e": 6722, "s": 6466, "text": "unique, counts1 = np.unique(r1, return_counts=True)unique, counts2 = np.unique(r2, return_counts=True)unique, counts3 = np.unique(r3, return_counts=True)unique, counts4 = np.unique(r4, return_counts=True)unique, counts5 = np.unique(r5, return_counts=True)" }, { "code": null, "e": 6780, "s": 6722, "text": "Now, we combine our arrays to run stats.chi2_contingency:" }, { "code": null, "e": 6843, "s": 6780, "text": "dice = np.array([counts1, counts2, counts3, counts4, counts5])" }, { "code": null, "e": 6871, "s": 6843, "text": "And let’s the run the test." }, { "code": null, "e": 6928, "s": 6871, "text": "chi2_stat, p_val, dof, ex = stats.chi2_contingency(dice)" }, { "code": null, "e": 6951, "s": 6928, "text": "Here were the results." }, { "code": null, "e": 7198, "s": 6951, "text": "Notice our contingency table now produces a more uniform expected distribution. It’s still slightly off (we should expect each number to come up about 166.7 times in a sample of 1,000 die rolls), but we’re getting very close to that distribution." }, { "code": null, "e": 7285, "s": 7198, "text": "I decided to run the test one more time, this time with 5 samples of 10,000 die rolls." }, { "code": null, "e": 7605, "s": 7285, "text": "We can see our distribution closes in even more on the known population distribution (16.667% chance for each number or 1,666.7 out of 10,000 rolls in sample). The interesting thing about this is that since we know the real expected distribution, we can see how samples allow us to estimate the population distribution." }, { "code": null, "e": 7644, "s": 7605, "text": "Twilight Struggle Dice Chi-Square Test" }, { "code": null, "e": 7705, "s": 7644, "text": "Now, let’s jump into our online Twilight Struggle dice data." }, { "code": null, "e": 7987, "s": 7705, "text": "For our actual test, we don’t need the contingency table. We know the expected distribution. For a 6 sided die, each number is expected to come up approximately 1/6 of the time. Since we know the expected distribution, we can use scipy.stats.chisquare rather than chi2_contingency." }, { "code": null, "e": 8196, "s": 7987, "text": "For my Twilight Struggle dice data, I have two samples: die rolls for myself and die rolls for my opponents. Our null hypothesis is that the die rolls are randomly distributed (and hence, evenly distributed)." }, { "code": null, "e": 8550, "s": 8196, "text": "For my data, I rolled 279 times. We divide by 6 to find the expected distribution (46.5 for each number). When running scipy.stats.chisquare, be careful to get the order of the arguments correct; otherwise, you’ll get inaccurate results. The first argument (f_obs) is for the ‘actual results’ while the second argument (f_exp) is for ‘expected results’." }, { "code": null, "e": 8701, "s": 8550, "text": "my_rolls_expected = [46.5, 46.5, 46.5, 46.5, 46.5, 46.5]my_rolls_actual = [59, 63, 37, 38, 32, 50]stats.chisquare(my_rolls_actual, my_rolls_expected)" }, { "code": null, "e": 8757, "s": 8701, "text": "Running this test, we come up with a p-value of 0.0037." }, { "code": null, "e": 8908, "s": 8757, "text": "This is below 0.01 and statistically significant. This means there’s only about a 0.4% chance that we’d see this result if the dice were truly random." }, { "code": null, "e": 9090, "s": 8908, "text": "Next let’s look at my opponent die rolls. My opponents rolled 303 times. Once again, we divide by 6 to find the expected distribution of 50.5. We compare to the actual distribution." }, { "code": null, "e": 9235, "s": 9090, "text": "opp_rolls_expected = [50.5,50.5,50.5,50.5,50.5,50.5]opp_rolls_actual = [39,39,46,54,53,72]stats.chisquare(opp_rolls_actual, opp_rolls_expected)" }, { "code": null, "e": 9261, "s": 9235, "text": "We find a similar result." }, { "code": null, "e": 9442, "s": 9261, "text": "Our p-value is 0.0097, which is also below 0.01, indicating that there’s slightly less than a 1% chance that we’d observe this distribution if the dice rolls were truly randomized." }, { "code": null, "e": 9752, "s": 9442, "text": "While I’ve anecdotally noticed odd patterns in the die rolls (which I had previously waived off as ‘observation bias’), I’m actually a little bit surprised by these results. For both my die rolls and opponent die rolls in our 2 random samples, we can reject the null hypothesis that the dice are truly random." }, { "code": null, "e": 9987, "s": 9752, "text": "This is interesting and I’ve decided I’m going to continue collecting data to see if I can replicate the results in the future. Unfortunately, it will likely take me a couple more months to build up a few more meaningful data samples." }, { "code": null, "e": 9999, "s": 9987, "text": "Conclusions" }, { "code": null, "e": 10212, "s": 9999, "text": "Chi-square is a great tool to compare results involving categorical data. We can see how a sample deviates from the expected distribution. Python’s SciPy library provides great tools for running chi-square tests." }, { "code": null, "e": 10230, "s": 10212, "text": "Further Resources" } ]
How to Show all the previously connected WiFi Networks using CMD in Windows? - GeeksforGeeks
12 Jun, 2020 Wi-Fi(Wireless Fidelity) Launched in September 1997 is affiliated with WLAN (Wireless Local Area Network).It is a wireless communication technology that uses radio waves to provide a high-speed network and Internet connection.Sometimes there is a need to know the previously connected WiFi networks to get details on some network. There is a wide range of Softwares available for the same. But, this can be done easily with the use of the command prompt of the windows. To show the History of previously connected WiFi networks using command-prompt of windows, follow the steps given below: Step 1: Open Command prompt by typing ‘cmd’ in the search bar and press enter. Step 2: Now type the following command and press Enter: netsh wlan show profile All the previously connected WiFi networks are now visible. GBlog How To Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Front End Developer Skills That You Need in 2022 DSA Sheet by Love Babbar 6 Best IDE's For Python in 2022 A Freshers Guide To Programming ML | Underfitting and Overfitting How to Install PIP on Windows ? How to Find the Wi-Fi Password Using CMD in Windows? How to install Jupyter Notebook on Windows? How to Align Text in HTML? How to Install OpenCV for Python on Windows?
[ { "code": null, "e": 24593, "s": 24565, "text": "\n12 Jun, 2020" }, { "code": null, "e": 25063, "s": 24593, "text": "Wi-Fi(Wireless Fidelity) Launched in September 1997 is affiliated with WLAN (Wireless Local Area Network).It is a wireless communication technology that uses radio waves to provide a high-speed network and Internet connection.Sometimes there is a need to know the previously connected WiFi networks to get details on some network. There is a wide range of Softwares available for the same. But, this can be done easily with the use of the command prompt of the windows." }, { "code": null, "e": 25184, "s": 25063, "text": "To show the History of previously connected WiFi networks using command-prompt of windows, follow the steps given below:" }, { "code": null, "e": 25263, "s": 25184, "text": "Step 1: Open Command prompt by typing ‘cmd’ in the search bar and press enter." }, { "code": null, "e": 25319, "s": 25263, "text": "Step 2: Now type the following command and press Enter:" }, { "code": null, "e": 25343, "s": 25319, "text": "netsh wlan show profile" }, { "code": null, "e": 25403, "s": 25343, "text": "All the previously connected WiFi networks are now visible." }, { "code": null, "e": 25409, "s": 25403, "text": "GBlog" }, { "code": null, "e": 25416, "s": 25409, "text": "How To" }, { "code": null, "e": 25514, "s": 25416, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25523, "s": 25514, "text": "Comments" }, { "code": null, "e": 25536, "s": 25523, "text": "Old Comments" }, { "code": null, "e": 25592, "s": 25536, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 25617, "s": 25592, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 25649, "s": 25617, "text": "6 Best IDE's For Python in 2022" }, { "code": null, "e": 25681, "s": 25649, "text": "A Freshers Guide To Programming" }, { "code": null, "e": 25715, "s": 25681, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 25747, "s": 25715, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25800, "s": 25747, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 25844, "s": 25800, "text": "How to install Jupyter Notebook on Windows?" }, { "code": null, "e": 25871, "s": 25844, "text": "How to Align Text in HTML?" } ]
How to set the margin of ImageView programmatically in Android using Kotlin ?
This example demonstrates how to set the margin of ImageView programmatically 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:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/image" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.os.Bundle import android.widget.ImageView import android.widget.RelativeLayout import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { lateinit var imageView: ImageView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" imageView = findViewById(R.id.imageView) val layoutParams = imageView.layoutParams as RelativeLayout.LayoutParams layoutParams.setMargins(100, 100, 100, 100) imageView.layoutParams = layoutParams } } 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="com.example.q11"> <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": 1165, "s": 1062, "text": "This example demonstrates how to set the margin of ImageView programmatically in Android using Kotlin." }, { "code": null, "e": 1294, "s": 1165, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1359, "s": 1294, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1833, "s": 1359, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:background=\"@drawable/image\" />\n</RelativeLayout>" }, { "code": null, "e": 1888, "s": 1833, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 2505, "s": 1888, "text": "import android.os.Bundle\nimport android.widget.ImageView\nimport android.widget.RelativeLayout\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var imageView: ImageView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n imageView = findViewById(R.id.imageView)\n val layoutParams = imageView.layoutParams as RelativeLayout.LayoutParams\n layoutParams.setMargins(100, 100, 100, 100)\n imageView.layoutParams = layoutParams\n }\n}" }, { "code": null, "e": 2560, "s": 2505, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3235, "s": 2560, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\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": 3584, "s": 3235, "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" } ]
Align Widget in Flutter - GeeksforGeeks
03 Jun, 2021 Align Widget is the widget that is used to align its child within itself and optionally sizes itself based on the child’s size. Align Widget is quite flexible and can change its size according to the size of its child. Constructor of Align class: Syntax: Align({Key key, AlignmentGeometry alignment: Alignment.center, double widthFactor, double heightFactor, Widget child}) Properties of Align Widget: alignment: It sets the alignment. child: The child widget in the tree. hashCode: The hashcode for the object. heightFactor: It sets its height to the child’s height multiplied by this heightFactor. key: It is used to controlling how one widget replaces the other one. runtimeType: It is a representation of runtime type. widthFactor: It sets its width to the child’s width multiplied by this widthFactor. Example 1: Aligning the text at the center of the container. The main.dart file: Dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'TextSpan', theme: ThemeData( primarySwatch: Colors.green, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); }} class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks Align Widget'), backgroundColor: Colors.green), body: Center( child: Container( height: 120.0, width: 120.0, color: Colors.blue[50], child: Align( alignment: Alignment.center, child: Text( "Geeky Text", style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), ), ), ))); }} Output: Example 2: Aligning the Image at the top right of the container. The main.dart file: Dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'TextSpan', theme: ThemeData( primarySwatch: Colors.green, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); }} class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks Align Widget'), backgroundColor: Colors.green), body: Center( child: Container( height: 240.0, width: 240.0, color: Colors.green, child: Align( alignment: Alignment.topRight, child: Image.network( "https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200-1.png", width: 100, )), ))); }} Output: adnanirshad158 android Flutter Flutter-widgets Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar Flutter - BorderRadius Widget ListView Class in Flutter Flutter - Stack Widget What is widgets in Flutter? Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - BorderRadius Widget Flutter - Stack Widget Flutter - Flexible Widget
[ { "code": null, "e": 23930, "s": 23902, "text": "\n03 Jun, 2021" }, { "code": null, "e": 24149, "s": 23930, "text": "Align Widget is the widget that is used to align its child within itself and optionally sizes itself based on the child’s size. Align Widget is quite flexible and can change its size according to the size of its child." }, { "code": null, "e": 24177, "s": 24149, "text": "Constructor of Align class:" }, { "code": null, "e": 24307, "s": 24177, "text": "Syntax:\nAlign({Key key, \nAlignmentGeometry alignment: Alignment.center,\ndouble widthFactor, \ndouble heightFactor, \nWidget child})" }, { "code": null, "e": 24335, "s": 24307, "text": "Properties of Align Widget:" }, { "code": null, "e": 24370, "s": 24335, "text": "alignment: It sets the alignment." }, { "code": null, "e": 24408, "s": 24370, "text": "child: The child widget in the tree." }, { "code": null, "e": 24447, "s": 24408, "text": "hashCode: The hashcode for the object." }, { "code": null, "e": 24535, "s": 24447, "text": "heightFactor: It sets its height to the child’s height multiplied by this heightFactor." }, { "code": null, "e": 24605, "s": 24535, "text": "key: It is used to controlling how one widget replaces the other one." }, { "code": null, "e": 24658, "s": 24605, "text": "runtimeType: It is a representation of runtime type." }, { "code": null, "e": 24742, "s": 24658, "text": "widthFactor: It sets its width to the child’s width multiplied by this widthFactor." }, { "code": null, "e": 24803, "s": 24742, "text": "Example 1: Aligning the text at the center of the container." }, { "code": null, "e": 24823, "s": 24803, "text": "The main.dart file:" }, { "code": null, "e": 24828, "s": 24823, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'TextSpan', theme: ThemeData( primarySwatch: Colors.green, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); }} class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks Align Widget'), backgroundColor: Colors.green), body: Center( child: Container( height: 120.0, width: 120.0, color: Colors.blue[50], child: Align( alignment: Alignment.center, child: Text( \"Geeky Text\", style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), ), ), ))); }}", "e": 25885, "s": 24828, "text": null }, { "code": null, "e": 25893, "s": 25885, "text": "Output:" }, { "code": null, "e": 25958, "s": 25893, "text": "Example 2: Aligning the Image at the top right of the container." }, { "code": null, "e": 25978, "s": 25958, "text": "The main.dart file:" }, { "code": null, "e": 25983, "s": 25978, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'TextSpan', theme: ThemeData( primarySwatch: Colors.green, ), home: MyHomePage(), debugShowCheckedModeBanner: false, ); }} class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('GeeksforGeeks Align Widget'), backgroundColor: Colors.green), body: Center( child: Container( height: 240.0, width: 240.0, color: Colors.green, child: Align( alignment: Alignment.topRight, child: Image.network( \"https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200-1.png\", width: 100, )), ))); }}", "e": 27054, "s": 25983, "text": null }, { "code": null, "e": 27062, "s": 27054, "text": "Output:" }, { "code": null, "e": 27077, "s": 27062, "text": "adnanirshad158" }, { "code": null, "e": 27085, "s": 27077, "text": "android" }, { "code": null, "e": 27093, "s": 27085, "text": "Flutter" }, { "code": null, "e": 27109, "s": 27093, "text": "Flutter-widgets" }, { "code": null, "e": 27114, "s": 27109, "text": "Dart" }, { "code": null, "e": 27122, "s": 27114, "text": "Flutter" }, { "code": null, "e": 27220, "s": 27122, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27229, "s": 27220, "text": "Comments" }, { "code": null, "e": 27242, "s": 27229, "text": "Old Comments" }, { "code": null, "e": 27281, "s": 27242, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 27311, "s": 27281, "text": "Flutter - BorderRadius Widget" }, { "code": null, "e": 27337, "s": 27311, "text": "ListView Class in Flutter" }, { "code": null, "e": 27360, "s": 27337, "text": "Flutter - Stack Widget" }, { "code": null, "e": 27388, "s": 27360, "text": "What is widgets in Flutter?" }, { "code": null, "e": 27427, "s": 27388, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 27444, "s": 27427, "text": "Flutter Tutorial" }, { "code": null, "e": 27474, "s": 27444, "text": "Flutter - BorderRadius Widget" }, { "code": null, "e": 27497, "s": 27474, "text": "Flutter - Stack Widget" } ]
How to copy files to a new directory using Python?
The shutil module provides functions for copying files, as well as entire folders. For copying multiple files at once, you'll have to have a list of all files you want to copy and loop over them to copy them. Calling shutil.copy(source, destination) will copy the file at the path source to the folder at the path destination. (Both source and destination are strings.) If destination is a filename, it will be used as the new name of the copied file. This function returns a string of the path of the copied file. For example, import shutil, os files = ['file1.txt', 'file2.txt', 'file3.txt'] os.mkdir('my_new_folder') for f in files: shutil.copy(f, 'my_new_folder')
[ { "code": null, "e": 1271, "s": 1062, "text": "The shutil module provides functions for copying files, as well as entire folders. For copying multiple files at once, you'll have to have a list of all files you want to copy and loop over them to copy them." }, { "code": null, "e": 1590, "s": 1271, "text": "Calling shutil.copy(source, destination) will copy the file at the path source to the folder at the path destination. (Both source and destination are strings.) If destination is a filename, it will be used as the new name of the copied file. This function returns a string of the path of the copied file. For example," }, { "code": null, "e": 1734, "s": 1590, "text": "import shutil, os\nfiles = ['file1.txt', 'file2.txt', 'file3.txt']\nos.mkdir('my_new_folder')\nfor f in files:\n shutil.copy(f, 'my_new_folder')" } ]
How to identify elements based on text visible on page in Selenium?
To identify elements based on text visible on page, text() method is used in xpath. Syntax − driver.findElement(By.xpath("//tagname[text()=’value’]")) import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class TextMatch { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://www.tutorialspoint.com/index.htm"; driver.get(url); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //xpath with text() method driver.findElement(By.xpath("//*[text()=’GATE Exams’]")).click(); driver.close(); } }
[ { "code": null, "e": 1146, "s": 1062, "text": "To identify elements based on text visible on page, text() method is used in xpath." }, { "code": null, "e": 1155, "s": 1146, "text": "Syntax −" }, { "code": null, "e": 1213, "s": 1155, "text": "driver.findElement(By.xpath(\"//tagname[text()=’value’]\"))" }, { "code": null, "e": 1996, "s": 1213, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.Keys;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class TextMatch {\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.tutorialspoint.com/index.htm\";\n driver.get(url);\n driver.manage().window().maximize();\n driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);\n //xpath with text() method\n driver.findElement(By.xpath(\"//*[text()=’GATE Exams’]\")).click();\n driver.close();\n }\n}" } ]
How to convert a Date value to string in JDBC?
The toString() method of the java.sql.Date class returns the escape format: yyyy-mm-dd of the date represented by the current date object. Using this method you can convert a Date object to a String. Date date = rs.getDate("Dispatch_Date"); date.toString()); Assume we have a table named dispatch_data 3 records as shown below: +--------------+------------------+---------------+----------------+ | Product_Name | Name_Of_Customer | Dispatch_Date | Location | +--------------+------------------+---------------+----------------+ | KeyBoard | Amith | 1981-12-05 | Hyderabad | | Ear phones | Sumith | 1981-04-22 | Vishakhapatnam | | Mouse | Sudha | 1988-11-05 | Vijayawada | +--------------+------------------+---------------+----------------+ Following JDBC program establishes connection with the database retrieves the contents of the dispatch_data table, converts the date objects into String values using the toString() method and displays the contents of the table along with the Date values (which are converted into String format): import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class DateToString { public static void main(String args[])throws Exception { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating a Statement object Statement stmt = con.createStatement(); //Creating Statement object stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("select * from dispatch_data"); //Retrieving values while(rs.next()) { System.out.println("Product Name: "+rs.getString("Product_Name")); System.out.println("Name Of The Customer: "+rs.getString("Name_Of_Customer")); //Retrieving the date Date date = rs.getDate("Dispatch_Date"); //Converting Date object to String System.out.println("Date: "+date.toString()); System.out.println(); } } } Connection established...... Product Name: KeyBoard Name Of The Customer: Amith Date: 1981-12-05 Product Name: Ear phones Name Of The Customer: Sumith Date: 1981-04-22 Product Name: Mouse Name Of The Customer: Sudha Date: 1988-11-05
[ { "code": null, "e": 1262, "s": 1062, "text": "The toString() method of the java.sql.Date class returns the escape format: yyyy-mm-dd of the date represented by the current date object. Using this method you can convert a Date object to a String." }, { "code": null, "e": 1321, "s": 1262, "text": "Date date = rs.getDate(\"Dispatch_Date\");\ndate.toString());" }, { "code": null, "e": 1390, "s": 1321, "text": "Assume we have a table named dispatch_data 3 records as shown below:" }, { "code": null, "e": 1873, "s": 1390, "text": "+--------------+------------------+---------------+----------------+\n| Product_Name | Name_Of_Customer | Dispatch_Date | Location |\n+--------------+------------------+---------------+----------------+\n| KeyBoard | Amith | 1981-12-05 | Hyderabad |\n| Ear phones | Sumith | 1981-04-22 | Vishakhapatnam |\n| Mouse | Sudha | 1988-11-05 | Vijayawada |\n+--------------+------------------+---------------+----------------+" }, { "code": null, "e": 2169, "s": 1873, "text": "Following JDBC program establishes connection with the database retrieves the contents of the dispatch_data table, converts the date objects into String values using the toString() method and displays the contents of the table along with the Date values (which are converted into String format):" }, { "code": null, "e": 3384, "s": 2169, "text": "import java.sql.Connection;\nimport java.sql.Date;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\npublic class DateToString {\n public static void main(String args[])throws Exception {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating a Statement object\n Statement stmt = con.createStatement();\n //Creating Statement object\n stmt = con.createStatement();\n ResultSet rs = stmt.executeQuery(\"select * from dispatch_data\");\n //Retrieving values\n while(rs.next()) {\n System.out.println(\"Product Name: \"+rs.getString(\"Product_Name\"));\n System.out.println(\"Name Of The Customer: \"+rs.getString(\"Name_Of_Customer\"));\n //Retrieving the date\n Date date = rs.getDate(\"Dispatch_Date\");\n //Converting Date object to String\n System.out.println(\"Date: \"+date.toString());\n System.out.println();\n }\n }\n}" }, { "code": null, "e": 3619, "s": 3384, "text": "Connection established......\nProduct Name: KeyBoard\nName Of The Customer: Amith\nDate: 1981-12-05\n\nProduct Name: Ear phones\nName Of The Customer: Sumith\nDate: 1981-04-22\n\nProduct Name: Mouse\nName Of The Customer: Sudha\nDate: 1988-11-05" } ]
Maven - External Dependencies
As you know, Maven does the dependency management using the concept of Repositories. But what happens if dependency is not available in any of remote repositories and central repository? Maven provides answer for such scenario using concept of External Dependency. For example, let us do the following changes to the project created in ‘Creating Java Project’ chapter. Add lib folder to the src folder. Add lib folder to the src folder. Copy any jar into the lib folder. We've used ldapjdk.jar, which is a helper library for LDAP operations. Copy any jar into the lib folder. We've used ldapjdk.jar, which is a helper library for LDAP operations. Now our project structure should look like the following − Here you are having your own library, specific to the project, which is an usual case and it contains jars, which may not be available in any repository for maven to download from. If your code is using this library with Maven, then Maven build will fail as it cannot download or refer to this library during compilation phase. To handle the situation, let's add this external dependency to maven pom.xml using the following way. <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.companyname.bank</groupId> <artifactId>consumerBanking</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>consumerBanking</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>ldapjdk</groupId> <artifactId>ldapjdk</artifactId> <scope>system</scope> <version>1.0</version> <systemPath>${basedir}\src\lib\ldapjdk.jar</systemPath> </dependency> </dependencies> </project> Look at the second dependency element under dependencies in the above example, which clears the following key concepts about External Dependency. External dependencies (library jar location) can be configured in pom.xml in same way as other dependencies. External dependencies (library jar location) can be configured in pom.xml in same way as other dependencies. Specify groupId same as the name of the library. Specify groupId same as the name of the library. Specify artifactId same as the name of the library. Specify artifactId same as the name of the library. Specify scope as system. Specify scope as system. Specify system path relative to the project location. Specify system path relative to the project location. Hope now you are clear about external dependencies and you will be able to specify external dependencies in your Maven project. 34 Lectures 4 hours Karthikeya T 14 Lectures 1.5 hours Quaatso Learning Print Add Notes Bookmark this page
[ { "code": null, "e": 2325, "s": 2060, "text": "As you know, Maven does the dependency management using the concept of Repositories. But what happens if dependency is not available in any of remote repositories and central repository? Maven provides answer for such scenario using concept of External Dependency." }, { "code": null, "e": 2429, "s": 2325, "text": "For example, let us do the following changes to the project created in ‘Creating Java Project’ chapter." }, { "code": null, "e": 2463, "s": 2429, "text": "Add lib folder to the src folder." }, { "code": null, "e": 2497, "s": 2463, "text": "Add lib folder to the src folder." }, { "code": null, "e": 2602, "s": 2497, "text": "Copy any jar into the lib folder. We've used ldapjdk.jar, which is a helper library for LDAP operations." }, { "code": null, "e": 2707, "s": 2602, "text": "Copy any jar into the lib folder. We've used ldapjdk.jar, which is a helper library for LDAP operations." }, { "code": null, "e": 2766, "s": 2707, "text": "Now our project structure should look like the following −" }, { "code": null, "e": 3094, "s": 2766, "text": "Here you are having your own library, specific to the project, which is an usual case and it contains jars, which may not be available in any repository for maven to download from. If your code is using this library with Maven, then Maven build will fail as it cannot download or refer to this library during compilation phase." }, { "code": null, "e": 3196, "s": 3094, "text": "To handle the situation, let's add this external dependency to maven pom.xml using the following way." }, { "code": null, "e": 4145, "s": 3196, "text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/maven-v4_0_0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.companyname.bank</groupId>\n <artifactId>consumerBanking</artifactId>\n <packaging>jar</packaging>\n <version>1.0-SNAPSHOT</version>\n <name>consumerBanking</name>\n <url>http://maven.apache.org</url>\n\n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n <scope>test</scope>\n </dependency>\n\n <dependency>\n <groupId>ldapjdk</groupId>\n <artifactId>ldapjdk</artifactId>\n <scope>system</scope>\n <version>1.0</version>\n <systemPath>${basedir}\\src\\lib\\ldapjdk.jar</systemPath>\n </dependency>\n </dependencies>\n\n</project>" }, { "code": null, "e": 4291, "s": 4145, "text": "Look at the second dependency element under dependencies in the above example, which clears the following key concepts about External Dependency." }, { "code": null, "e": 4400, "s": 4291, "text": "External dependencies (library jar location) can be configured in pom.xml in same way as other dependencies." }, { "code": null, "e": 4509, "s": 4400, "text": "External dependencies (library jar location) can be configured in pom.xml in same way as other dependencies." }, { "code": null, "e": 4558, "s": 4509, "text": "Specify groupId same as the name of the library." }, { "code": null, "e": 4607, "s": 4558, "text": "Specify groupId same as the name of the library." }, { "code": null, "e": 4659, "s": 4607, "text": "Specify artifactId same as the name of the library." }, { "code": null, "e": 4711, "s": 4659, "text": "Specify artifactId same as the name of the library." }, { "code": null, "e": 4736, "s": 4711, "text": "Specify scope as system." }, { "code": null, "e": 4761, "s": 4736, "text": "Specify scope as system." }, { "code": null, "e": 4815, "s": 4761, "text": "Specify system path relative to the project location." }, { "code": null, "e": 4869, "s": 4815, "text": "Specify system path relative to the project location." }, { "code": null, "e": 4997, "s": 4869, "text": "Hope now you are clear about external dependencies and you will be able to specify external dependencies in your Maven project." }, { "code": null, "e": 5030, "s": 4997, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 5044, "s": 5030, "text": " Karthikeya T" }, { "code": null, "e": 5079, "s": 5044, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5097, "s": 5079, "text": " Quaatso Learning" }, { "code": null, "e": 5104, "s": 5097, "text": " Print" }, { "code": null, "e": 5115, "s": 5104, "text": " Add Notes" } ]
SQL INNER JOIN Keyword
The INNER JOIN keyword selects records that have matching values in both tables. In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Orders" table: And a selection from the "Customers" table: The following SQL statement selects all orders with customer information: Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match between the columns. If there are records in the "Orders" table that do not have matches in "Customers", these orders will not be shown! The following SQL statement selects all orders with customer and shipper information: Choose the correct JOIN clause to select all records from the two tables where there is a match in both tables. SELECT * FROM Orders ON Orders.CustomerID=Customers.CustomerID; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 82, "s": 0, "text": "The INNER JOIN keyword selects records that have matching values in \nboth tables." }, { "code": null, "e": 153, "s": 82, "text": "In this tutorial we will use the well-known Northwind sample database." }, { "code": null, "e": 199, "s": 153, "text": "Below is a selection from the \"Orders\" table:" }, { "code": null, "e": 243, "s": 199, "text": "And a selection from the \"Customers\" table:" }, { "code": null, "e": 317, "s": 243, "text": "The following SQL statement selects all orders with customer information:" }, { "code": null, "e": 548, "s": 317, "text": "Note: The INNER JOIN keyword selects all rows from both \ntables as long as there is a match between the columns. If there are records in the \n\"Orders\" table that do not have matches in \"Customers\", these orders will not \nbe shown!" }, { "code": null, "e": 635, "s": 548, "text": "The following SQL statement selects all orders with customer and shipper \ninformation:" }, { "code": null, "e": 747, "s": 635, "text": "Choose the correct JOIN clause to select all records from the two tables where there is a match in both tables." }, { "code": null, "e": 813, "s": 747, "text": "SELECT *\nFROM Orders\n\nON Orders.CustomerID=Customers.CustomerID;\n" }, { "code": null, "e": 832, "s": 813, "text": "Start the Exercise" }, { "code": null, "e": 865, "s": 832, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 907, "s": 865, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1014, "s": 907, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1033, "s": 1014, "text": "help@w3schools.com" } ]
Implement Text search in MongoDB
For text search, you need to use textalongwithsearch. Let us create a collection with documents − > db.demo156.createIndex({"StudentName":"text"}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo156.insertOne({"StudentName":"Chris Brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3547e8fdf09dd6d08539e6") } > db.demo156.insertOne({"StudentName":"John Doe"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3547f2fdf09dd6d08539e7") } > db.demo156.insertOne({"StudentName":"John Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3547f7fdf09dd6d08539e8") } Display all documents from a collection with the help of find() method − > db.demo156.find(); This will produce the following output − { "_id" : ObjectId("5e3547e8fdf09dd6d08539e6"), "StudentName" : "Chris Brown" } { "_id" : ObjectId("5e3547f2fdf09dd6d08539e7"), "StudentName" : "John Doe" } { "_id" : ObjectId("5e3547f7fdf09dd6d08539e8"), "StudentName" : "John Smith" } Following is the query to implement text search in MongoDB − > db.demo156.find({ $text: { $search: "John" } } ) This will produce the following output − { "_id" : ObjectId("5e3547f7fdf09dd6d08539e8"), "StudentName" : "John Smith" } { "_id" : ObjectId("5e3547f2fdf09dd6d08539e7"), "StudentName" : "John Doe" }
[ { "code": null, "e": 1160, "s": 1062, "text": "For text search, you need to use textalongwithsearch. Let us create a collection with documents −" }, { "code": null, "e": 1739, "s": 1160, "text": "> db.demo156.createIndex({\"StudentName\":\"text\"});\n{\n \"createdCollectionAutomatically\" : true,\n \"numIndexesBefore\" : 1,\n \"numIndexesAfter\" : 2,\n \"ok\" : 1\n}\n> db.demo156.insertOne({\"StudentName\":\"Chris Brown\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3547e8fdf09dd6d08539e6\")\n}\n> db.demo156.insertOne({\"StudentName\":\"John Doe\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3547f2fdf09dd6d08539e7\")\n}\n> db.demo156.insertOne({\"StudentName\":\"John Smith\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3547f7fdf09dd6d08539e8\")\n}" }, { "code": null, "e": 1812, "s": 1739, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1833, "s": 1812, "text": "> db.demo156.find();" }, { "code": null, "e": 1874, "s": 1833, "text": "This will produce the following output −" }, { "code": null, "e": 2110, "s": 1874, "text": "{ \"_id\" : ObjectId(\"5e3547e8fdf09dd6d08539e6\"), \"StudentName\" : \"Chris Brown\" }\n{ \"_id\" : ObjectId(\"5e3547f2fdf09dd6d08539e7\"), \"StudentName\" : \"John Doe\" }\n{ \"_id\" : ObjectId(\"5e3547f7fdf09dd6d08539e8\"), \"StudentName\" : \"John Smith\" }" }, { "code": null, "e": 2171, "s": 2110, "text": "Following is the query to implement text search in MongoDB −" }, { "code": null, "e": 2222, "s": 2171, "text": "> db.demo156.find({ $text: { $search: \"John\" } } )" }, { "code": null, "e": 2263, "s": 2222, "text": "This will produce the following output −" }, { "code": null, "e": 2419, "s": 2263, "text": "{ \"_id\" : ObjectId(\"5e3547f7fdf09dd6d08539e8\"), \"StudentName\" : \"John Smith\" }\n{ \"_id\" : ObjectId(\"5e3547f2fdf09dd6d08539e7\"), \"StudentName\" : \"John Doe\" }" } ]
LocalDateTime parse() method in Java
The LocalDateTime instance can be obtained from a string value using the parse() method in the LocalDateTime class in Java. This method requires a single parameter i.e. the string which is to be parsed. This string cannot be null. Also, it returns the LocalDateTime instance obtained from the string value that was passed as a parameter. A program that demonstrates this is given as follows − Live Demo import java.time.*; public class Demo { public static void main(String[] args) { LocalDateTime ldt = LocalDateTime.parse("2019-02-18T23:15:30"); System.out.println("The LocalDateTime is: " + ldt); } } The LocalDateTime is: 2019-02-18T23:15:30 Now let us understand the above program. The LocalDateTime instance is obtained from the string value using the parse() method. Then this instance is displayed. A code snippet that demonstrates this is as follows − LocalDateTime ldt = LocalDateTime.parse("2019-02-18T23:15:30"); System.out.println("The LocalDateTime is: " + ldt);
[ { "code": null, "e": 1400, "s": 1062, "text": "The LocalDateTime instance can be obtained from a string value using the parse() method in the LocalDateTime class in Java. This method requires a single parameter i.e. the string which is to be parsed. This string cannot be null. Also, it returns the LocalDateTime instance obtained from the string value that was passed as a parameter." }, { "code": null, "e": 1455, "s": 1400, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1466, "s": 1455, "text": " Live Demo" }, { "code": null, "e": 1685, "s": 1466, "text": "import java.time.*;\npublic class Demo {\n public static void main(String[] args) {\n LocalDateTime ldt = LocalDateTime.parse(\"2019-02-18T23:15:30\");\n System.out.println(\"The LocalDateTime is: \" + ldt);\n }\n}" }, { "code": null, "e": 1727, "s": 1685, "text": "The LocalDateTime is: 2019-02-18T23:15:30" }, { "code": null, "e": 1768, "s": 1727, "text": "Now let us understand the above program." }, { "code": null, "e": 1942, "s": 1768, "text": "The LocalDateTime instance is obtained from the string value using the parse() method. Then this instance is displayed. A code snippet that demonstrates this is as follows −" }, { "code": null, "e": 2058, "s": 1942, "text": "LocalDateTime ldt = LocalDateTime.parse(\"2019-02-18T23:15:30\");\nSystem.out.println(\"The LocalDateTime is: \" + ldt);" } ]
Find square root of number upto given precision using binary search in C++
Suppose we have a positive number n, and precision p. We have to find square root of the number n up to p decimal places using binary search technique. So if the number is n = 50, and p = 3, then output is 7.071. So solve this, we have to follow some steps − Initialize start := 0 and end := n Compare the square of mid integer, if this is equal to the number then integral part has found out, otherwise look for left or right as required. Once we have completed the task for integral part, then do for the fractional part. Initialize increment variable as 0.1, then compute fractional part up to p places. For each iteration increment changes to 1/10 th of its previous value. Finally return the answer. Live Demo #include<iostream> using namespace std; float sqrtBinarySearch(int num, int p) { int left = 0, right = num; int mid; float res; while (left <= right) { mid = (left + right) / 2; if (mid * mid == num) { res = mid; break; } if (mid * mid < num) { left = mid + 1; res = mid; } else { right = mid - 1; } } float incr = 0.1; for (int i = 0; i < p; i++) { while (res * res <= num) { res += incr; } res -= incr; incr /= 10; } return res; } int main() { int n = 50, p = 3; cout << "Square root of " << n << " up to precision " << p << " is: " << sqrtBinarySearch(50, 3) << endl; } Square root of 50 up to precision 3 is: 7.071
[ { "code": null, "e": 1275, "s": 1062, "text": "Suppose we have a positive number n, and precision p. We have to find square root of the number n up to p decimal places using binary search technique. So if the number is n = 50, and p = 3, then output is 7.071." }, { "code": null, "e": 1321, "s": 1275, "text": "So solve this, we have to follow some steps −" }, { "code": null, "e": 1356, "s": 1321, "text": "Initialize start := 0 and end := n" }, { "code": null, "e": 1502, "s": 1356, "text": "Compare the square of mid integer, if this is equal to the number then integral part has found out, otherwise look for left or right as required." }, { "code": null, "e": 1586, "s": 1502, "text": "Once we have completed the task for integral part, then do for the fractional part." }, { "code": null, "e": 1740, "s": 1586, "text": "Initialize increment variable as 0.1, then compute fractional part up to p places. For each iteration increment changes to 1/10 th of its previous value." }, { "code": null, "e": 1767, "s": 1740, "text": "Finally return the answer." }, { "code": null, "e": 1778, "s": 1767, "text": " Live Demo" }, { "code": null, "e": 2498, "s": 1778, "text": "#include<iostream>\nusing namespace std;\nfloat sqrtBinarySearch(int num, int p) {\n int left = 0, right = num;\n int mid;\n float res;\n while (left <= right) {\n mid = (left + right) / 2;\n if (mid * mid == num) {\n res = mid;\n break;\n }\n if (mid * mid < num) {\n left = mid + 1;\n res = mid;\n } else {\n right = mid - 1;\n }\n }\n float incr = 0.1;\n for (int i = 0; i < p; i++) {\n while (res * res <= num) {\n res += incr;\n }\n res -= incr;\n incr /= 10;\n }\n return res;\n}\nint main() {\n int n = 50, p = 3;\n cout << \"Square root of \" << n << \" up to precision \" << p << \" is: \" << sqrtBinarySearch(50, 3) << endl;\n}" }, { "code": null, "e": 2544, "s": 2498, "text": "Square root of 50 up to precision 3 is: 7.071" } ]
JavaFX - Scatter Chart
A scatterplot is a type of graph which uses values from two variables plotted in a Cartesian plane. It is usually used to find out the relationship between two variables. Following is a Scatter chart plotted between area and weight. In JavaFX, a Scatter chart is represented by a class named ScatterChart. This class belongs to the package javafx.scene.chart. By instantiating this class, you can create a ScatterChart node in JavaFX. To generate an area chart in JavaFX, follow the steps given below. Create a Java class and inherit the Application class of the package javafx.application. You can then implement the start() method of this class as follows. public class ClassName extends Application { @Override public void start(Stage primaryStage) throws Exception { } } Define the X and Y axis of the area chart and set labels to them. In our example, X axis represents area and the Y axis represents weights. //Defining the x axis NumberAxis xAxis = new NumberAxis(0, 12, 3); xAxis.setLabel("Area"); //Defining the y axis NumberAxis yAxis = new NumberAxis(0, 16, 4); yAxis.setLabel("Weight"); Create a line chart by instantiating the class named ScatterChart of the package javafx.scene.chart. To the constructor of this class, pass the objects representing the X and Y axis created in the previous step. //Creating the Scatter chart ScatterChart<String, Number> scatterChart = new ScatterChart(xAxis, yAxis); Instantiate the XYChart.Series class and add the data (a series of, x and y coordinates) to the Observable list of this class as follows − //Prepare XYChart.Series objects by setting data XYChart.Series series = new XYChart.Series(); series.getData().add(new XYChart.Data(8, 12)); series.getData().add(new XYChart.Data(4, 5.5)); series.getData().add(new XYChart.Data(11, 14)); series.getData().add(new XYChart.Data(4, 5)); series.getData().add(new XYChart.Data(3, 3.5)); series.getData().add(new XYChart.Data(6.5, 7)); Add the data series prepared in the previous step to the scatter chart as follows − //Setting the data to scatter chart scatterChart.getData().addAll(series); In the start() method, create a group object by instantiating the class named Group. This belongs to the package javafx.scene. Pass the ScatterChart (node) object created in the previous step as a parameter to the constructor of the Group class. This should be done in order to add it to the group as follows − Group root = new Group(scatterChart); Create a Scene by instantiating the class named Scene, which belongs to the package javafx.scene. To this class, pass the Group object (root) created in the previous step. In addition to the Root Object, you can also pass two double parameters representing height and width of the screen, along with the object of the Group class as follows. Scene scene = new Scene(group ,600, 300); You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object, which is passed to the start method of the scene class as a parameter. Using the primaryStage object, set the title of the scene as Sample Application as follows. primaryStage.setTitle("Sample Application"); You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as follows. primaryStage.setScene(scene); Display the contents of the scene using the method named show() of the Stage class as follows. primaryStage.show(); Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows. public static void main(String args[]){ launch(args); } The following table contains sample data plotted between area and weight. Following is a Java program which generates a scatter chart depicting the above data using JavaFX. Save this code in a file with the name ScatterChartExample.java. import javafx.application.Application; import static javafx.application.Application.launch; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.ScatterChart; import javafx.scene.chart.XYChart; public class ScatterChartExample extends Application { @Override public void start(Stage stage) { //Defining the axes NumberAxis xAxis = new NumberAxis(0, 12, 3); xAxis.setLabel("Area"); NumberAxis yAxis = new NumberAxis(0, 16, 4); yAxis.setLabel("Weight"); //Creating the Scatter chart ScatterChart<String, Number> scatterChart = new ScatterChart(xAxis, yAxis); //Prepare XYChart.Series objects by setting data XYChart.Series series = new XYChart.Series(); series.getData().add(new XYChart.Data(8, 12)); series.getData().add(new XYChart.Data(4, 5.5)); series.getData().add(new XYChart.Data(11, 14)); series.getData().add(new XYChart.Data(4, 5)); series.getData().add(new XYChart.Data(3, 3.5)); series.getData().add(new XYChart.Data(6.5, 7)); //Setting the data to scatter chart scatterChart.getData().addAll(series); //Creating a Group object Group root = new Group(scatterChart); //Creating a scene object Scene scene = new Scene(root, 600, 400); //Setting title to the Stage stage.setTitle("Scatter Chart"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac ScatterChartExample.java java ScatterChartExample On executing, the above program generates a JavaFX window displaying a scatter chart as shown below. 33 Lectures 7.5 hours Syed Raza 64 Lectures 12.5 hours Emenwa Global, Ejike IfeanyiChukwu 20 Lectures 4 hours Emenwa Global, Ejike IfeanyiChukwu Print Add Notes Bookmark this page
[ { "code": null, "e": 2071, "s": 1900, "text": "A scatterplot is a type of graph which uses values from two variables plotted in a Cartesian plane. It is usually used to find out the relationship between two variables." }, { "code": null, "e": 2133, "s": 2071, "text": "Following is a Scatter chart plotted between area and weight." }, { "code": null, "e": 2335, "s": 2133, "text": "In JavaFX, a Scatter chart is represented by a class named ScatterChart. This class belongs to the package javafx.scene.chart. By instantiating this class, you can create a ScatterChart node in JavaFX." }, { "code": null, "e": 2402, "s": 2335, "text": "To generate an area chart in JavaFX, follow the steps given below." }, { "code": null, "e": 2559, "s": 2402, "text": "Create a Java class and inherit the Application class of the package javafx.application. You can then implement the start() method of this class as follows." }, { "code": null, "e": 2701, "s": 2559, "text": "public class ClassName extends Application { \n @Override \n public void start(Stage primaryStage) throws Exception { \n } \n}" }, { "code": null, "e": 2841, "s": 2701, "text": "Define the X and Y axis of the area chart and set labels to them. In our example, X axis represents area and the Y axis represents weights." }, { "code": null, "e": 3063, "s": 2841, "text": "//Defining the x axis \nNumberAxis xAxis = new NumberAxis(0, 12, 3); \nxAxis.setLabel(\"Area\"); \n \n//Defining the y axis \nNumberAxis yAxis = new NumberAxis(0, 16, 4); \nyAxis.setLabel(\"Weight\");\n" }, { "code": null, "e": 3275, "s": 3063, "text": "Create a line chart by instantiating the class named ScatterChart of the package javafx.scene.chart. To the constructor of this class, pass the objects representing the X and Y axis created in the previous step." }, { "code": null, "e": 3383, "s": 3275, "text": "//Creating the Scatter chart \nScatterChart<String, Number> scatterChart = new ScatterChart(xAxis, yAxis); \n" }, { "code": null, "e": 3522, "s": 3383, "text": "Instantiate the XYChart.Series class and add the data (a series of, x and y coordinates) to the Observable list of this class as follows −" }, { "code": null, "e": 3911, "s": 3522, "text": "//Prepare XYChart.Series objects by setting data \nXYChart.Series series = new XYChart.Series(); \nseries.getData().add(new XYChart.Data(8, 12)); \nseries.getData().add(new XYChart.Data(4, 5.5)); \nseries.getData().add(new XYChart.Data(11, 14)); \nseries.getData().add(new XYChart.Data(4, 5)); \nseries.getData().add(new XYChart.Data(3, 3.5)); \nseries.getData().add(new XYChart.Data(6.5, 7)); " }, { "code": null, "e": 3995, "s": 3911, "text": "Add the data series prepared in the previous step to the scatter chart as follows −" }, { "code": null, "e": 4079, "s": 3995, "text": "//Setting the data to scatter chart \nscatterChart.getData().addAll(series);\n" }, { "code": null, "e": 4206, "s": 4079, "text": "In the start() method, create a group object by instantiating the class named Group. This belongs to the package javafx.scene." }, { "code": null, "e": 4390, "s": 4206, "text": "Pass the ScatterChart (node) object created in the previous step as a parameter to the constructor of the Group class. This should be done in order to add it to the group as follows −" }, { "code": null, "e": 4429, "s": 4390, "text": "Group root = new Group(scatterChart);\n" }, { "code": null, "e": 4601, "s": 4429, "text": "Create a Scene by instantiating the class named Scene, which belongs to the package javafx.scene. To this class, pass the Group object (root) created in the previous step." }, { "code": null, "e": 4771, "s": 4601, "text": "In addition to the Root Object, you can also pass two double parameters representing height and width of the screen, along with the object of the Group class as follows." }, { "code": null, "e": 4814, "s": 4771, "text": "Scene scene = new Scene(group ,600, 300);\n" }, { "code": null, "e": 5004, "s": 4814, "text": "You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object, which is passed to the start method of the scene class as a parameter." }, { "code": null, "e": 5096, "s": 5004, "text": "Using the primaryStage object, set the title of the scene as Sample Application as follows." }, { "code": null, "e": 5142, "s": 5096, "text": "primaryStage.setTitle(\"Sample Application\");\n" }, { "code": null, "e": 5318, "s": 5142, "text": "You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as follows." }, { "code": null, "e": 5350, "s": 5318, "text": "primaryStage.setScene(scene); \n" }, { "code": null, "e": 5445, "s": 5350, "text": "Display the contents of the scene using the method named show() of the Stage class as follows." }, { "code": null, "e": 5468, "s": 5445, "text": "primaryStage.show(); \n" }, { "code": null, "e": 5594, "s": 5468, "text": "Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows." }, { "code": null, "e": 5662, "s": 5594, "text": "public static void main(String args[]){ \n launch(args); \n}" }, { "code": null, "e": 5736, "s": 5662, "text": "The following table contains sample data plotted between area and weight." }, { "code": null, "e": 5835, "s": 5736, "text": "Following is a Java program which generates a scatter chart depicting the above data using JavaFX." }, { "code": null, "e": 5900, "s": 5835, "text": "Save this code in a file with the name ScatterChartExample.java." }, { "code": null, "e": 7739, "s": 5900, "text": "import javafx.application.Application; \nimport static javafx.application.Application.launch; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.stage.Stage; \nimport javafx.scene.chart.NumberAxis; \nimport javafx.scene.chart.ScatterChart; \nimport javafx.scene.chart.XYChart; \n \npublic class ScatterChartExample extends Application { \n @Override \n public void start(Stage stage) { \n //Defining the axes \n NumberAxis xAxis = new NumberAxis(0, 12, 3); \n xAxis.setLabel(\"Area\"); \n \n NumberAxis yAxis = new NumberAxis(0, 16, 4); \n yAxis.setLabel(\"Weight\"); \n \n //Creating the Scatter chart \n ScatterChart<String, Number> scatterChart = \n new ScatterChart(xAxis, yAxis); \n \n //Prepare XYChart.Series objects by setting data \n XYChart.Series series = new XYChart.Series(); \n series.getData().add(new XYChart.Data(8, 12)); \n series.getData().add(new XYChart.Data(4, 5.5)); \n series.getData().add(new XYChart.Data(11, 14)); \n series.getData().add(new XYChart.Data(4, 5)); \n series.getData().add(new XYChart.Data(3, 3.5)); \n series.getData().add(new XYChart.Data(6.5, 7)); \n \n //Setting the data to scatter chart \n scatterChart.getData().addAll(series); \n \n //Creating a Group object \n Group root = new Group(scatterChart); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 400); \n \n //Setting title to the Stage \n stage.setTitle(\"Scatter Chart\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n}" }, { "code": null, "e": 7833, "s": 7739, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 7891, "s": 7833, "text": "javac ScatterChartExample.java \njava ScatterChartExample\n" }, { "code": null, "e": 7992, "s": 7891, "text": "On executing, the above program generates a JavaFX window displaying a scatter chart as shown below." }, { "code": null, "e": 8027, "s": 7992, "text": "\n 33 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8038, "s": 8027, "text": " Syed Raza" }, { "code": null, "e": 8074, "s": 8038, "text": "\n 64 Lectures \n 12.5 hours \n" }, { "code": null, "e": 8110, "s": 8074, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8143, "s": 8110, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 8179, "s": 8143, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8186, "s": 8179, "text": " Print" }, { "code": null, "e": 8197, "s": 8186, "text": " Add Notes" } ]
Reverse Geocoding in Python. How to Convert Raw Latitude/Longitude... | by Abdishakur | Towards Data Science
Many datasets have only coordinates — latitude and longitude — and do not have any association with identifiable features like addresses, street names, building names or postcodes that we humans recognise. Reverse Geocoding is an essential component in many location data science applications. The process of converting the raw coordinates to insightful location data features is called Reverse Geocoding. Reverse geocoding is the process of back (reverse) coding of a point location (latitude, longitude) to a readable address or place name. — Wikipedia In this tutorial, we will cover how to perform reverse geocoding using Python. We use Pandas and Geopy libraries to deliver reverse geocoding. In the next section, we cover the basics and convert a single point coordinates to an address with postcode and building name. Let us import our libraries first. %load_ext autotimeimport pandas as pdimport geopandas as gpdimport geopyfrom geopy.geocoders import Nominatimfrom geopy.extra.rate_limiter import RateLimiterimport matplotlib.pyplot as pltimport plotly_express as pximport tqdmfrom tqdm._tqdm_notebook import tqdm_notebook We now can construct our Geocoder. We first need to specify the Geocoding service. You can access different services including 'google', 'bing', 'yahoo'and 'openmapquest' . Some of these services charge small free after a specific limit, but in our example, we will use the free Geocoding service of Openstreetmap. locator = Nominatim(user_agent=”myGeocoder”)coordinates = “53.480837, -2.244914”location = locator.reverse(coordinates)location.raw Once you provide the coordinates with the Geocoding service of our choice, the result is a dictionary of different features you can access. If you print out the raw element of the location you will see several exciting features derived from the coordinates. {‘address’: {‘building’: ‘Eagle Insurance Buildings’, ‘city’: ‘Manchester’, ‘country’: ‘United Kingdom’, ‘country_code’: ‘gb’, ‘county’: ‘Greater Manchester’, ‘house_number’: ‘68’, ‘postcode’: ‘M2 4JG’, ‘road’: ‘Cross Street’, ‘state’: ‘England’, ‘state_district’: ‘North West England’, ‘suburb’: ‘City Centre’}, ‘boundingbox’: [‘53.480856’, ‘53.4810634’, ‘-2.2451761’, ‘-2.2449576’], ‘display_name’: ‘Eagle Insurance Buildings, 68, Cross Street, City Centre, Manchester, Greater Manchester, North West England, England, M2 4JG, United Kingdom’,‘lat’: ‘53.4809597’, ‘licence’: ‘Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright', ‘lon’: ‘-2.24506682746292’, ‘osm_id’: 37139875, ‘osm_type’: ‘way’, ‘place_id’: 86197794} Here you have a building, postcode, address, country, road name and a bunch of other insightful attributes that were not available with the raw coordinates. If you are only interested in printing out the address only, you can use dictionary keys, or you can directly do like this. print(location.address) And it will print out the address part of the output. In the next section, we will see how we can use reverse Geocoding in Pandas DataFrame. It is often a subset or complete dataset we want to get addresses from latitude and longitude — Reverse Geocoding — rather than individual coordinates. In this section, we explore how we can do that with Pandas and Geopy. First, we read the data from URL in Pandas. The data is stored in Dropbox and we can easily use with Pandas if we have a link. You just need to make sure that the last characters of the URL are set to “dl=1”. url = “https://www.dropbox.com/s/15gisj8hx218rn1/street-pole-sample.csv?dl=1"df = pd.read_csv(url)df.head() The data has X and Y columns where the coordinates are stored with other features, as shown below in this table. We can also explore the data and show this in a map using Plotly Express. With just one line of code, you can show a map with a base map. import plotly_express as pxpx.scatter_mapbox(df, lat=”Y”, lon=”X”, zoom=15) The map shows a subset of Phillidelphia street poles. Now, we need to construct the coordinates column from X and Y columns. We can achieve this by merely mapping these two columns (X & Y) as strings and then concatenate with a comma between them. df[“geom”] = df[“Y”].map(str) + ‘,’ + df[‘X’].map(str)df[“geom”][0] Here is how the first row of the geomcolumn we created above. '39.9427660880249,-75.17009743393821' We create a service provider locator this time pass timeout to be 10 minutes since we have many rows. That will prevent timeout errors that you might encounter during the process. locator = Nominatim(user_agent=”myGeocoder”, timeout=10)rgeocode = RateLimiter(locator.reverse, min_delay_seconds=0.001) Now, we can reverse geocode by using applying the reverse geocoding rgeocode we created above. To get a nice progress bar, we are using here tqdm library. tqdm.pandas()df[‘address’] = df[‘geom’].progress_apply(rgeocode)df.head() It might take a while depending on the number of rows in the dataset. But once the process finishes, you will have an additional feature in the dataset where each point has an address as shown below. The data has now much more insightful attributes associated with each point, including address, postcode, buildings, etc.... It took 1 minute and 45 seconds to perform reverse geocoding with only 150 points. The computation time is probably not a good option as an increase in data points will require a lot of processing time. If you have a large dataset, you might try to decrease the delay seconds. In this article, we have explored how you can reverse geocode coordinates to addresses. You can access the notebook for this tutorial in this Google Colab Notebook.
[ { "code": null, "e": 578, "s": 172, "text": "Many datasets have only coordinates — latitude and longitude — and do not have any association with identifiable features like addresses, street names, building names or postcodes that we humans recognise. Reverse Geocoding is an essential component in many location data science applications. The process of converting the raw coordinates to insightful location data features is called Reverse Geocoding." }, { "code": null, "e": 727, "s": 578, "text": "Reverse geocoding is the process of back (reverse) coding of a point location (latitude, longitude) to a readable address or place name. — Wikipedia" }, { "code": null, "e": 997, "s": 727, "text": "In this tutorial, we will cover how to perform reverse geocoding using Python. We use Pandas and Geopy libraries to deliver reverse geocoding. In the next section, we cover the basics and convert a single point coordinates to an address with postcode and building name." }, { "code": null, "e": 1032, "s": 997, "text": "Let us import our libraries first." }, { "code": null, "e": 1304, "s": 1032, "text": "%load_ext autotimeimport pandas as pdimport geopandas as gpdimport geopyfrom geopy.geocoders import Nominatimfrom geopy.extra.rate_limiter import RateLimiterimport matplotlib.pyplot as pltimport plotly_express as pximport tqdmfrom tqdm._tqdm_notebook import tqdm_notebook" }, { "code": null, "e": 1619, "s": 1304, "text": "We now can construct our Geocoder. We first need to specify the Geocoding service. You can access different services including 'google', 'bing', 'yahoo'and 'openmapquest' . Some of these services charge small free after a specific limit, but in our example, we will use the free Geocoding service of Openstreetmap." }, { "code": null, "e": 1751, "s": 1619, "text": "locator = Nominatim(user_agent=”myGeocoder”)coordinates = “53.480837, -2.244914”location = locator.reverse(coordinates)location.raw" }, { "code": null, "e": 2009, "s": 1751, "text": "Once you provide the coordinates with the Geocoding service of our choice, the result is a dictionary of different features you can access. If you print out the raw element of the location you will see several exciting features derived from the coordinates." }, { "code": null, "e": 2749, "s": 2009, "text": "{‘address’: {‘building’: ‘Eagle Insurance Buildings’, ‘city’: ‘Manchester’, ‘country’: ‘United Kingdom’, ‘country_code’: ‘gb’, ‘county’: ‘Greater Manchester’, ‘house_number’: ‘68’, ‘postcode’: ‘M2 4JG’, ‘road’: ‘Cross Street’, ‘state’: ‘England’, ‘state_district’: ‘North West England’, ‘suburb’: ‘City Centre’}, ‘boundingbox’: [‘53.480856’, ‘53.4810634’, ‘-2.2451761’, ‘-2.2449576’], ‘display_name’: ‘Eagle Insurance Buildings, 68, Cross Street, City Centre, Manchester, Greater Manchester, North West England, England, M2 4JG, United Kingdom’,‘lat’: ‘53.4809597’, ‘licence’: ‘Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright', ‘lon’: ‘-2.24506682746292’, ‘osm_id’: 37139875, ‘osm_type’: ‘way’, ‘place_id’: 86197794}" }, { "code": null, "e": 3030, "s": 2749, "text": "Here you have a building, postcode, address, country, road name and a bunch of other insightful attributes that were not available with the raw coordinates. If you are only interested in printing out the address only, you can use dictionary keys, or you can directly do like this." }, { "code": null, "e": 3054, "s": 3030, "text": "print(location.address)" }, { "code": null, "e": 3195, "s": 3054, "text": "And it will print out the address part of the output. In the next section, we will see how we can use reverse Geocoding in Pandas DataFrame." }, { "code": null, "e": 3417, "s": 3195, "text": "It is often a subset or complete dataset we want to get addresses from latitude and longitude — Reverse Geocoding — rather than individual coordinates. In this section, we explore how we can do that with Pandas and Geopy." }, { "code": null, "e": 3626, "s": 3417, "text": "First, we read the data from URL in Pandas. The data is stored in Dropbox and we can easily use with Pandas if we have a link. You just need to make sure that the last characters of the URL are set to “dl=1”." }, { "code": null, "e": 3734, "s": 3626, "text": "url = “https://www.dropbox.com/s/15gisj8hx218rn1/street-pole-sample.csv?dl=1\"df = pd.read_csv(url)df.head()" }, { "code": null, "e": 3847, "s": 3734, "text": "The data has X and Y columns where the coordinates are stored with other features, as shown below in this table." }, { "code": null, "e": 3985, "s": 3847, "text": "We can also explore the data and show this in a map using Plotly Express. With just one line of code, you can show a map with a base map." }, { "code": null, "e": 4061, "s": 3985, "text": "import plotly_express as pxpx.scatter_mapbox(df, lat=”Y”, lon=”X”, zoom=15)" }, { "code": null, "e": 4309, "s": 4061, "text": "The map shows a subset of Phillidelphia street poles. Now, we need to construct the coordinates column from X and Y columns. We can achieve this by merely mapping these two columns (X & Y) as strings and then concatenate with a comma between them." }, { "code": null, "e": 4377, "s": 4309, "text": "df[“geom”] = df[“Y”].map(str) + ‘,’ + df[‘X’].map(str)df[“geom”][0]" }, { "code": null, "e": 4439, "s": 4377, "text": "Here is how the first row of the geomcolumn we created above." }, { "code": null, "e": 4477, "s": 4439, "text": "'39.9427660880249,-75.17009743393821'" }, { "code": null, "e": 4657, "s": 4477, "text": "We create a service provider locator this time pass timeout to be 10 minutes since we have many rows. That will prevent timeout errors that you might encounter during the process." }, { "code": null, "e": 4778, "s": 4657, "text": "locator = Nominatim(user_agent=”myGeocoder”, timeout=10)rgeocode = RateLimiter(locator.reverse, min_delay_seconds=0.001)" }, { "code": null, "e": 4933, "s": 4778, "text": "Now, we can reverse geocode by using applying the reverse geocoding rgeocode we created above. To get a nice progress bar, we are using here tqdm library." }, { "code": null, "e": 5007, "s": 4933, "text": "tqdm.pandas()df[‘address’] = df[‘geom’].progress_apply(rgeocode)df.head()" }, { "code": null, "e": 5207, "s": 5007, "text": "It might take a while depending on the number of rows in the dataset. But once the process finishes, you will have an additional feature in the dataset where each point has an address as shown below." }, { "code": null, "e": 5332, "s": 5207, "text": "The data has now much more insightful attributes associated with each point, including address, postcode, buildings, etc...." }, { "code": null, "e": 5609, "s": 5332, "text": "It took 1 minute and 45 seconds to perform reverse geocoding with only 150 points. The computation time is probably not a good option as an increase in data points will require a lot of processing time. If you have a large dataset, you might try to decrease the delay seconds." } ]
tracepath - Unix, Linux Command
tracepath [-nc] <destination>[/<port>] It traces path to destination discovering MTU along this path. It uses UDP port port or some random port. It is similar to traceroute, only does not not require superuser privileges. Option -c causes tracepath to use the return address instead of the reply type (connection refused) to determine when to stop. tracepath6 is good replacement for traceroute6 and classic example of application of Linux error queues. The situation with tracepath is worse, because commercial IP routers do not return enough information in icmp error messages. Probably, it will change, when they will be updated. For now it uses Van Jacobson’s trick, sweeping a range of UDP ports to maintain trace history. root@mops:~ # tracepath6 3ffe:2400:0:109::2 1?: [LOCALHOST] pmtu 1500 1: dust.inr.ac.ru 0.411ms 2: dust.inr.ac.ru asymm 1 0.390ms pmtu 1480 2: 3ffe:2400:0:109::2 463.514ms reached Resume: pmtu 1480 hops 2 back 2 The first column shows TTL of the probe, followed by colon. Usually value of TTL is obtained from reply from network, but sometimes reply does not contain necessary information and we have to guess it. In this case the number is followed by ?. The second column shows the network hop, which replied to the probe. It is either address of router or word [LOCALHOST], if the probe was not sent to the network. The rest of line shows miscellaneous information about path to the correspinding hetwork hop. As rule it contains value of RTT. Additionally, it can show Path MTU, when it changes. If the path is asymmetric or the probe finishes before it reach prescribed hop, difference between number of hops in forward and backward direction is shown folloing keyword async. This information is not reliable. F.e. the third line shows asymmetry of 1, it is because the first probe with TTL of 2 was rejected at the first hop due to Path MTU Discovery. Te last line summarizes information about all the path to the destination, it shows detected Path MTU, amount of hops to the destination and our guess about amount of hops from the destination to us, which can be different when the path is asymmetric. tracepath was written by Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>. No security issues. This lapidary deserves to be elaborated. tracepath is not a privileged program, unlike traceroute, ping and other beasts of this kind. tracepath may be executed by everyone who has some access to network, enough to send UDP datagrams to investigated destination using given port. tracepath is part of iputils package and the latest versions are available in source form from anonymous ftp ftp://ftp.inr.ac.ru/ip-routing/iputils-current.tar.gz. 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": 10618, "s": 10577, "text": "\ntracepath [-nc] <destination>[/<port>]\n" }, { "code": null, "e": 10932, "s": 10620, "text": "\nIt traces path to destination discovering MTU along this path.\nIt uses UDP port port or some random port.\nIt is similar to traceroute, only does not not require superuser\nprivileges. Option -c causes tracepath to use the return address instead\nof the reply type (connection refused) to determine when to stop.\n" }, { "code": null, "e": 11313, "s": 10932, "text": "\ntracepath6 is good replacement for traceroute6\nand classic example of application of Linux error queues.\nThe situation with tracepath is worse, because commercial\nIP routers do not return enough information in icmp error messages.\nProbably, it will change, when they will be updated.\nFor now it uses Van Jacobson’s trick, sweeping a range\nof UDP ports to maintain trace history.\n" }, { "code": null, "e": 11613, "s": 11317, "text": "root@mops:~ # tracepath6 3ffe:2400:0:109::2\n 1?: [LOCALHOST] pmtu 1500\n 1: dust.inr.ac.ru 0.411ms\n 2: dust.inr.ac.ru asymm 1 0.390ms pmtu 1480\n 2: 3ffe:2400:0:109::2 463.514ms reached\n Resume: pmtu 1480 hops 2 back 2\n" }, { "code": null, "e": 11859, "s": 11613, "text": "\nThe first column shows TTL of the probe, followed by colon.\nUsually value of TTL is obtained from reply from network,\nbut sometimes reply does not contain necessary information and\nwe have to guess it. In this case the number is followed by ?.\n" }, { "code": null, "e": 12024, "s": 11859, "text": "\nThe second column shows the network hop, which replied to the probe.\nIt is either address of router or word [LOCALHOST], if\nthe probe was not sent to the network.\n" }, { "code": null, "e": 12565, "s": 12024, "text": "\nThe rest of line shows miscellaneous information about path to\nthe correspinding hetwork hop. As rule it contains value of RTT.\nAdditionally, it can show Path MTU, when it changes.\nIf the path is asymmetric\nor the probe finishes before it reach prescribed hop, difference\nbetween number of hops in forward and backward direction is shown\nfolloing keyword async. This information is not reliable.\nF.e. the third line shows asymmetry of 1, it is because the first probe\nwith TTL of 2 was rejected at the first hop due to Path MTU Discovery.\n" }, { "code": null, "e": 12819, "s": 12565, "text": "\nTe last line summarizes information about all the path to the destination,\nit shows detected Path MTU, amount of hops to the destination and our\nguess about amount of hops from the destination to us, which can be\ndifferent when the path is asymmetric.\n" }, { "code": null, "e": 12887, "s": 12819, "text": "\ntracepath was written by\nAlexey Kuznetsov\n<kuznet@ms2.inr.ac.ru>.\n" }, { "code": null, "e": 12909, "s": 12887, "text": "\nNo security issues.\n" }, { "code": null, "e": 13191, "s": 12909, "text": "\nThis lapidary deserves to be elaborated.\ntracepath is not a privileged program, unlike\ntraceroute, ping and other beasts of this kind.\ntracepath may be executed by everyone who has some access\nto network, enough to send UDP datagrams to investigated destination\nusing given port.\n" }, { "code": null, "e": 13367, "s": 13191, "text": "\ntracepath is part of iputils package\nand the latest versions are available in source form from anonymous ftp\nftp://ftp.inr.ac.ru/ip-routing/iputils-current.tar.gz.\n\n\n\n\n\n\n\n\n\n" }, { "code": null, "e": 13384, "s": 13367, "text": "\nAdvertisements\n" }, { "code": null, "e": 13419, "s": 13384, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 13447, "s": 13419, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 13481, "s": 13447, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13498, "s": 13481, "text": " Frahaan Hussain" }, { "code": null, "e": 13531, "s": 13498, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 13542, "s": 13531, "text": " Pradeep D" }, { "code": null, "e": 13577, "s": 13542, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13593, "s": 13577, "text": " Musab Zayadneh" }, { "code": null, "e": 13626, "s": 13593, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 13638, "s": 13626, "text": " GUHARAJANM" }, { "code": null, "e": 13670, "s": 13638, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 13678, "s": 13670, "text": " Uplatz" }, { "code": null, "e": 13685, "s": 13678, "text": " Print" }, { "code": null, "e": 13696, "s": 13685, "text": " Add Notes" } ]
Unix Socket - Network Byte Orders
Unfortunately, not all computers store the bytes that comprise a multibyte value in the same order. Consider a 16-bit internet that is made up of 2 bytes. There are two ways to store this value. Little Endian − In this scheme, low-order byte is stored on the starting address (A) and high-order byte is stored on the next address (A + 1). Little Endian − In this scheme, low-order byte is stored on the starting address (A) and high-order byte is stored on the next address (A + 1). Big Endian − In this scheme, high-order byte is stored on the starting address (A) and low-order byte is stored on the next address (A + 1). Big Endian − In this scheme, high-order byte is stored on the starting address (A) and low-order byte is stored on the next address (A + 1). To allow machines with different byte order conventions communicate with each other, the Internet protocols specify a canonical byte order convention for data transmitted over the network. This is known as Network Byte Order. While establishing an Internet socket connection, you must make sure that the data in the sin_port and sin_addr members of the sockaddr_in structure are represented in Network Byte Order. Routines for converting data between a host's internal representation and Network Byte Order are as follows − Listed below are some more detail about these functions − unsigned short htons(unsigned short hostshort) − This function converts 16-bit (2-byte) quantities from host byte order to network byte order. unsigned short htons(unsigned short hostshort) − This function converts 16-bit (2-byte) quantities from host byte order to network byte order. unsigned long htonl(unsigned long hostlong) − This function converts 32-bit (4-byte) quantities from host byte order to network byte order. unsigned long htonl(unsigned long hostlong) − This function converts 32-bit (4-byte) quantities from host byte order to network byte order. unsigned short ntohs(unsigned short netshort) − This function converts 16-bit (2-byte) quantities from network byte order to host byte order. unsigned short ntohs(unsigned short netshort) − This function converts 16-bit (2-byte) quantities from network byte order to host byte order. unsigned long ntohl(unsigned long netlong) − This function converts 32-bit quantities from network byte order to host byte order. unsigned long ntohl(unsigned long netlong) − This function converts 32-bit quantities from network byte order to host byte order. These functions are macros and result in the insertion of conversion source code into the calling program. On little-endian machines, the code will change the values around to network byte order. On big-endian machines, no code is inserted since none is needed; the functions are defined as null. Keep the following code in a file byteorder.c and then compile it and run it over your machine. In this example, we store the two-byte value 0x0102 in the short integer and then look at the two consecutive bytes, c[0] (the address A) and c[1] (the address A + 1) to determine the byte order. #include <stdio.h> int main(int argc, char **argv) { union { short s; char c[sizeof(short)]; }un; un.s = 0x0102; if (sizeof(short) == 2) { if (un.c[0] == 1 && un.c[1] == 2) printf("big-endian\n"); else if (un.c[0] == 2 && un.c[1] == 1) printf("little-endian\n"); else printf("unknown\n"); } else { printf("sizeof(short) = %d\n", sizeof(short)); } exit(0); } An output generated by this program on a Pentium machine is as follows − $> gcc byteorder.c $> ./a.out little-endian $> 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": 2198, "s": 2003, "text": "Unfortunately, not all computers store the bytes that comprise a multibyte value in the same order. Consider a 16-bit internet that is made up of 2 bytes. There are two ways to store this value." }, { "code": null, "e": 2342, "s": 2198, "text": "Little Endian − In this scheme, low-order byte is stored on the starting address (A) and high-order byte is stored on the next address (A + 1)." }, { "code": null, "e": 2486, "s": 2342, "text": "Little Endian − In this scheme, low-order byte is stored on the starting address (A) and high-order byte is stored on the next address (A + 1)." }, { "code": null, "e": 2627, "s": 2486, "text": "Big Endian − In this scheme, high-order byte is stored on the starting address (A) and low-order byte is stored on the next address (A + 1)." }, { "code": null, "e": 2768, "s": 2627, "text": "Big Endian − In this scheme, high-order byte is stored on the starting address (A) and low-order byte is stored on the next address (A + 1)." }, { "code": null, "e": 2994, "s": 2768, "text": "To allow machines with different byte order conventions communicate with each other, the Internet protocols specify a canonical byte order convention for data transmitted over the network. This is known as Network Byte Order." }, { "code": null, "e": 3182, "s": 2994, "text": "While establishing an Internet socket connection, you must make sure that the data in the sin_port and sin_addr members of the sockaddr_in structure are represented in Network Byte Order." }, { "code": null, "e": 3292, "s": 3182, "text": "Routines for converting data between a host's internal representation and Network Byte Order are as follows −" }, { "code": null, "e": 3350, "s": 3292, "text": "Listed below are some more detail about these functions −" }, { "code": null, "e": 3493, "s": 3350, "text": "unsigned short htons(unsigned short hostshort) − This function converts 16-bit (2-byte) quantities from host byte order to network byte order." }, { "code": null, "e": 3636, "s": 3493, "text": "unsigned short htons(unsigned short hostshort) − This function converts 16-bit (2-byte) quantities from host byte order to network byte order." }, { "code": null, "e": 3776, "s": 3636, "text": "unsigned long htonl(unsigned long hostlong) − This function converts 32-bit (4-byte) quantities from host byte order to network byte order." }, { "code": null, "e": 3916, "s": 3776, "text": "unsigned long htonl(unsigned long hostlong) − This function converts 32-bit (4-byte) quantities from host byte order to network byte order." }, { "code": null, "e": 4058, "s": 3916, "text": "unsigned short ntohs(unsigned short netshort) − This function converts 16-bit (2-byte) quantities from network byte order to host byte order." }, { "code": null, "e": 4200, "s": 4058, "text": "unsigned short ntohs(unsigned short netshort) − This function converts 16-bit (2-byte) quantities from network byte order to host byte order." }, { "code": null, "e": 4330, "s": 4200, "text": "unsigned long ntohl(unsigned long netlong) − This function converts 32-bit quantities from network byte order to host byte order." }, { "code": null, "e": 4460, "s": 4330, "text": "unsigned long ntohl(unsigned long netlong) − This function converts 32-bit quantities from network byte order to host byte order." }, { "code": null, "e": 4757, "s": 4460, "text": "These functions are macros and result in the insertion of conversion source code into the calling program. On little-endian machines, the code will change the values around to network byte order. On big-endian machines, no code is inserted since none is needed; the functions are defined as null." }, { "code": null, "e": 4853, "s": 4757, "text": "Keep the following code in a file byteorder.c and then compile it and run it over your machine." }, { "code": null, "e": 5049, "s": 4853, "text": "In this example, we store the two-byte value 0x0102 in the short integer and then look at the two consecutive bytes, c[0] (the address A) and c[1] (the address A + 1) to determine the byte order." }, { "code": null, "e": 5518, "s": 5049, "text": "#include <stdio.h>\n\nint main(int argc, char **argv) {\n\n union {\n short s;\n char c[sizeof(short)];\n }un;\n\t\n un.s = 0x0102;\n \n if (sizeof(short) == 2) {\n if (un.c[0] == 1 && un.c[1] == 2)\n printf(\"big-endian\\n\");\n \n else if (un.c[0] == 2 && un.c[1] == 1)\n printf(\"little-endian\\n\");\n \n else\n printf(\"unknown\\n\");\n }\n else {\n printf(\"sizeof(short) = %d\\n\", sizeof(short));\n }\n\t\n exit(0);\n}" }, { "code": null, "e": 5591, "s": 5518, "text": "An output generated by this program on a Pentium machine is as follows −" }, { "code": null, "e": 5639, "s": 5591, "text": "$> gcc byteorder.c\n$> ./a.out\nlittle-endian\n$>\n" }, { "code": null, "e": 5674, "s": 5639, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 5702, "s": 5674, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5736, "s": 5702, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5753, "s": 5736, "text": " Frahaan Hussain" }, { "code": null, "e": 5786, "s": 5753, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 5797, "s": 5786, "text": " Pradeep D" }, { "code": null, "e": 5832, "s": 5797, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5848, "s": 5832, "text": " Musab Zayadneh" }, { "code": null, "e": 5881, "s": 5848, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 5893, "s": 5881, "text": " GUHARAJANM" }, { "code": null, "e": 5925, "s": 5893, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 5933, "s": 5925, "text": " Uplatz" }, { "code": null, "e": 5940, "s": 5933, "text": " Print" }, { "code": null, "e": 5951, "s": 5940, "text": " Add Notes" } ]
How to pause in Node.js for a specific time ? - GeeksforGeeks
07 Oct, 2021 Sometimes we need to execute some function after some amount of time like you asked for something from the user and the details are required for the next function from the server end. That time we will require a pause in our server. So to pause for a specific time we use the setTimeout() function. It has a callback function attached to it which gets executed after a given amount of time. The setTimeout() can be used to execute the code after a given amount of milliseconds. There is one thing you can do for multiple functions that you can break the functions into different blocks of code and use the setTimeout() between them. Syntax: setTimeout(function, milliseconds); Below example illustrate the approach of pausing the NOdeJS by using setTimeout() function: Example: This function uses setTimeout() under the hood and shows geek! After Hello after 2 seconds. Here the file name is wait.js. wait.js function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms));} console.log("Hello");sleep(2000).then(() => { console.log("Geek!");}); Output: NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Express.js res.sendFile() Function Express.js res.redirect() Function Top 10 Front End Developer Skills That You Need in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24105, "s": 24077, "text": "\n07 Oct, 2021" }, { "code": null, "e": 24583, "s": 24105, "text": "Sometimes we need to execute some function after some amount of time like you asked for something from the user and the details are required for the next function from the server end. That time we will require a pause in our server. So to pause for a specific time we use the setTimeout() function. It has a callback function attached to it which gets executed after a given amount of time. The setTimeout() can be used to execute the code after a given amount of milliseconds." }, { "code": null, "e": 24738, "s": 24583, "text": "There is one thing you can do for multiple functions that you can break the functions into different blocks of code and use the setTimeout() between them." }, { "code": null, "e": 24746, "s": 24738, "text": "Syntax:" }, { "code": null, "e": 24782, "s": 24746, "text": "setTimeout(function, milliseconds);" }, { "code": null, "e": 24874, "s": 24782, "text": "Below example illustrate the approach of pausing the NOdeJS by using setTimeout() function:" }, { "code": null, "e": 25006, "s": 24874, "text": "Example: This function uses setTimeout() under the hood and shows geek! After Hello after 2 seconds. Here the file name is wait.js." }, { "code": null, "e": 25014, "s": 25006, "text": "wait.js" }, { "code": "function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms));} console.log(\"Hello\");sleep(2000).then(() => { console.log(\"Geek!\");});", "e": 25168, "s": 25014, "text": null }, { "code": null, "e": 25176, "s": 25168, "text": "Output:" }, { "code": null, "e": 25193, "s": 25176, "text": "NodeJS-Questions" }, { "code": null, "e": 25200, "s": 25193, "text": "Picked" }, { "code": null, "e": 25208, "s": 25200, "text": "Node.js" }, { "code": null, "e": 25225, "s": 25208, "text": "Web Technologies" }, { "code": null, "e": 25323, "s": 25225, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25332, "s": 25323, "text": "Comments" }, { "code": null, "e": 25345, "s": 25332, "text": "Old Comments" }, { "code": null, "e": 25402, "s": 25345, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 25456, "s": 25402, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 25493, "s": 25456, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 25528, "s": 25493, "text": "Express.js res.sendFile() Function" }, { "code": null, "e": 25563, "s": 25528, "text": "Express.js res.redirect() Function" }, { "code": null, "e": 25619, "s": 25563, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 25681, "s": 25619, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 25724, "s": 25681, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 25774, "s": 25724, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to use jQuery.getScript() method to load external js files?
The jQuery.getScript( url, [callback] ) method loads and executes a JavaScript file using an HTTP GET request. Here is the description of all the parameters used by this method − url − A string containing the URL to which the request is sent callback − This optional parameter represents a function to be executed whenever the data is loaded successfully. Assuming we have following JavaScript content in result.js file − function CheckJS(){ alert("This is JavaScript"); } The following is the code snippet showing the usage of this method − <head> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> $(document).ready(function() { $("#driver").click(function(event){ $.getScript('result.js', function(jd) { // Call custom function defined in script CheckJS(); }); }); }); </script> </head> <body> <p>Click on the button to load result.js file −</p> <div id = "stage" style = "background-color:cc0;"> STAGE </div> <input type = "button" id = "driver" value = "Load Data" /> </body>
[ { "code": null, "e": 1173, "s": 1062, "text": "The jQuery.getScript( url, [callback] ) method loads and executes a JavaScript file using an HTTP GET request." }, { "code": null, "e": 1241, "s": 1173, "text": "Here is the description of all the parameters used by this method −" }, { "code": null, "e": 1304, "s": 1241, "text": "url − A string containing the URL to which the request is sent" }, { "code": null, "e": 1418, "s": 1304, "text": "callback − This optional parameter represents a function to be executed whenever the data is loaded successfully." }, { "code": null, "e": 1484, "s": 1418, "text": "Assuming we have following JavaScript content in result.js file −" }, { "code": null, "e": 1538, "s": 1484, "text": "function CheckJS(){\n alert(\"This is JavaScript\");\n}" }, { "code": null, "e": 1607, "s": 1538, "text": "The following is the code snippet showing the usage of this method −" }, { "code": null, "e": 2331, "s": 1607, "text": "<head>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function() {\n \n $(\"#driver\").click(function(event){\n $.getScript('result.js', function(jd) {\n // Call custom function defined in script\n CheckJS();\n });\n });\n \n });\n </script>\n </head>\n \n <body>\n \n <p>Click on the button to load result.js file −</p>\n \n <div id = \"stage\" style = \"background-color:cc0;\">\n STAGE\n </div>\n \n <input type = \"button\" id = \"driver\" value = \"Load Data\" />\n \n </body>" } ]
Delete Database in MS SQL Server - GeeksforGeeks
02 Sep, 2020 Prerequisite – Introduction of MS SQL Server and Create Database in MS SQL Server System databases can’t be deleted, only user databases could be deleted. Data and log files will automatically be deleted from disk with database deletion. To delete a database, the below methods could be used – SQL Server Management Studio.Transact-SQL. SQL Server Management Studio. Transact-SQL. These are explained as following below. 1. Using SQL Server Management Studio :To delete a database, connect to an instance of the SQL Server, and then expand that instance. Expand Databases, select the database which need to be deleted. Right-click the database which need to be deleted, and then click Delete. Check delete backup and restore history or close existing connections if required and then click OK. 2. Using Transact-SQL :To execute DROP DATABASE statement a user must have CONTROL permission on the database. To delete a database :USE master ; GO DROP DATABASE Databasename; GO USE master ; GO DROP DATABASE Databasename; GO To delete multiple databases :USE master ; GO DROP DATABASE database1, database2, ...; GO USE master ; GO DROP DATABASE database1, database2, ...; GO Example :Let us assume we have created a database “Geekstest” which is no longer required, to delete database : USE master ; GO DROP DATABASE Geekstest; GO DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SQL | Views Difference between DELETE, DROP and TRUNCATE How to Update Multiple Columns in Single Update Statement in SQL? SQL | GROUP BY Difference between DDL and DML in DBMS SQL Interview Questions What is Temporary Table in SQL? MySQL | Group_CONCAT() Function Difference between Where and Having Clause in SQL SQL - ORDER BY
[ { "code": null, "e": 23483, "s": 23455, "text": "\n02 Sep, 2020" }, { "code": null, "e": 23565, "s": 23483, "text": "Prerequisite – Introduction of MS SQL Server and Create Database in MS SQL Server" }, { "code": null, "e": 23721, "s": 23565, "text": "System databases can’t be deleted, only user databases could be deleted. Data and log files will automatically be deleted from disk with database deletion." }, { "code": null, "e": 23777, "s": 23721, "text": "To delete a database, the below methods could be used –" }, { "code": null, "e": 23820, "s": 23777, "text": "SQL Server Management Studio.Transact-SQL." }, { "code": null, "e": 23850, "s": 23820, "text": "SQL Server Management Studio." }, { "code": null, "e": 23864, "s": 23850, "text": "Transact-SQL." }, { "code": null, "e": 23904, "s": 23864, "text": "These are explained as following below." }, { "code": null, "e": 24038, "s": 23904, "text": "1. Using SQL Server Management Studio :To delete a database, connect to an instance of the SQL Server, and then expand that instance." }, { "code": null, "e": 24102, "s": 24038, "text": "Expand Databases, select the database which need to be deleted." }, { "code": null, "e": 24176, "s": 24102, "text": "Right-click the database which need to be deleted, and then click Delete." }, { "code": null, "e": 24277, "s": 24176, "text": "Check delete backup and restore history or close existing connections if required and then click OK." }, { "code": null, "e": 24388, "s": 24277, "text": "2. Using Transact-SQL :To execute DROP DATABASE statement a user must have CONTROL permission on the database." }, { "code": null, "e": 24465, "s": 24388, "text": "To delete a database :USE master ; \nGO \nDROP DATABASE Databasename; \nGO " }, { "code": null, "e": 24520, "s": 24465, "text": "USE master ; \nGO \nDROP DATABASE Databasename; \nGO " }, { "code": null, "e": 24616, "s": 24520, "text": "To delete multiple databases :USE master ; \nGO \nDROP DATABASE database1, database2, ...; \nGO" }, { "code": null, "e": 24682, "s": 24616, "text": "USE master ; \nGO \nDROP DATABASE database1, database2, ...; \nGO" }, { "code": null, "e": 24794, "s": 24682, "text": "Example :Let us assume we have created a database “Geekstest” which is no longer required, to delete database :" }, { "code": null, "e": 24839, "s": 24794, "text": "USE master ;\nGO\nDROP DATABASE Geekstest;\nGO " }, { "code": null, "e": 24848, "s": 24839, "text": "DBMS-SQL" }, { "code": null, "e": 24859, "s": 24848, "text": "SQL-Server" }, { "code": null, "e": 24863, "s": 24859, "text": "SQL" }, { "code": null, "e": 24867, "s": 24863, "text": "SQL" }, { "code": null, "e": 24965, "s": 24867, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24974, "s": 24965, "text": "Comments" }, { "code": null, "e": 24987, "s": 24974, "text": "Old Comments" }, { "code": null, "e": 24999, "s": 24987, "text": "SQL | Views" }, { "code": null, "e": 25044, "s": 24999, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 25110, "s": 25044, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 25125, "s": 25110, "text": "SQL | GROUP BY" }, { "code": null, "e": 25164, "s": 25125, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 25188, "s": 25164, "text": "SQL Interview Questions" }, { "code": null, "e": 25220, "s": 25188, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 25252, "s": 25220, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 25302, "s": 25252, "text": "Difference between Where and Having Clause in SQL" } ]
How to use POSIX semaphores in C language
The semaphore is a concept of process or thread synchronization. Here we will see how to use the semaphores in real programs. In Linux system, we can get the POSIX semaphore library. To use it, we have to include semaphores.h library. We have to compile the code using the following options. gcc program_name.c –lpthread -lrt We can use sem_wait() to lock or wait. And sem_post() to release the lock. The semaphore initializes sem_init() or sem_open() for the Inter-Process Communication (IPC). #include <stdio.h> #include <pthread.h> #include <semaphore.h> #include <unistd.h> sem_t mutex; void* thread(void* arg) { //function which act like thread sem_wait(&mutex); //wait state printf("\nEntered into the Critical Section..\n"); sleep(3); //critical section printf("\nCompleted...\n"); //comming out from Critical section sem_post(&mutex); } main() { sem_init(&mutex, 0, 1); pthread_t th1,th2; pthread_create(&th1,NULL,thread,NULL); sleep(2); pthread_create(&th2,NULL,thread,NULL); //Join threads with the main thread pthread_join(th1,NULL); pthread_join(th2,NULL); sem_destroy(&mutex); } soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ gcc 1270.posix_semaphore.c -lpthread -lrt 1270.posix_semaphore.c:19:1: warning: return type defaults to ‘int’ [-Wimplicit-int] main() { ^~~~ soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ ./a.out Entered into the Critical Section.. Completed... Entered into the Critical Section.. Completed... soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$
[ { "code": null, "e": 1188, "s": 1062, "text": "The semaphore is a concept of process or thread synchronization. Here we will see how to use the semaphores in real programs." }, { "code": null, "e": 1354, "s": 1188, "text": "In Linux system, we can get the POSIX semaphore library. To use it, we have to include semaphores.h library. We have to compile the code using the following options." }, { "code": null, "e": 1388, "s": 1354, "text": "gcc program_name.c –lpthread -lrt" }, { "code": null, "e": 1557, "s": 1388, "text": "We can use sem_wait() to lock or wait. And sem_post() to release the lock. The semaphore initializes sem_init() or sem_open() for the Inter-Process Communication (IPC)." }, { "code": null, "e": 2196, "s": 1557, "text": "#include <stdio.h>\n#include <pthread.h>\n#include <semaphore.h>\n#include <unistd.h>\nsem_t mutex;\nvoid* thread(void* arg) { //function which act like thread\n sem_wait(&mutex); //wait state\n printf(\"\\nEntered into the Critical Section..\\n\");\n sleep(3); //critical section\n printf(\"\\nCompleted...\\n\"); //comming out from Critical section\n sem_post(&mutex);\n}\nmain() {\n sem_init(&mutex, 0, 1);\n pthread_t th1,th2;\n pthread_create(&th1,NULL,thread,NULL);\n sleep(2);\n pthread_create(&th2,NULL,thread,NULL);\n //Join threads with the main thread\n pthread_join(th1,NULL);\n pthread_join(th2,NULL);\n sem_destroy(&mutex);\n}" }, { "code": null, "e": 2585, "s": 2196, "text": "soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ gcc 1270.posix_semaphore.c -lpthread -lrt\n1270.posix_semaphore.c:19:1: warning: return type defaults to ‘int’ [-Wimplicit-int]\nmain() {\n^~~~\nsoumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ ./a.out\n\nEntered into the Critical Section..\n\nCompleted...\n\nEntered into the Critical Section..\n\nCompleted...\nsoumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$" } ]
Class Keyword in JavaScript
JavaScript classes, introduced in ES6, are syntactical sugar over JavaScript prototype-based inheritance. Classes are in fact "special functions". You can define classes in JavaScript using the class keyword using the following syntax − class Person { // Constructor for this class constructor(name) { this.name = name; } // an instance method on this class displayName() { console.log(this.name) } } This is essentially equivalent to the following declaration − let Person = function(name) { this.name = name; } Person.prototype.displayName = function() { console.log(this.name) } This class can also be written as a class expressions. The above format is a class declaration. The following format is a class expression − // Unnamed expression let Person = class { // Constructor for this class constructor(name) { this.name = name; } // an instance method on this class displayName() { console.log(this.name) } } No matter how you define the classes as mentioned above, you can create objects of these classes using the following − let John = new Person("John"); John.displayName(); John You can read in depth about JS classes and the class keyword at https://www.tutorialspoint.com/es6/es6_classes.htm.
[ { "code": null, "e": 1299, "s": 1062, "text": "JavaScript classes, introduced in ES6, are syntactical sugar over JavaScript prototype-based inheritance. Classes are in fact \"special functions\". You can define classes in JavaScript using the class keyword using the following syntax −" }, { "code": null, "e": 1493, "s": 1299, "text": "class Person {\n // Constructor for this class\n constructor(name) {\n this.name = name;\n }\n // an instance method on this class\n displayName() {\n console.log(this.name)\n }\n}" }, { "code": null, "e": 1555, "s": 1493, "text": "This is essentially equivalent to the following declaration −" }, { "code": null, "e": 1680, "s": 1555, "text": "let Person = function(name) {\n this.name = name;\n}\nPerson.prototype.displayName = function() {\n console.log(this.name)\n}" }, { "code": null, "e": 1821, "s": 1680, "text": "This class can also be written as a class expressions. The above format is a class declaration. The following format is a class expression −" }, { "code": null, "e": 2043, "s": 1821, "text": "// Unnamed expression\nlet Person = class {\n // Constructor for this class\n constructor(name) {\n this.name = name;\n }\n // an instance method on this class\n displayName() {\n console.log(this.name)\n }\n}" }, { "code": null, "e": 2162, "s": 2043, "text": "No matter how you define the classes as mentioned above, you can create objects of these classes using the following −" }, { "code": null, "e": 2213, "s": 2162, "text": "let John = new Person(\"John\");\nJohn.displayName();" }, { "code": null, "e": 2218, "s": 2213, "text": "John" }, { "code": null, "e": 2334, "s": 2218, "text": "You can read in depth about JS classes and the class keyword at https://www.tutorialspoint.com/es6/es6_classes.htm." } ]
What is BLOB data type in MySQL?
A BLOB is binary large object that can hold a variable amount of data. Followings are some points about BLOB data type − BLOB is the family of column type intended as high-capacity binary storage. The actual BLOB column type is of four types-TINYBLOB, BLOB, MEDIUMBLOB and LONGBLOB. The four BLOB types are very similar to each other; the only difference is the maximum amount of data each can store. Example − Following example shows how to declare a column as BLOB. mysql> Create table stock(ID INT, Name VARCHAR(40), PHOTO BLOB, Quantity INT); Query OK, 0 rows affected (0.15 sec) mysql> Describe stock; +----------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+-------+ | ID | int(11) | YES | | NULL | | | Name | varchar(40) | YES | | NULL | | | PHOTO | blob | YES | | NULL | | | Quantity | int(11) | YES | | NULL | | +----------+-------------+------+-----+---------+-------+ 4 rows in set (0.03 sec)
[ { "code": null, "e": 1184, "s": 1062, "text": " A BLOB is binary large object that can hold a variable amount of data. Followings are some points about BLOB data type −" }, { "code": null, "e": 1260, "s": 1184, "text": "BLOB is the family of column type intended as high-capacity binary storage." }, { "code": null, "e": 1346, "s": 1260, "text": "The actual BLOB column type is of four types-TINYBLOB, BLOB, MEDIUMBLOB and LONGBLOB." }, { "code": null, "e": 1464, "s": 1346, "text": "The four BLOB types are very similar to each other; the only difference is the maximum amount of data each can store." }, { "code": null, "e": 1531, "s": 1464, "text": "Example − Following example shows how to declare a column as BLOB." }, { "code": null, "e": 2160, "s": 1531, "text": "mysql> Create table stock(ID INT, Name VARCHAR(40), PHOTO BLOB, Quantity INT);\nQuery OK, 0 rows affected (0.15 sec)\n\nmysql> Describe stock;\n+----------+-------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+----------+-------------+------+-----+---------+-------+\n| ID | int(11) | YES | | NULL | |\n| Name | varchar(40) | YES | | NULL | |\n| PHOTO | blob | YES | | NULL | |\n| Quantity | int(11) | YES | | NULL | |\n+----------+-------------+------+-----+---------+-------+\n4 rows in set (0.03 sec)" } ]
MS SQL Server - Login Database
A login is a simple credential for accessing SQL Server. For example, you provide your username and password when logging on to Windows or even your e-mail account. This username and password builds up the credentials. Therefore, credentials are simply a username and a password. SQL Server allows four types of logins − A login based on Windows credentials. A login specific to SQL Server. A login mapped to a certificate. A login mapped to asymmetric key. In this tutorial, we are interested in logins based on Windows Credentials and logins specific to SQL Server. Logins based on Windows credentials allow you to log in to SQL Server using a Windows username and password. If you need to create your own credentials (username and password,) you can create a login specific to SQL Server. To create, alter, or remove a SQL Server login, you can take one of two approaches − Using SQL Server Management Studio. Using T-SQL statements. Following methods are used to create Login − Step 1 − After connecting to SQL Server Instance, expand logins folder as shown in the following snapshot. Step 2 − Right-click on Logins, then click Newlogin and the following screen will open. Step 3 − Fill the Login name, Password and Confirm password columns as shown in the above screen and then click OK. Login will be created as shown in the following image. Create login yourloginname with password='yourpassword' To create login name with TestLogin and password ‘P@ssword’ run below the following query. Create login TestLogin with password='P@ssword' 32 Lectures 2.5 hours Pavan Lalwani 18 Lectures 1.5 hours Dr. Saatya Prasad 102 Lectures 10 hours Pavan Lalwani 52 Lectures 4 hours Pavan Lalwani 239 Lectures 33 hours Gowthami Swarna 53 Lectures 5 hours Akshay Magre Print Add Notes Bookmark this page
[ { "code": null, "e": 2515, "s": 2235, "text": "A login is a simple credential for accessing SQL Server. For example, you provide your username and password when logging on to Windows or even your e-mail account. This username and password builds up the credentials. Therefore, credentials are simply a username and a password." }, { "code": null, "e": 2556, "s": 2515, "text": "SQL Server allows four types of logins −" }, { "code": null, "e": 2594, "s": 2556, "text": "A login based on Windows credentials." }, { "code": null, "e": 2626, "s": 2594, "text": "A login specific to SQL Server." }, { "code": null, "e": 2659, "s": 2626, "text": "A login mapped to a certificate." }, { "code": null, "e": 2693, "s": 2659, "text": "A login mapped to asymmetric key." }, { "code": null, "e": 2803, "s": 2693, "text": "In this tutorial, we are interested in logins based on Windows Credentials and logins specific to SQL Server." }, { "code": null, "e": 3027, "s": 2803, "text": "Logins based on Windows credentials allow you to log in to SQL Server using a Windows username and password. If you need to create your own credentials (username and password,) you can create a login specific to SQL Server." }, { "code": null, "e": 3112, "s": 3027, "text": "To create, alter, or remove a SQL Server login, you can take one of two approaches −" }, { "code": null, "e": 3148, "s": 3112, "text": "Using SQL Server Management Studio." }, { "code": null, "e": 3172, "s": 3148, "text": "Using T-SQL statements." }, { "code": null, "e": 3217, "s": 3172, "text": "Following methods are used to create Login −" }, { "code": null, "e": 3324, "s": 3217, "text": "Step 1 − After connecting to SQL Server Instance, expand logins folder as shown in the following snapshot." }, { "code": null, "e": 3412, "s": 3324, "text": "Step 2 − Right-click on Logins, then click Newlogin and the following screen will open." }, { "code": null, "e": 3528, "s": 3412, "text": "Step 3 − Fill the Login name, Password and Confirm password columns as shown in the above screen and then click OK." }, { "code": null, "e": 3583, "s": 3528, "text": "Login will be created as shown in the following image." }, { "code": null, "e": 3640, "s": 3583, "text": "Create login yourloginname with password='yourpassword'\n" }, { "code": null, "e": 3731, "s": 3640, "text": "To create login name with TestLogin and password ‘P@ssword’ run below the following query." }, { "code": null, "e": 3780, "s": 3731, "text": "Create login TestLogin with password='P@ssword'\n" }, { "code": null, "e": 3815, "s": 3780, "text": "\n 32 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3830, "s": 3815, "text": " Pavan Lalwani" }, { "code": null, "e": 3865, "s": 3830, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3884, "s": 3865, "text": " Dr. Saatya Prasad" }, { "code": null, "e": 3919, "s": 3884, "text": "\n 102 Lectures \n 10 hours \n" }, { "code": null, "e": 3934, "s": 3919, "text": " Pavan Lalwani" }, { "code": null, "e": 3967, "s": 3934, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 3982, "s": 3967, "text": " Pavan Lalwani" }, { "code": null, "e": 4017, "s": 3982, "text": "\n 239 Lectures \n 33 hours \n" }, { "code": null, "e": 4034, "s": 4017, "text": " Gowthami Swarna" }, { "code": null, "e": 4067, "s": 4034, "text": "\n 53 Lectures \n 5 hours \n" }, { "code": null, "e": 4081, "s": 4067, "text": " Akshay Magre" }, { "code": null, "e": 4088, "s": 4081, "text": " Print" }, { "code": null, "e": 4099, "s": 4088, "text": " Add Notes" } ]
How to get the Windows certificate details using PowerShell?
We know that the Windows Certificates are resided in the Certificate store but finding the certificate with its name or getting particular certificate details might be cumbersome sometimes. You can access the certificate store using MMC or using CertMgr.msc command. There are certificates stored for CurrentUser, ServiceAccount, and Local Computer. To access the certificate store using PowerShell, you need to access the PSDrive, and Certificates are stored in the drive called Cert as you can see below. PS C:\> Get-PSDrive cert | ft -AutoSize Name Used (GB) Free (GB) Provider Root CurrentLocation ---- --------- --------- -------- ---- --------------- Cert Certificate \ Let say we want to retrieve the details of the certificate stored in the Root directory in the local machine account then we can use the below command. Get-ChildItem Cert:\LocalMachine\Root\ PSParentPath: Microsoft.PowerShell.Security\Certificate::LocalMachine\Root Thumbprint Subject ---------- ------- CDD4EEAE6000AC7F40C3802C171E30148030C072 CN=Microsoft Root Certificate Authority BE36A4562FB2EE05DBB3D32323ADF445084ED656 CN=Thawte Timestamping CA, OU=Thawte Ce A43489159A520F0D93D032CCAF37E7FE20A8B419 CN=Microsoft Root Authority, OU=Microso 92B46C76E13054E104F230517E6E504D43AB10B5 CN=Symantec Enterprise Mobile Root for 8F43288AD272F3103B6FB1428485EA3014C0BCFE CN=Microsoft Root Certificate Authority 7F88CD7223F3C813818C994614A89C99FA3B5247 CN=Microsoft Authenticode(tm) Root Auth Or you can also use the below command, Get-Item Cert:\LocalMachine\Root\* | ft -AutoSize The below command will get all the Microsoft certificates. Get-ChildItem Cert:\LocalMachine\Root\ | where{$_.Subject -like "*Microsoft*"} To find the specific certificate, you should know the certificate friendly name. For example, to find the “DigiCert” certificate from the Root store, Get-ChildItem Cert:\LocalMachine\Root\ | where{$_.FriendlyName -eq 'DigiCert'} Thumbprint Subject ---------- ------- A8985D3A65E5E5C4B2D7D66D40C6DD2FB19C5436 CN=DigiCert Global Root CA, OU=www.digicert.com, 0563B8630D62D75ABBC8AB1E4BDFB5A899B24D43 CN=DigiCert Assured ID Root CA, OU=www.digicert.com To search directly from the LocalComputer, CurrentUser, or Root store, use -Recurse parameter. Get-ChildItem Cert:\LocalMachine\ -Recurse | where{$_.FriendlyName -eq 'DigiCert'} Once you get the thumbprint or friendly Name, you can use the fl * pipeline to get the full details of the certificate. Get-ChildItem Cert:\LocalMachine\root | where{$_.FriendlyName -eq 'DigiCert'} | fl * For the remote servers, we can use Invoke-Command, the below example will get the certificates from the remote servers. Invoke-Command -ComputerName Test1Comp, Test2Comp -Scriptblock{ Get-ChildItem Cert:\LocalMachine\root | where{$_.FriendlyName -eq 'DigiCert'} }
[ { "code": null, "e": 1252, "s": 1062, "text": "We know that the Windows Certificates are resided in the Certificate store but finding the certificate with its name or getting particular certificate details might be cumbersome sometimes." }, { "code": null, "e": 1569, "s": 1252, "text": "You can access the certificate store using MMC or using CertMgr.msc command. There are certificates stored for CurrentUser, ServiceAccount, and Local Computer. To access the certificate store using PowerShell, you need to access the PSDrive, and Certificates are stored in the drive called Cert as you can see below." }, { "code": null, "e": 1738, "s": 1569, "text": "PS C:\\> Get-PSDrive cert | ft -AutoSize\nName Used (GB) Free (GB) Provider Root CurrentLocation\n---- --------- --------- -------- ---- ---------------\nCert Certificate \\" }, { "code": null, "e": 1890, "s": 1738, "text": "Let say we want to retrieve the details of the certificate stored in the Root directory in the local machine account then we can use the below command." }, { "code": null, "e": 1929, "s": 1890, "text": "Get-ChildItem Cert:\\LocalMachine\\Root\\" }, { "code": null, "e": 2587, "s": 1929, "text": "PSParentPath: Microsoft.PowerShell.Security\\Certificate::LocalMachine\\Root\nThumbprint Subject\n---------- -------\nCDD4EEAE6000AC7F40C3802C171E30148030C072 CN=Microsoft Root Certificate Authority\nBE36A4562FB2EE05DBB3D32323ADF445084ED656 CN=Thawte Timestamping CA, OU=Thawte Ce\nA43489159A520F0D93D032CCAF37E7FE20A8B419 CN=Microsoft Root Authority, OU=Microso\n92B46C76E13054E104F230517E6E504D43AB10B5 CN=Symantec Enterprise Mobile Root for\n8F43288AD272F3103B6FB1428485EA3014C0BCFE CN=Microsoft Root Certificate Authority\n7F88CD7223F3C813818C994614A89C99FA3B5247 CN=Microsoft Authenticode(tm) Root Auth" }, { "code": null, "e": 2626, "s": 2587, "text": "Or you can also use the below command," }, { "code": null, "e": 2676, "s": 2626, "text": "Get-Item Cert:\\LocalMachine\\Root\\* | ft -AutoSize" }, { "code": null, "e": 2735, "s": 2676, "text": "The below command will get all the Microsoft certificates." }, { "code": null, "e": 2814, "s": 2735, "text": "Get-ChildItem Cert:\\LocalMachine\\Root\\ | where{$_.Subject -like \"*Microsoft*\"}" }, { "code": null, "e": 2964, "s": 2814, "text": "To find the specific certificate, you should know the certificate friendly name. For example, to find the “DigiCert” certificate from the Root store," }, { "code": null, "e": 3043, "s": 2964, "text": "Get-ChildItem Cert:\\LocalMachine\\Root\\ | where{$_.FriendlyName -eq 'DigiCert'}" }, { "code": null, "e": 3328, "s": 3043, "text": "Thumbprint Subject\n---------- -------\nA8985D3A65E5E5C4B2D7D66D40C6DD2FB19C5436 CN=DigiCert Global Root CA, OU=www.digicert.com,\n0563B8630D62D75ABBC8AB1E4BDFB5A899B24D43 CN=DigiCert Assured ID Root CA, OU=www.digicert.com" }, { "code": null, "e": 3423, "s": 3328, "text": "To search directly from the LocalComputer, CurrentUser, or Root store, use -Recurse parameter." }, { "code": null, "e": 3506, "s": 3423, "text": "Get-ChildItem Cert:\\LocalMachine\\ -Recurse | where{$_.FriendlyName -eq 'DigiCert'}" }, { "code": null, "e": 3626, "s": 3506, "text": "Once you get the thumbprint or friendly Name, you can use the fl * pipeline to get the full details of the certificate." }, { "code": null, "e": 3711, "s": 3626, "text": "Get-ChildItem Cert:\\LocalMachine\\root | where{$_.FriendlyName -eq 'DigiCert'} | fl *" }, { "code": null, "e": 3831, "s": 3711, "text": "For the remote servers, we can use Invoke-Command, the below example will get the certificates from the remote servers." }, { "code": null, "e": 3978, "s": 3831, "text": "Invoke-Command -ComputerName Test1Comp, Test2Comp -Scriptblock{\n Get-ChildItem Cert:\\LocalMachine\\root | where{$_.FriendlyName -eq 'DigiCert'}\n}" } ]
Why You Need to Close the Java Streams in Finally Block? - GeeksforGeeks
27 Oct, 2021 In Java finally block is a block used to execute important and common code. The finally block is mostly used during exception handling with try and catch to close streams and files. The code in finally block is executed irrespective of whether there is an exception or not. This ensures that all the opened files are properly closed and all the running threads are properly terminated. So, the data in the files will not be corrupted and the user is on the safe-side. Finally block is executed after try and catch block. The flow of the code is: try catch finally Below mentioned are two examples of when exception is caused and when it is not caused. We will observe that finally block is executed in both our codes. Example 1: With exception in code Java // Java program to show the execution of the code// when exception is caused import java.io.*; class GFG { public static void main(String[] args) { try { // open files System.out.println("Open files"); // do some processing int a = 45; int b = 0; // dividing by 0 to get an exception int div = a / b; System.out.println("After dividing a and b ans is " + div); } catch (ArithmeticException ae) { System.out.println("exception caught"); // display exception details System.out.println(ae); } finally { System.out.println("Inside finally block"); // close the files irrespective of any exception System.out.println("Close files"); } }} Open files exception caught java.lang.ArithmeticException: / by zero Inside finally block Close files Example 2: Without exception Java // Java program to show the execution of the code// when exception is not caused import java.io.*; class GFG { public static void main(String[] args) { try { // open files System.out.println("Open files"); // do some processing int a = 45; int b = 5; int div = a / b; System.out.println("After dividing a and b ans is " + div); } catch (ArithmeticException ae) { System.out.println("exception caught"); // display exception details System.out.println(ae); } finally { System.out.println("Inside finally block"); // close the files irrespective of any exception System.out.println("Close files"); } }} Open files After dividing a and b ans is 9 Inside finally block Close files saurabh1990aror java-stream Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Different ways of Reading a text file in Java Constructors in Java Stream In Java Exceptions in Java StringBuilder Class in Java with Examples Comparator Interface in Java with Examples Generics in Java Functional Interfaces in Java Java Programming Examples HashMap get() Method in Java
[ { "code": null, "e": 23868, "s": 23840, "text": "\n27 Oct, 2021" }, { "code": null, "e": 24336, "s": 23868, "text": "In Java finally block is a block used to execute important and common code. The finally block is mostly used during exception handling with try and catch to close streams and files. The code in finally block is executed irrespective of whether there is an exception or not. This ensures that all the opened files are properly closed and all the running threads are properly terminated. So, the data in the files will not be corrupted and the user is on the safe-side." }, { "code": null, "e": 24414, "s": 24336, "text": "Finally block is executed after try and catch block. The flow of the code is:" }, { "code": null, "e": 24418, "s": 24414, "text": "try" }, { "code": null, "e": 24424, "s": 24418, "text": "catch" }, { "code": null, "e": 24432, "s": 24424, "text": "finally" }, { "code": null, "e": 24520, "s": 24432, "text": "Below mentioned are two examples of when exception is caused and when it is not caused." }, { "code": null, "e": 24586, "s": 24520, "text": "We will observe that finally block is executed in both our codes." }, { "code": null, "e": 24620, "s": 24586, "text": "Example 1: With exception in code" }, { "code": null, "e": 24625, "s": 24620, "text": "Java" }, { "code": "// Java program to show the execution of the code// when exception is caused import java.io.*; class GFG { public static void main(String[] args) { try { // open files System.out.println(\"Open files\"); // do some processing int a = 45; int b = 0; // dividing by 0 to get an exception int div = a / b; System.out.println(\"After dividing a and b ans is \" + div); } catch (ArithmeticException ae) { System.out.println(\"exception caught\"); // display exception details System.out.println(ae); } finally { System.out.println(\"Inside finally block\"); // close the files irrespective of any exception System.out.println(\"Close files\"); } }}", "e": 25512, "s": 24625, "text": null }, { "code": null, "e": 25617, "s": 25515, "text": "Open files\nexception caught\njava.lang.ArithmeticException: / by zero\nInside finally block\nClose files" }, { "code": null, "e": 25648, "s": 25619, "text": "Example 2: Without exception" }, { "code": null, "e": 25655, "s": 25650, "text": "Java" }, { "code": "// Java program to show the execution of the code// when exception is not caused import java.io.*; class GFG { public static void main(String[] args) { try { // open files System.out.println(\"Open files\"); // do some processing int a = 45; int b = 5; int div = a / b; System.out.println(\"After dividing a and b ans is \" + div); } catch (ArithmeticException ae) { System.out.println(\"exception caught\"); // display exception details System.out.println(ae); } finally { System.out.println(\"Inside finally block\"); // close the files irrespective of any exception System.out.println(\"Close files\"); } }}", "e": 26509, "s": 25655, "text": null }, { "code": null, "e": 26588, "s": 26512, "text": "Open files\nAfter dividing a and b ans is 9\nInside finally block\nClose files" }, { "code": null, "e": 26606, "s": 26590, "text": "saurabh1990aror" }, { "code": null, "e": 26618, "s": 26606, "text": "java-stream" }, { "code": null, "e": 26625, "s": 26618, "text": "Picked" }, { "code": null, "e": 26630, "s": 26625, "text": "Java" }, { "code": null, "e": 26635, "s": 26630, "text": "Java" }, { "code": null, "e": 26733, "s": 26635, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26742, "s": 26733, "text": "Comments" }, { "code": null, "e": 26755, "s": 26742, "text": "Old Comments" }, { "code": null, "e": 26801, "s": 26755, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26822, "s": 26801, "text": "Constructors in Java" }, { "code": null, "e": 26837, "s": 26822, "text": "Stream In Java" }, { "code": null, "e": 26856, "s": 26837, "text": "Exceptions in Java" }, { "code": null, "e": 26898, "s": 26856, "text": "StringBuilder Class in Java with Examples" }, { "code": null, "e": 26941, "s": 26898, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 26958, "s": 26941, "text": "Generics in Java" }, { "code": null, "e": 26988, "s": 26958, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27014, "s": 26988, "text": "Java Programming Examples" } ]
Zone-based firewall Configuration
10 Jun, 2022 Prerequisite – Zone-based firewall Zone-based firewall is an advanced method of stateful firewall. In stateful firewall, an entry containing source IP address, destination IP address, source Port number and destination Port number, is maintained for the traffic generated by the trusted (private) network in the stateful database. This will only the traffic including the replies for the private (trusted) network using the stateful database. Zone-based Firewall procedure: Create zones and assign an interface to it – In Zone-based firewall, logical zones are created. A zone is assigned to an interface. By default, traffic from one zone to another is not allowed.Create class-map – After creating a zone, a class-map policy is made which will identify the type of traffic, like ICMP, on which the policies will be applied.Create policy-map and assign class-map to the policy-map – After identifying the type of traffic in class-map, we have to define what action must be taken on the traffic. The action can be:Inspect: It is same as inspection of CBAC i.e only that traffic will be allowed from the outside network which will be inspected (return traffic of inside (trusted) network.Drop: This is the default action for all traffic. The class-map configured in a policy map can be configured to drop unwanted traffic.Pass: This will allow the traffic from one zone to another. Unlike inspect action, it will not create a session state for a traffic. If we want to allow traffic from the opposite direction, corresponding policy should be created.Configure a zone-pair and assign the policy – A zone-pair is configured for one direction only. Policies are defined in which traffic is identified (what type of traffic) then what action should be taken (Inspect Denied, permit). Then we have to apply this policies to a zone-pair. Create zones and assign an interface to it – In Zone-based firewall, logical zones are created. A zone is assigned to an interface. By default, traffic from one zone to another is not allowed. Create class-map – After creating a zone, a class-map policy is made which will identify the type of traffic, like ICMP, on which the policies will be applied. Create policy-map and assign class-map to the policy-map – After identifying the type of traffic in class-map, we have to define what action must be taken on the traffic. The action can be:Inspect: It is same as inspection of CBAC i.e only that traffic will be allowed from the outside network which will be inspected (return traffic of inside (trusted) network.Drop: This is the default action for all traffic. The class-map configured in a policy map can be configured to drop unwanted traffic.Pass: This will allow the traffic from one zone to another. Unlike inspect action, it will not create a session state for a traffic. If we want to allow traffic from the opposite direction, corresponding policy should be created. Inspect: It is same as inspection of CBAC i.e only that traffic will be allowed from the outside network which will be inspected (return traffic of inside (trusted) network. Drop: This is the default action for all traffic. The class-map configured in a policy map can be configured to drop unwanted traffic. Pass: This will allow the traffic from one zone to another. Unlike inspect action, it will not create a session state for a traffic. If we want to allow traffic from the opposite direction, corresponding policy should be created. Configure a zone-pair and assign the policy – A zone-pair is configured for one direction only. Policies are defined in which traffic is identified (what type of traffic) then what action should be taken (Inspect Denied, permit). Then we have to apply this policies to a zone-pair. Configuration: As shown in the figure, 4 routers are connected with each other namely Router1 having ip address 10.1.1.1/24 on its fa0/0 interface, Router2 having IP address 10.1.1.2/24 on its fa0/0 10.1.2.1/24 on its fa0/1 interface and 10.1.3.1/24 on its fa1/0 interface, Router3 having IP address 10.1.2.2/24 on its fa0/1 interface and Router4 has 10.1.3.2/24 on its fa0/1 interface. First we have to perform routing so that the routers are reachable to each other. Configuring RIP on Router2: Router2(config)#router rip Router2(config-router)#network 10.1.1.0 Router2(config-router)#network 10.1.2.0 Router2(config-router)#network 10.1.3.0 Router2(config-router)#no auto-summary Now, giving default route on Router1: Router1(config)#ip route 0.0.0.0 0.0.0.0 10.1.1.2 Giving default route on Router2 Router3(config)#ip route 0.0.0.0 0.0.0.0 10.1.2.1 Giving default route on Router4 Router4(config)#ip route 0.0.0.0 0.0.0.0 10.1.3.1 Now, we have to redistribute default routes in RIP: Router2(config)#router rip Router2(config-router)#default-information originate These routers will be able to ping each other. Now, configure Zone-based firewall. In this scenario, we will allow only ICMP traffic and telnet traffic from inside zone to outside zone. To achieve this task, following steps will be taken: Create zones and assign interfaces to zone – First, we have to configure a name for zone and then apply it to the interface (here, Router2). Configuring the zones and name them as inside, outside and dmz. Router2(config)#zone security inside Router2(config-sec-zone)#exit Router2(config)#zone security outside Router2(config-sec-zone)#exit Router2(config)#zone security dmz Router2(config-sec-zone)#exit Now, applying zones to the interfaces. Router2(config)#interface fa0/0 Router2(config-if)#zone-member security inside Router2(config)#interface fa0/1 Router2(config-if)#zone-member security outside Router2(config)#interface fa1/0 Router2(config-if)#zone-member security dmz After applying zones to the interface, the routers will not be able to ping each other as by default, traffic from one zone to another will be drop (as per default policy). Create a class-map – Class-map will be created to identify the type of traffic in which we want to perform the operation. Configuring class-map stating the type of traffic on which inspection will be performed. Router2(config)#class-map type inspect match-any in-out Router2(config-cmap)#match protocol icmp Router2(config-cmap)#match protocol telnet match-any means any of the statement matches in the class-map i.e either for telnet or ICMP. We have given name in-out to the class-map. Create policy-map and apply class-map to the policy-map – Policy-map will be configured to mention what operation (inspect, drop or pass) will be performed. In our scenario, we will use inspect i.e only that traffic will enter from outside to inside zone if it has an entry in stateful database (replies of traffic initiated in inside zone). Router2(config)#policy-map type inspect in-out Router2(config-pmap)#class in-out Router2(config-pmap-c)#inspect Here, we have configured a policy-map named input an assign class-map (named in-out) to it and action that will be taken is inspect. Here, we have taken same name of class-map and policy-map. Different names can be taken but then it will be complicated. Create zone-pair and apply policy-map to the zone-pair – Create zone pair specifying the source and the destination zone and apply the policy-map to the zone-pair. Router2(config)#zone-pair security in-outpair source inside destination outside Router2(config-sec-zone-pair)#service-policy type inspect in-out Here, in the first command, notice that in-outpair is the name for zone-pair in which inside zone will be the source and outside zone will be the destination. It means a zone-pair has been defined in direction from inside zone to outside zone. In the second command, in-out is the name of policy-map. Now, the inside zone will be to ping and telnet the outside zone devices but for vice-versa we have to define separate zone-pair. Also, note that inside zone devices will be able to reach outside zone devices but not DMZ zone because no zone-pair has been defined for it. simmytarika5 Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jun, 2022" }, { "code": null, "e": 502, "s": 28, "text": "Prerequisite – Zone-based firewall Zone-based firewall is an advanced method of stateful firewall. In stateful firewall, an entry containing source IP address, destination IP address, source Port number and destination Port number, is maintained for the traffic generated by the trusted (private) network in the stateful database. This will only the traffic including the replies for the private (trusted) network using the stateful database. Zone-based Firewall procedure:" }, { "code": null, "e": 1860, "s": 502, "text": "Create zones and assign an interface to it – In Zone-based firewall, logical zones are created. A zone is assigned to an interface. By default, traffic from one zone to another is not allowed.Create class-map – After creating a zone, a class-map policy is made which will identify the type of traffic, like ICMP, on which the policies will be applied.Create policy-map and assign class-map to the policy-map – After identifying the type of traffic in class-map, we have to define what action must be taken on the traffic. The action can be:Inspect: It is same as inspection of CBAC i.e only that traffic will be allowed from the outside network which will be inspected (return traffic of inside (trusted) network.Drop: This is the default action for all traffic. The class-map configured in a policy map can be configured to drop unwanted traffic.Pass: This will allow the traffic from one zone to another. Unlike inspect action, it will not create a session state for a traffic. If we want to allow traffic from the opposite direction, corresponding policy should be created.Configure a zone-pair and assign the policy – A zone-pair is configured for one direction only. Policies are defined in which traffic is identified (what type of traffic) then what action should be taken (Inspect Denied, permit). Then we have to apply this policies to a zone-pair." }, { "code": null, "e": 2053, "s": 1860, "text": "Create zones and assign an interface to it – In Zone-based firewall, logical zones are created. A zone is assigned to an interface. By default, traffic from one zone to another is not allowed." }, { "code": null, "e": 2213, "s": 2053, "text": "Create class-map – After creating a zone, a class-map policy is made which will identify the type of traffic, like ICMP, on which the policies will be applied." }, { "code": null, "e": 2939, "s": 2213, "text": "Create policy-map and assign class-map to the policy-map – After identifying the type of traffic in class-map, we have to define what action must be taken on the traffic. The action can be:Inspect: It is same as inspection of CBAC i.e only that traffic will be allowed from the outside network which will be inspected (return traffic of inside (trusted) network.Drop: This is the default action for all traffic. The class-map configured in a policy map can be configured to drop unwanted traffic.Pass: This will allow the traffic from one zone to another. Unlike inspect action, it will not create a session state for a traffic. If we want to allow traffic from the opposite direction, corresponding policy should be created." }, { "code": null, "e": 3113, "s": 2939, "text": "Inspect: It is same as inspection of CBAC i.e only that traffic will be allowed from the outside network which will be inspected (return traffic of inside (trusted) network." }, { "code": null, "e": 3248, "s": 3113, "text": "Drop: This is the default action for all traffic. The class-map configured in a policy map can be configured to drop unwanted traffic." }, { "code": null, "e": 3478, "s": 3248, "text": "Pass: This will allow the traffic from one zone to another. Unlike inspect action, it will not create a session state for a traffic. If we want to allow traffic from the opposite direction, corresponding policy should be created." }, { "code": null, "e": 3760, "s": 3478, "text": "Configure a zone-pair and assign the policy – A zone-pair is configured for one direction only. Policies are defined in which traffic is identified (what type of traffic) then what action should be taken (Inspect Denied, permit). Then we have to apply this policies to a zone-pair." }, { "code": null, "e": 4258, "s": 3760, "text": "Configuration: As shown in the figure, 4 routers are connected with each other namely Router1 having ip address 10.1.1.1/24 on its fa0/0 interface, Router2 having IP address 10.1.1.2/24 on its fa0/0 10.1.2.1/24 on its fa0/1 interface and 10.1.3.1/24 on its fa1/0 interface, Router3 having IP address 10.1.2.2/24 on its fa0/1 interface and Router4 has 10.1.3.2/24 on its fa0/1 interface. First we have to perform routing so that the routers are reachable to each other. Configuring RIP on Router2:" }, { "code": null, "e": 4444, "s": 4258, "text": "Router2(config)#router rip\nRouter2(config-router)#network 10.1.1.0\nRouter2(config-router)#network 10.1.2.0\nRouter2(config-router)#network 10.1.3.0\nRouter2(config-router)#no auto-summary" }, { "code": null, "e": 4482, "s": 4444, "text": "Now, giving default route on Router1:" }, { "code": null, "e": 4533, "s": 4482, "text": "Router1(config)#ip route 0.0.0.0 0.0.0.0 10.1.1.2 " }, { "code": null, "e": 4565, "s": 4533, "text": "Giving default route on Router2" }, { "code": null, "e": 4615, "s": 4565, "text": "Router3(config)#ip route 0.0.0.0 0.0.0.0 10.1.2.1" }, { "code": null, "e": 4647, "s": 4615, "text": "Giving default route on Router4" }, { "code": null, "e": 4697, "s": 4647, "text": "Router4(config)#ip route 0.0.0.0 0.0.0.0 10.1.3.1" }, { "code": null, "e": 4749, "s": 4697, "text": "Now, we have to redistribute default routes in RIP:" }, { "code": null, "e": 4830, "s": 4749, "text": "Router2(config)#router rip\nRouter2(config-router)#default-information originate " }, { "code": null, "e": 5069, "s": 4830, "text": "These routers will be able to ping each other. Now, configure Zone-based firewall. In this scenario, we will allow only ICMP traffic and telnet traffic from inside zone to outside zone. To achieve this task, following steps will be taken:" }, { "code": null, "e": 5274, "s": 5069, "text": "Create zones and assign interfaces to zone – First, we have to configure a name for zone and then apply it to the interface (here, Router2). Configuring the zones and name them as inside, outside and dmz." }, { "code": null, "e": 5476, "s": 5274, "text": "Router2(config)#zone security inside\nRouter2(config-sec-zone)#exit \nRouter2(config)#zone security outside \nRouter2(config-sec-zone)#exit\nRouter2(config)#zone security dmz \nRouter2(config-sec-zone)#exit" }, { "code": null, "e": 5515, "s": 5476, "text": "Now, applying zones to the interfaces." }, { "code": null, "e": 5750, "s": 5515, "text": "Router2(config)#interface fa0/0\nRouter2(config-if)#zone-member security inside\nRouter2(config)#interface fa0/1\nRouter2(config-if)#zone-member security outside\nRouter2(config)#interface fa1/0\nRouter2(config-if)#zone-member security dmz" }, { "code": null, "e": 5923, "s": 5750, "text": "After applying zones to the interface, the routers will not be able to ping each other as by default, traffic from one zone to another will be drop (as per default policy)." }, { "code": null, "e": 6134, "s": 5923, "text": "Create a class-map – Class-map will be created to identify the type of traffic in which we want to perform the operation. Configuring class-map stating the type of traffic on which inspection will be performed." }, { "code": null, "e": 6274, "s": 6134, "text": "Router2(config)#class-map type inspect match-any in-out\nRouter2(config-cmap)#match protocol icmp\nRouter2(config-cmap)#match protocol telnet" }, { "code": null, "e": 6411, "s": 6274, "text": "match-any means any of the statement matches in the class-map i.e either for telnet or ICMP. We have given name in-out to the class-map." }, { "code": null, "e": 6753, "s": 6411, "text": "Create policy-map and apply class-map to the policy-map – Policy-map will be configured to mention what operation (inspect, drop or pass) will be performed. In our scenario, we will use inspect i.e only that traffic will enter from outside to inside zone if it has an entry in stateful database (replies of traffic initiated in inside zone)." }, { "code": null, "e": 6865, "s": 6753, "text": "Router2(config)#policy-map type inspect in-out\nRouter2(config-pmap)#class in-out\nRouter2(config-pmap-c)#inspect" }, { "code": null, "e": 7119, "s": 6865, "text": "Here, we have configured a policy-map named input an assign class-map (named in-out) to it and action that will be taken is inspect. Here, we have taken same name of class-map and policy-map. Different names can be taken but then it will be complicated." }, { "code": null, "e": 7283, "s": 7119, "text": "Create zone-pair and apply policy-map to the zone-pair – Create zone pair specifying the source and the destination zone and apply the policy-map to the zone-pair." }, { "code": null, "e": 7428, "s": 7283, "text": "Router2(config)#zone-pair security in-outpair source inside destination outside\nRouter2(config-sec-zone-pair)#service-policy type inspect in-out" }, { "code": null, "e": 8002, "s": 7428, "text": "Here, in the first command, notice that in-outpair is the name for zone-pair in which inside zone will be the source and outside zone will be the destination. It means a zone-pair has been defined in direction from inside zone to outside zone. In the second command, in-out is the name of policy-map. Now, the inside zone will be to ping and telnet the outside zone devices but for vice-versa we have to define separate zone-pair. Also, note that inside zone devices will be able to reach outside zone devices but not DMZ zone because no zone-pair has been defined for it." }, { "code": null, "e": 8015, "s": 8002, "text": "simmytarika5" }, { "code": null, "e": 8033, "s": 8015, "text": "Computer Networks" }, { "code": null, "e": 8051, "s": 8033, "text": "Computer Networks" } ]
Perl – Difference between Functions and Subroutines
28 Jul, 2020 In Perl, when a code-script gets bigger in size i.e. contains hundreds of lines of code, it becomes difficult to manage such a code-script. To avoid this difficulty, Perl provides its users with the concept of Functions and subroutines. Functions and subroutines break up complex/large amounts of code into smaller more concise parts to make the program more readable. They reduce the size of the application and debugging time by allowing us to reuse the code that has been written in the program earlier. Perl functions and subroutines are used to reuse code in a program. We can use a function at several places in our application with different parameters. A function is something which takes up a number of arguments, does something with them and then returns a value. It can either be built into the programming language or it can be provided by the user. In Perl, when we define a function, we specify the name and the sequence of statements. Later, when we want to perform a computation, we can ‘call’ the function by name which will run the sequence of statements contained in the function definition.There are many built-in functions in Perl which are quite handy too. For example, ‘say’ is a built-in function. Perl even allows us to build up our own function which can help us to perform the task that we want to do. Subroutines (or sub) give us the ability to give a name to the section of the code so that when we want to use it again in the program, we can use it by just calling its name. Subroutines help us do programming in Perl in two major ways: First, they let us reuse the code again in the program which makes it easier to find and fix bugs, making it faster to write programs. Second, they allow us to chunk our code into organizational sections. Each subroutine is responsible for a specific task. In Perl, there are two cases when a piece of code is put into the subroutine: When we know that the code would be used for calculation or action that’s going to happen more than once. For example, while putting a strong into a specific format or while turning an incoming data record into a hash, etc. When there are logical units of our program that we want to break into pieces making our program easier to understand. Below is a table of differences between a Function and a Subroutine: The basic format of a function is : $myvalue = myfunction(parameter, parameter); The basic format of subroutine is : sub subroutine_name { # body of subroutine } A Sample program for reversing a string using a Function and a Subroutine: Function Subroutine #!/usr/bin/perl# Perl program to reverse a string# using pre-defined function # Creating a string$string = "GeeksForGeeks"; print "Original string: $string", "\n";print "Reversed string: "; # Calling pre-defined functionprint scalar reverse("$string"), "\n"; #!/usr/bin/perl# Perl program to reverse a string# using a subroutine # Creating a stringmy $string = 'GeeksforGeeks'; print 'Original string: ', $string, "\n";print 'Reversed using Subroutine: ', reverse_in_place($string), "\n"; # Creating a subroutinesub reverse_in_place{ my ($string) = @_; my @array = split //, $string; my $n = scalar @array; for (0 .. $n / 2 - 1) { my $tmp = $array[$_]; $array[$_] = $array[$n - $_ - 1]; $array[$n - $_ - 1] = $tmp; } return join('', @array);} Original string: GeeksforGeeks Reversed using Subroutine: skeeGrofskeeG perl-basics Perl-function Picked Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jul, 2020" }, { "code": null, "e": 423, "s": 54, "text": "In Perl, when a code-script gets bigger in size i.e. contains hundreds of lines of code, it becomes difficult to manage such a code-script. To avoid this difficulty, Perl provides its users with the concept of Functions and subroutines. Functions and subroutines break up complex/large amounts of code into smaller more concise parts to make the program more readable." }, { "code": null, "e": 715, "s": 423, "text": "They reduce the size of the application and debugging time by allowing us to reuse the code that has been written in the program earlier. Perl functions and subroutines are used to reuse code in a program. We can use a function at several places in our application with different parameters." }, { "code": null, "e": 916, "s": 715, "text": "A function is something which takes up a number of arguments, does something with them and then returns a value. It can either be built into the programming language or it can be provided by the user." }, { "code": null, "e": 1383, "s": 916, "text": "In Perl, when we define a function, we specify the name and the sequence of statements. Later, when we want to perform a computation, we can ‘call’ the function by name which will run the sequence of statements contained in the function definition.There are many built-in functions in Perl which are quite handy too. For example, ‘say’ is a built-in function. Perl even allows us to build up our own function which can help us to perform the task that we want to do." }, { "code": null, "e": 1559, "s": 1383, "text": "Subroutines (or sub) give us the ability to give a name to the section of the code so that when we want to use it again in the program, we can use it by just calling its name." }, { "code": null, "e": 1621, "s": 1559, "text": "Subroutines help us do programming in Perl in two major ways:" }, { "code": null, "e": 1756, "s": 1621, "text": "First, they let us reuse the code again in the program which makes it easier to find and fix bugs, making it faster to write programs." }, { "code": null, "e": 1878, "s": 1756, "text": "Second, they allow us to chunk our code into organizational sections. Each subroutine is responsible for a specific task." }, { "code": null, "e": 1956, "s": 1878, "text": "In Perl, there are two cases when a piece of code is put into the subroutine:" }, { "code": null, "e": 2180, "s": 1956, "text": "When we know that the code would be used for calculation or action that’s going to happen more than once. For example, while putting a strong into a specific format or while turning an incoming data record into a hash, etc." }, { "code": null, "e": 2299, "s": 2180, "text": "When there are logical units of our program that we want to break into pieces making our program easier to understand." }, { "code": null, "e": 2368, "s": 2299, "text": "Below is a table of differences between a Function and a Subroutine:" }, { "code": null, "e": 2404, "s": 2368, "text": "The basic format of a function is :" }, { "code": null, "e": 2449, "s": 2404, "text": "$myvalue = myfunction(parameter, parameter);" }, { "code": null, "e": 2485, "s": 2449, "text": "The basic format of subroutine is :" }, { "code": null, "e": 2505, "s": 2485, "text": "sub subroutine_name" }, { "code": null, "e": 2507, "s": 2505, "text": "{" }, { "code": null, "e": 2531, "s": 2507, "text": " # body of subroutine" }, { "code": null, "e": 2533, "s": 2531, "text": "}" }, { "code": null, "e": 2608, "s": 2533, "text": "A Sample program for reversing a string using a Function and a Subroutine:" }, { "code": null, "e": 2617, "s": 2608, "text": "Function" }, { "code": null, "e": 2628, "s": 2617, "text": "Subroutine" }, { "code": "#!/usr/bin/perl# Perl program to reverse a string# using pre-defined function # Creating a string$string = \"GeeksForGeeks\"; print \"Original string: $string\", \"\\n\";print \"Reversed string: \"; # Calling pre-defined functionprint scalar reverse(\"$string\"), \"\\n\";", "e": 2890, "s": 2628, "text": null }, { "code": "#!/usr/bin/perl# Perl program to reverse a string# using a subroutine # Creating a stringmy $string = 'GeeksforGeeks'; print 'Original string: ', $string, \"\\n\";print 'Reversed using Subroutine: ', reverse_in_place($string), \"\\n\"; # Creating a subroutinesub reverse_in_place{ my ($string) = @_; my @array = split //, $string; my $n = scalar @array; for (0 .. $n / 2 - 1) { my $tmp = $array[$_]; $array[$_] = $array[$n - $_ - 1]; $array[$n - $_ - 1] = $tmp; } return join('', @array);}", "e": 3428, "s": 2890, "text": null }, { "code": null, "e": 3502, "s": 3428, "text": "Original string: GeeksforGeeks\nReversed using Subroutine: skeeGrofskeeG\n" }, { "code": null, "e": 3514, "s": 3502, "text": "perl-basics" }, { "code": null, "e": 3528, "s": 3514, "text": "Perl-function" }, { "code": null, "e": 3535, "s": 3528, "text": "Picked" }, { "code": null, "e": 3540, "s": 3535, "text": "Perl" }, { "code": null, "e": 3545, "s": 3540, "text": "Perl" } ]
Python time.daylight() Function
19 Dec, 2021 Time.daylight() function which returns a non zero integer value when Daylight Saving Time (DST) is defined, else it returns 0. Daylight Saving Time, in short, is called DST which is a best practice of setting a clock time one hour forward from standard time during months of summer and back again in fall. This will be done to make better use of sunlight. Syntax: time.daylight Parameters: This function doesn’t require any parameters. Example 1: Here, the daylight function returns 0 indicates that Daylight Saving Time (DST) is not defined. Python3 # import necessary packagesimport time # use daylight functionprint(time.daylight) Output: 0 Instead of time.daylight function, we can also check whether the Daylight Saving Time (DST) is defined or not using localtime method. It returns the present Date, Time along with whether a Daylight Saving Time (DST) is set or not. If set, in the returned result it will be displayed as tm_isdst=1 else 0. Example 2: At last in the first line of output tm_isdst=0 specifies that DST is not set. So in confirmation time.daylight also returns 0 that DST is not defined. Python3 # import necessary packagesimport time # use localtime methodprint(time.localtime()) # use daylight functionprint(time.daylight) Output: time.struct_time(tm_year=2021, tm_mon=12, tm_mday=6, tm_hour=9, tm_min=0, tm_sec=43, tm_wday=0, tm_yday=340, tm_isdst=0) 0 Example 3: Here, we are going to check whether the DST is defined or not. Python3 # import necessary packagesimport time # if DST definedif(time.daylight): print('DST defined')else: print('DST not defined') Output: DST not defined Picked Python time-module 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": "\n19 Dec, 2021" }, { "code": null, "e": 384, "s": 28, "text": "Time.daylight() function which returns a non zero integer value when Daylight Saving Time (DST) is defined, else it returns 0. Daylight Saving Time, in short, is called DST which is a best practice of setting a clock time one hour forward from standard time during months of summer and back again in fall. This will be done to make better use of sunlight." }, { "code": null, "e": 392, "s": 384, "text": "Syntax:" }, { "code": null, "e": 406, "s": 392, "text": "time.daylight" }, { "code": null, "e": 418, "s": 406, "text": "Parameters:" }, { "code": null, "e": 464, "s": 418, "text": "This function doesn’t require any parameters." }, { "code": null, "e": 475, "s": 464, "text": "Example 1:" }, { "code": null, "e": 571, "s": 475, "text": "Here, the daylight function returns 0 indicates that Daylight Saving Time (DST) is not defined." }, { "code": null, "e": 579, "s": 571, "text": "Python3" }, { "code": "# import necessary packagesimport time # use daylight functionprint(time.daylight)", "e": 663, "s": 579, "text": null }, { "code": null, "e": 671, "s": 663, "text": "Output:" }, { "code": null, "e": 673, "s": 671, "text": "0" }, { "code": null, "e": 807, "s": 673, "text": "Instead of time.daylight function, we can also check whether the Daylight Saving Time (DST) is defined or not using localtime method." }, { "code": null, "e": 979, "s": 807, "text": "It returns the present Date, Time along with whether a Daylight Saving Time (DST) is set or not. If set, in the returned result it will be displayed as tm_isdst=1 else 0. " }, { "code": null, "e": 990, "s": 979, "text": "Example 2:" }, { "code": null, "e": 1141, "s": 990, "text": "At last in the first line of output tm_isdst=0 specifies that DST is not set. So in confirmation time.daylight also returns 0 that DST is not defined." }, { "code": null, "e": 1149, "s": 1141, "text": "Python3" }, { "code": "# import necessary packagesimport time # use localtime methodprint(time.localtime()) # use daylight functionprint(time.daylight)", "e": 1280, "s": 1149, "text": null }, { "code": null, "e": 1288, "s": 1280, "text": "Output:" }, { "code": null, "e": 1409, "s": 1288, "text": "time.struct_time(tm_year=2021, tm_mon=12, tm_mday=6, tm_hour=9, tm_min=0, tm_sec=43, tm_wday=0, tm_yday=340, tm_isdst=0)" }, { "code": null, "e": 1411, "s": 1409, "text": "0" }, { "code": null, "e": 1422, "s": 1411, "text": "Example 3:" }, { "code": null, "e": 1485, "s": 1422, "text": "Here, we are going to check whether the DST is defined or not." }, { "code": null, "e": 1493, "s": 1485, "text": "Python3" }, { "code": "# import necessary packagesimport time # if DST definedif(time.daylight): print('DST defined')else: print('DST not defined')", "e": 1625, "s": 1493, "text": null }, { "code": null, "e": 1633, "s": 1625, "text": "Output:" }, { "code": null, "e": 1649, "s": 1633, "text": "DST not defined" }, { "code": null, "e": 1656, "s": 1649, "text": "Picked" }, { "code": null, "e": 1675, "s": 1656, "text": "Python time-module" }, { "code": null, "e": 1682, "s": 1675, "text": "Python" }, { "code": null, "e": 1780, "s": 1682, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1812, "s": 1780, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1839, "s": 1812, "text": "Python Classes and Objects" }, { "code": null, "e": 1860, "s": 1839, "text": "Python OOPs Concepts" }, { "code": null, "e": 1883, "s": 1860, "text": "Introduction To PYTHON" }, { "code": null, "e": 1939, "s": 1883, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1970, "s": 1939, "text": "Python | os.path.join() method" }, { "code": null, "e": 2012, "s": 1970, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2054, "s": 2012, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2093, "s": 2054, "text": "Python | datetime.timedelta() function" } ]
Creating Phishing page of a website
13 Aug, 2020 Prerequisite – Phishing Phishing is a type of social engineering attack of tricking an individual to enter the sensitive information like usernames, passwords and credit card details. It can be done by any individual with a mere basic requirement of Kali Linux (or any other Linux Distribution). Steps to create a phishing page : Open Kali Linux terminal and paste the following code :git clone https://github.com/DarkSecDevelopers/HiddenEye.git git clone https://github.com/DarkSecDevelopers/HiddenEye.git Now perform the steps mentioned below : Now you can select the website which you want to clone. You can also add a keylogger or a Cloudflare Protection Page to make your cloned website look more legitimate. Now you have to enter the redirect URL, i.e. the URL which you want the user to be redirected to after performing a successful phishing attack. You also have to select a server of your choice and can make a legitimate-looking phishing URL or you can go with the random URL. You now have to deliver the phishing URL to your user and when he clicks on it and he will get redirected to your cloned website. Once the user enters the details, he will get redirected to our chosen URL and we will be able to phish all the user’s credentials. Preventive Measures : Never open suspicious email attachments. Never click on suspicious email links. Never provide confidential information via email, over phone or text messages. Never post your personal data, like your email address or phone number, publicly on social media. Always check for the authenticity of the URL which the sender wants you to get redirected to. To create a Facebook Phishing Page using PHP, refer. Information-Security Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Aug, 2020" }, { "code": null, "e": 76, "s": 52, "text": "Prerequisite – Phishing" }, { "code": null, "e": 348, "s": 76, "text": "Phishing is a type of social engineering attack of tricking an individual to enter the sensitive information like usernames, passwords and credit card details. It can be done by any individual with a mere basic requirement of Kali Linux (or any other Linux Distribution)." }, { "code": null, "e": 382, "s": 348, "text": "Steps to create a phishing page :" }, { "code": null, "e": 498, "s": 382, "text": "Open Kali Linux terminal and paste the following code :git clone https://github.com/DarkSecDevelopers/HiddenEye.git" }, { "code": null, "e": 559, "s": 498, "text": "git clone https://github.com/DarkSecDevelopers/HiddenEye.git" }, { "code": null, "e": 599, "s": 559, "text": "Now perform the steps mentioned below :" }, { "code": null, "e": 655, "s": 599, "text": "Now you can select the website which you want to clone." }, { "code": null, "e": 766, "s": 655, "text": "You can also add a keylogger or a Cloudflare Protection Page to make your cloned website look more legitimate." }, { "code": null, "e": 1040, "s": 766, "text": "Now you have to enter the redirect URL, i.e. the URL which you want the user to be redirected to after performing a successful phishing attack. You also have to select a server of your choice and can make a legitimate-looking phishing URL or you can go with the random URL." }, { "code": null, "e": 1170, "s": 1040, "text": "You now have to deliver the phishing URL to your user and when he clicks on it and he will get redirected to your cloned website." }, { "code": null, "e": 1302, "s": 1170, "text": "Once the user enters the details, he will get redirected to our chosen URL and we will be able to phish all the user’s credentials." }, { "code": null, "e": 1324, "s": 1302, "text": "Preventive Measures :" }, { "code": null, "e": 1365, "s": 1324, "text": "Never open suspicious email attachments." }, { "code": null, "e": 1404, "s": 1365, "text": "Never click on suspicious email links." }, { "code": null, "e": 1483, "s": 1404, "text": "Never provide confidential information via email, over phone or text messages." }, { "code": null, "e": 1581, "s": 1483, "text": "Never post your personal data, like your email address or phone number, publicly on social media." }, { "code": null, "e": 1675, "s": 1581, "text": "Always check for the authenticity of the URL which the sender wants you to get redirected to." }, { "code": null, "e": 1728, "s": 1675, "text": "To create a Facebook Phishing Page using PHP, refer." }, { "code": null, "e": 1749, "s": 1728, "text": "Information-Security" }, { "code": null, "e": 1767, "s": 1749, "text": "Computer Networks" }, { "code": null, "e": 1785, "s": 1767, "text": "Computer Networks" } ]
Requesting in http vs Requesting in Express.js
09 Feb, 2021 Node.js: Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that Node.js is not a framework and it’s not a programming language. Most of the people are confused and understand it’s a framework or a programming language. We often use Node.js for building back-end services like APIs like Web App or Mobile App. http Module Import http module: Import http module and store returned HTTP instance into a variable. Syntax: var http = require("http"); Creating and Binding Server: Create a server instance using createServer() method and bind it to some port using listen() method. Syntax: const server = http.createServer().listen(port) Parameter: This method (listen()) accepts a single parameter as mentioned above and described below: port <Number>: Ports are in the range 1024 to 65535 containing both registered and Dynamic ports. The below example illustrate the use of http module in Node.js. Example 1: Filename: index.js javascript // Node.js program to create http server // using require to access http module const http = require("http"); // Port numberconst PORT = process.env.PORT || 2020; // Creating serverconst server = http.createServer( // Server listening on port 2020 function (req, res) { res.write('Hello geeksforgeeks!'); // Write a response to the client res.end(); }).listen(PORT, error => { // Prints in console console.log(`Server listening on port ${PORT}`)}); Run index.js file using the following command: node index.js Output: Server listening on port 2020 Express Module In order to use the express module, we need to install the NPM (Node Package Manager) and the following modules (on cmd). // Creates package.json file >> npm init // Installs express module >> npm install express --save // OR >> npm i express -s Import express module: Import express module and store returned instance into a variable. Syntax: var express = require("express"); Creating Server: The above syntax calls the “express()” function and creates a new express application which gets stored inside the app variable. Syntax: const app = express(); // OR var express = require("express")(); Sending and listening to the response: It communicates the request and response with the client and the server. It requires PORT <number> and IP <number> to communicate. app.listen(PORT, IP, Callback); Parameter: This method accepts three parameters as mentioned above and described below: PORT <Number>: Ports are the endpoints of communication which helps to communicate with the client and the server. IP <Number>: IPs represent IPv4 or IPv6 address of a host or a device. Callback <Function>: It accepts a function. The below example illustrates the Express.js module in Node.js. Example 2: Filename: index.js javascript // Node.js program to create server // with help of Express.js module // Importing express const express = require('express'); // Creating new express app const app = express(); // PORT configurationconst PORT = process.env.PORT || 2020; // IP configurationconst IP = process.env.IP || 2021; // Create a route for the appapp.get('/', (req, res) => { res.send('Hello Vikas_g from geeksforgeeks!');}); // Create a route for the appapp.get('*', (req, res) => { res.send('OOPS!! The link is broken...');}); // Server listening to requestsapp.listen(PORT, IP, () => { console.log(`The Server is running at: http://localhost:${PORT}/`);}); Run index.js file using the following command: node index.js Output: The Server is running at: http://localhost:2020 Now type http://127.0.0.1:2020/ OR http://localhost:2020/ in a web browser to see the output. mridulmanochagfg Express.js Node.js-Misc Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Feb, 2021" }, { "code": null, "e": 422, "s": 28, "text": "Node.js: Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that Node.js is not a framework and it’s not a programming language. Most of the people are confused and understand it’s a framework or a programming language. We often use Node.js for building back-end services like APIs like Web App or Mobile App." }, { "code": null, "e": 434, "s": 422, "text": "http Module" }, { "code": null, "e": 523, "s": 434, "text": "Import http module: Import http module and store returned HTTP instance into a variable." }, { "code": null, "e": 531, "s": 523, "text": "Syntax:" }, { "code": null, "e": 559, "s": 531, "text": "var http = require(\"http\");" }, { "code": null, "e": 689, "s": 559, "text": "Creating and Binding Server: Create a server instance using createServer() method and bind it to some port using listen() method." }, { "code": null, "e": 697, "s": 689, "text": "Syntax:" }, { "code": null, "e": 745, "s": 697, "text": "const server = http.createServer().listen(port)" }, { "code": null, "e": 846, "s": 745, "text": "Parameter: This method (listen()) accepts a single parameter as mentioned above and described below:" }, { "code": null, "e": 944, "s": 846, "text": "port <Number>: Ports are in the range 1024 to 65535 containing both registered and Dynamic ports." }, { "code": null, "e": 1008, "s": 944, "text": "The below example illustrate the use of http module in Node.js." }, { "code": null, "e": 1038, "s": 1008, "text": "Example 1: Filename: index.js" }, { "code": null, "e": 1049, "s": 1038, "text": "javascript" }, { "code": "// Node.js program to create http server // using require to access http module const http = require(\"http\"); // Port numberconst PORT = process.env.PORT || 2020; // Creating serverconst server = http.createServer( // Server listening on port 2020 function (req, res) { res.write('Hello geeksforgeeks!'); // Write a response to the client res.end(); }).listen(PORT, error => { // Prints in console console.log(`Server listening on port ${PORT}`)});", "e": 1521, "s": 1049, "text": null }, { "code": null, "e": 1568, "s": 1521, "text": "Run index.js file using the following command:" }, { "code": null, "e": 1582, "s": 1568, "text": "node index.js" }, { "code": null, "e": 1590, "s": 1582, "text": "Output:" }, { "code": null, "e": 1620, "s": 1590, "text": "Server listening on port 2020" }, { "code": null, "e": 1635, "s": 1620, "text": "Express Module" }, { "code": null, "e": 1757, "s": 1635, "text": "In order to use the express module, we need to install the NPM (Node Package Manager) and the following modules (on cmd)." }, { "code": null, "e": 1884, "s": 1757, "text": "// Creates package.json file\n>> npm init \n\n// Installs express module\n>> npm install express --save // OR\n>> npm i express -s " }, { "code": null, "e": 1974, "s": 1884, "text": "Import express module: Import express module and store returned instance into a variable." }, { "code": null, "e": 1982, "s": 1974, "text": "Syntax:" }, { "code": null, "e": 2016, "s": 1982, "text": "var express = require(\"express\");" }, { "code": null, "e": 2162, "s": 2016, "text": "Creating Server: The above syntax calls the “express()” function and creates a new express application which gets stored inside the app variable." }, { "code": null, "e": 2170, "s": 2162, "text": "Syntax:" }, { "code": null, "e": 2237, "s": 2170, "text": "const app = express(); // OR \nvar express = require(\"express\")(); " }, { "code": null, "e": 2409, "s": 2237, "text": "Sending and listening to the response: It communicates the request and response with the client and the server. It requires PORT <number> and IP <number> to communicate. " }, { "code": null, "e": 2441, "s": 2409, "text": "app.listen(PORT, IP, Callback);" }, { "code": null, "e": 2529, "s": 2441, "text": "Parameter: This method accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 2644, "s": 2529, "text": "PORT <Number>: Ports are the endpoints of communication which helps to communicate with the client and the server." }, { "code": null, "e": 2715, "s": 2644, "text": "IP <Number>: IPs represent IPv4 or IPv6 address of a host or a device." }, { "code": null, "e": 2759, "s": 2715, "text": "Callback <Function>: It accepts a function." }, { "code": null, "e": 2823, "s": 2759, "text": "The below example illustrates the Express.js module in Node.js." }, { "code": null, "e": 2853, "s": 2823, "text": "Example 2: Filename: index.js" }, { "code": null, "e": 2864, "s": 2853, "text": "javascript" }, { "code": "// Node.js program to create server // with help of Express.js module // Importing express const express = require('express'); // Creating new express app const app = express(); // PORT configurationconst PORT = process.env.PORT || 2020; // IP configurationconst IP = process.env.IP || 2021; // Create a route for the appapp.get('/', (req, res) => { res.send('Hello Vikas_g from geeksforgeeks!');}); // Create a route for the appapp.get('*', (req, res) => { res.send('OOPS!! The link is broken...');}); // Server listening to requestsapp.listen(PORT, IP, () => { console.log(`The Server is running at: http://localhost:${PORT}/`);});", "e": 3498, "s": 2864, "text": null }, { "code": null, "e": 3545, "s": 3498, "text": "Run index.js file using the following command:" }, { "code": null, "e": 3559, "s": 3545, "text": "node index.js" }, { "code": null, "e": 3567, "s": 3559, "text": "Output:" }, { "code": null, "e": 3615, "s": 3567, "text": "The Server is running at: http://localhost:2020" }, { "code": null, "e": 3709, "s": 3615, "text": "Now type http://127.0.0.1:2020/ OR http://localhost:2020/ in a web browser to see the output." }, { "code": null, "e": 3726, "s": 3709, "text": "mridulmanochagfg" }, { "code": null, "e": 3737, "s": 3726, "text": "Express.js" }, { "code": null, "e": 3750, "s": 3737, "text": "Node.js-Misc" }, { "code": null, "e": 3758, "s": 3750, "text": "Node.js" }, { "code": null, "e": 3775, "s": 3758, "text": "Web Technologies" } ]
Trapping Rain Water | Practice | GeeksforGeeks
Given an array arr[] of N non-negative integers representing the height of blocks. If width of each block is 1, compute how much water can be trapped between the blocks during the rainy season. Example 1: Input: N = 6 arr[] = {3,0,0,2,0,4} Output: 10 Explanation: Example 2: Input: N = 4 arr[] = {7,4,0,9} Output: 10 Explanation: Water trapped by above block of height 4 is 3 units and above block of height 0 is 7 units. So, the total unit of water trapped is 10 units. Example 3: Input: N = 3 arr[] = {6,9,9} Output: 0 Explanation: No water will be trapped. Your Task: You don't need to read input or print anything. The task is to complete the function trappingWater() which takes arr[] and N as input parameters and returns the total amount of water that can be trapped. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 3 < N < 106 0 < Ai < 108 0 dakshbajaj2410in 8 hours Simple C++ Solution public: long long trappingWater(int arr[], int n){ // code here long long water = 0; int left = arr[0]; int right = arr[n-1]; int lIndex = 1; int rIndex = n-2; while(lIndex<=rIndex){ if(left<=right){ if(arr[lIndex]<=left){ water+= left-arr[lIndex]; }else{ left = arr[lIndex]; } lIndex++; }else{ if(arr[rIndex]<=right){ water+= right-arr[rIndex]; }else{ right = arr[rIndex]; } rIndex--; } } return water; } 0 dakshbajaj2410 This comment was deleted. 0 aditya16jain162 hours ago def trappingWater(self, arr,n): max_ele = arr.index(max(arr)) if (max_ele == n - 1): thres = arr[0] water = 0 for i in arr: if (i >= thres): thres = i else: water += thres - i elif (max_ele == 0): arr.reverse() thres = arr[0] water = 0 for i in arr: if (i >= thres): thres = i else: water += thres - i else: water = 0 lst = arr[:max_ele + 1] thres = lst[0] for i in lst: if (i >= thres): thres = i else: water += thres - i lst = arr[max_ele:] lst.reverse() thres = lst[0] for i in lst: if (i >= thres): thres = i else: water += thres - i return water 0 ruchikajamwal03198 hours ago class Solution{ // Function to find the trapped water between the blocks. public: long long trappingWater(int arr[], int n){ // code here int lmax[n],rmax[n]; long long int res=0; lmax[0]=arr[0]; for(int i=1;i<n;i++){ lmax[i]=max(lmax[i-1],arr[i]); } rmax[n-1]=arr[n-1]; for(int i=n-2;i>=0;i--){ rmax[i]=max(rmax[i+1],arr[i]); } for(int i=1;i<n-1;i++){ res += min(lmax[i],rmax[i])-arr[i]; } return res; }}; 0 ashishgohil140811 hours ago def trappingWater(self, a,n): left = 0 right = n-1 i = 0 j = n-1 vol = 0 while i <= j: while i <= j and a[i] <= a[j]: if a[i] <= a[left]: vol += a[left] - a[i] i += 1 else: left = i while i <= j and a[j] < a[i]: if a[right] >= a[j]: vol += a[right] - a[j] j -= 1 else: right = j return vol 0 ashish400rl1 day ago long long trappingWater(int arr[], int n){ // code here int lmax[n],rmax[n]; long long int res=0; lmax[0]=arr[0]; for(int i=1;i<n;i++){ lmax[i]=max(lmax[i-1],arr[i]); } rmax[n-1]=arr[n-1]; for(int i=n-2;i>=0;i--){ rmax[i]=max(rmax[i+1],arr[i]); } for(int i=1;i<n-1;i++){ res += min(lmax[i],rmax[i])-arr[i]; } return res; } +1 lakshitagaur1231 day ago Java Solution -: static long trappingWater(int arr[], int n) { // Your code here int lmax[] =new int[n]; int rmax[]= new int[n]; lmax[0] = arr[0]; long res=0; for(int i=1;i<n;i++) { lmax[i]= Math.max(arr[i],lmax[i-1]); } rmax[n-1]=arr[n-1]; for(int i=n-2;i>=0;i--) { rmax[i]= Math.max(arr[i],rmax[i+1]); } for(int i=0;i<n;i++) { res = res + (Math.min(lmax[i],rmax[i]) - arr[i]); } return res; } } 0 evgenykalldx2 days ago def trappingWater(self, arr,n): #Code here left_2_right = {} right_2_left = {} max_l2r = max_r2l = trapped_water = 0 for i in range(0,n): left_2_right[i] = max_l2r = max(arr[i], max_l2r) for i in range(n-1,-1,-1): right_2_left[i] = max_r2l = max(arr[i], max_r2l) for i in range(0,n): trapped_water += min(left_2_right[i], right_2_left[i]) - arr[i] return trapped_water -1 pradhanrahul33462 days ago static long trappingWater(int arr[], int n) { // Your code here int lmax[]=new int[n]; int rmax[]=new int[n]; int res=0; lmax[0]=arr[0]; for(int i=1;i<n;i++){ lmax[i]=Math.max(arr[i],arr[i-1]); } rmax[n-1]=arr[n-1]; for(int i=n-2;i>=0;i--){ rmax[i]=Math.max(arr[i],arr[i+1]); } for(int i=0;i<n;i++){ res=res+Math.min(lmax[i],rmax[i])-arr[i]; } return res; } 0 deepakt90su302 days ago lst=[]s=0n=int(input())a=list(map(int,input().strip().split()))[:n]m=max(a)index=a.index(m) if(a[0]<=a[n-1]and m==a[n-1]): t=0 for i in range(t,n): v=a[t]-a[i] if(a[t]>a[i]): x=a[t]-a[i] lst.append(x) if(v<0): t=ielif(a[0]>=a[n-1] and m==a[0]): t=-1 for i in range(t,-n,-1): v=a[t]-a[i] if(a[t]>a[i]): x=a[t]-a[i] lst.append(x) if(v<0): t=i elif(m>a[0] and m>a[n-1]): t=0 t1=-1 for i in range(0,index,1): v=a[t]-a[i] if(a[t]>a[i]): x=a[t]-a[i] lst.append(x) if(v<0): t=i for j in range(t1,-(n-index),-1): p=a[t1]-a[j] if(a[t1]>a[j]): x=a[t1]-a[j] lst.append(x) if(p<0): t1=j if(v<0): t1=-1#print(lst)for k in lst: if(k>0): s=s+kprint(s) We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. 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": 435, "s": 238, "text": "Given an array arr[] of N non-negative integers representing the height of blocks. If width of each block is 1, compute how much water can be trapped between the blocks during the rainy season. \n " }, { "code": null, "e": 446, "s": 435, "text": "Example 1:" }, { "code": null, "e": 508, "s": 446, "text": "Input:\nN = 6\narr[] = {3,0,0,2,0,4}\nOutput:\n10\nExplanation: \n\n" }, { "code": null, "e": 519, "s": 508, "text": "Example 2:" }, { "code": null, "e": 719, "s": 519, "text": "Input:\nN = 4\narr[] = {7,4,0,9}\nOutput:\n10\nExplanation:\nWater trapped by above \nblock of height 4 is 3 units and above \nblock of height 0 is 7 units. So, the \ntotal unit of water trapped is 10 units.\n" }, { "code": null, "e": 730, "s": 719, "text": "Example 3:" }, { "code": null, "e": 808, "s": 730, "text": "Input:\nN = 3\narr[] = {6,9,9}\nOutput:\n0\nExplanation:\nNo water will be trapped." }, { "code": null, "e": 1024, "s": 808, "text": "\nYour Task:\nYou don't need to read input or print anything. The task is to complete the function trappingWater() which takes arr[] and N as input parameters and returns the total amount of water that can be trapped." }, { "code": null, "e": 1087, "s": 1024, "text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1126, "s": 1087, "text": "\nConstraints:\n3 < N < 106\n0 < Ai < 108" }, { "code": null, "e": 1128, "s": 1126, "text": "0" }, { "code": null, "e": 1153, "s": 1128, "text": "dakshbajaj2410in 8 hours" }, { "code": null, "e": 1174, "s": 1153, "text": "Simple C++ Solution " }, { "code": null, "e": 1852, "s": 1174, "text": "public: long long trappingWater(int arr[], int n){ // code here long long water = 0; int left = arr[0]; int right = arr[n-1]; int lIndex = 1; int rIndex = n-2; while(lIndex<=rIndex){ if(left<=right){ if(arr[lIndex]<=left){ water+= left-arr[lIndex]; }else{ left = arr[lIndex]; } lIndex++; }else{ if(arr[rIndex]<=right){ water+= right-arr[rIndex]; }else{ right = arr[rIndex]; } rIndex--; } } return water; }" }, { "code": null, "e": 1854, "s": 1852, "text": "0" }, { "code": null, "e": 1869, "s": 1854, "text": "dakshbajaj2410" }, { "code": null, "e": 1895, "s": 1869, "text": "This comment was deleted." }, { "code": null, "e": 1897, "s": 1895, "text": "0" }, { "code": null, "e": 1923, "s": 1897, "text": "aditya16jain162 hours ago" }, { "code": null, "e": 2206, "s": 1923, "text": " def trappingWater(self, arr,n): max_ele = arr.index(max(arr)) if (max_ele == n - 1): thres = arr[0] water = 0 for i in arr: if (i >= thres): thres = i else: water += thres - i" }, { "code": null, "e": 2443, "s": 2206, "text": " elif (max_ele == 0): arr.reverse() thres = arr[0] water = 0 for i in arr: if (i >= thres): thres = i else: water += thres - i" }, { "code": null, "e": 2687, "s": 2443, "text": " else: water = 0 lst = arr[:max_ele + 1] thres = lst[0] for i in lst: if (i >= thres): thres = i else: water += thres - i" }, { "code": null, "e": 2930, "s": 2687, "text": " lst = arr[max_ele:] lst.reverse() thres = lst[0] for i in lst: if (i >= thres): thres = i else: water += thres - i return water " }, { "code": null, "e": 2932, "s": 2930, "text": "0" }, { "code": null, "e": 2961, "s": 2932, "text": "ruchikajamwal03198 hours ago" }, { "code": null, "e": 2977, "s": 2961, "text": "class Solution{" }, { "code": null, "e": 3467, "s": 2977, "text": " // Function to find the trapped water between the blocks. public: long long trappingWater(int arr[], int n){ // code here int lmax[n],rmax[n]; long long int res=0; lmax[0]=arr[0]; for(int i=1;i<n;i++){ lmax[i]=max(lmax[i-1],arr[i]); } rmax[n-1]=arr[n-1]; for(int i=n-2;i>=0;i--){ rmax[i]=max(rmax[i+1],arr[i]); } for(int i=1;i<n-1;i++){ res += min(lmax[i],rmax[i])-arr[i]; } return res; }};" }, { "code": null, "e": 3469, "s": 3467, "text": "0" }, { "code": null, "e": 3497, "s": 3469, "text": "ashishgohil140811 hours ago" }, { "code": null, "e": 4013, "s": 3497, "text": "def trappingWater(self, a,n): left = 0 right = n-1 i = 0 j = n-1 vol = 0 while i <= j: while i <= j and a[i] <= a[j]: if a[i] <= a[left]: vol += a[left] - a[i] i += 1 else: left = i while i <= j and a[j] < a[i]: if a[right] >= a[j]: vol += a[right] - a[j] j -= 1 else: right = j return vol" }, { "code": null, "e": 4015, "s": 4013, "text": "0" }, { "code": null, "e": 4036, "s": 4015, "text": "ashish400rl1 day ago" }, { "code": null, "e": 4463, "s": 4036, "text": "long long trappingWater(int arr[], int n){ // code here int lmax[n],rmax[n]; long long int res=0; lmax[0]=arr[0]; for(int i=1;i<n;i++){ lmax[i]=max(lmax[i-1],arr[i]); } rmax[n-1]=arr[n-1]; for(int i=n-2;i>=0;i--){ rmax[i]=max(rmax[i+1],arr[i]); } for(int i=1;i<n-1;i++){ res += min(lmax[i],rmax[i])-arr[i]; } return res; }" }, { "code": null, "e": 4466, "s": 4463, "text": "+1" }, { "code": null, "e": 4491, "s": 4466, "text": "lakshitagaur1231 day ago" }, { "code": null, "e": 4508, "s": 4491, "text": "Java Solution -:" }, { "code": null, "e": 5034, "s": 4510, "text": "static long trappingWater(int arr[], int n) { // Your code here int lmax[] =new int[n]; int rmax[]= new int[n]; lmax[0] = arr[0]; long res=0; for(int i=1;i<n;i++) { lmax[i]= Math.max(arr[i],lmax[i-1]); } rmax[n-1]=arr[n-1]; for(int i=n-2;i>=0;i--) { rmax[i]= Math.max(arr[i],rmax[i+1]); } for(int i=0;i<n;i++) { res = res + (Math.min(lmax[i],rmax[i]) - arr[i]); } return res; } } " }, { "code": null, "e": 5036, "s": 5034, "text": "0" }, { "code": null, "e": 5059, "s": 5036, "text": "evgenykalldx2 days ago" }, { "code": null, "e": 5514, "s": 5059, "text": " def trappingWater(self, arr,n): #Code here left_2_right = {} right_2_left = {} max_l2r = max_r2l = trapped_water = 0 for i in range(0,n): left_2_right[i] = max_l2r = max(arr[i], max_l2r) for i in range(n-1,-1,-1): right_2_left[i] = max_r2l = max(arr[i], max_r2l) for i in range(0,n): trapped_water += min(left_2_right[i], right_2_left[i]) - arr[i] return trapped_water" }, { "code": null, "e": 5517, "s": 5514, "text": "-1" }, { "code": null, "e": 5544, "s": 5517, "text": "pradhanrahul33462 days ago" }, { "code": null, "e": 6022, "s": 5544, "text": "static long trappingWater(int arr[], int n) { // Your code here int lmax[]=new int[n]; int rmax[]=new int[n]; int res=0; lmax[0]=arr[0]; for(int i=1;i<n;i++){ lmax[i]=Math.max(arr[i],arr[i-1]); } rmax[n-1]=arr[n-1]; for(int i=n-2;i>=0;i--){ rmax[i]=Math.max(arr[i],arr[i+1]); } for(int i=0;i<n;i++){ res=res+Math.min(lmax[i],rmax[i])-arr[i]; } return res; } " }, { "code": null, "e": 6024, "s": 6022, "text": "0" }, { "code": null, "e": 6048, "s": 6024, "text": "deepakt90su302 days ago" }, { "code": null, "e": 6140, "s": 6048, "text": "lst=[]s=0n=int(input())a=list(map(int,input().strip().split()))[:n]m=max(a)index=a.index(m)" }, { "code": null, "e": 6909, "s": 6140, "text": "if(a[0]<=a[n-1]and m==a[n-1]): t=0 for i in range(t,n): v=a[t]-a[i] if(a[t]>a[i]): x=a[t]-a[i] lst.append(x) if(v<0): t=ielif(a[0]>=a[n-1] and m==a[0]): t=-1 for i in range(t,-n,-1): v=a[t]-a[i] if(a[t]>a[i]): x=a[t]-a[i] lst.append(x) if(v<0): t=i elif(m>a[0] and m>a[n-1]): t=0 t1=-1 for i in range(0,index,1): v=a[t]-a[i] if(a[t]>a[i]): x=a[t]-a[i] lst.append(x) if(v<0): t=i for j in range(t1,-(n-index),-1): p=a[t1]-a[j] if(a[t1]>a[j]): x=a[t1]-a[j] lst.append(x) if(p<0): t1=j if(v<0): t1=-1#print(lst)for k in lst: if(k>0): s=s+kprint(s)" }, { "code": null, "e": 7060, "s": 6914, "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": 7096, "s": 7060, "text": " Login to access your submissions. " }, { "code": null, "e": 7106, "s": 7096, "text": "\nProblem\n" }, { "code": null, "e": 7116, "s": 7106, "text": "\nContest\n" }, { "code": null, "e": 7179, "s": 7116, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7364, "s": 7179, "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": 7648, "s": 7364, "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": 7794, "s": 7648, "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": 7871, "s": 7794, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 7912, "s": 7871, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 7940, "s": 7912, "text": "Disable browser extensions." }, { "code": null, "e": 8011, "s": 7940, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 8198, "s": 8011, "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." } ]
Data Conversion in C++
06 Oct, 2021 A user-defined data types are designed by the user to suit their requirements, the compiler does not support automatic type conversions for such data types therefore, the user needs to design the conversion routines by themselves if required. There can be 3 types of situations that may come in the data conversion between incompatible data types: Conversion of primitive data type to user-defined type: To perform this conversion, the idea is to use the constructor to perform type conversion during the object creation. Below is the example to convert int to user-defined data type: Example: C++ // C++ program to illustrate the// type-conversion#include <bits/stdc++.h>using namespace std; // Time Classclass Time { int hour; int mins; public: // Default Constructor Time() { hour = 0; mins = 0; } // Parameterized Constructor Time(int t) { hour = t / 60; mins = t % 60; } // Function to print the value // of class variables void Display() { cout << "Time = " << hour << " hrs and " << mins << " mins\n"; }}; // Driver Codeint main(){ // Object of Time class Time T1; int dur = 95; // Conversion of int type to // class type T1 = dur; T1.Display(); return 0;} Time = 1 hrs and 35 mins Conversion of class object to primitive data type: In this conversion, the from type is a class object and the to type is primitive data type. The normal form of an overloaded casting operator function, also known as a conversion function. Below is the syntax for the same: Syntax: operator typename() { // Code } Now, this function converts a user-defined data type to a primitive data type. For Example, the operator double() converts a class object to type double, the operator int() converts a class type object to type int, and so on. Below is the program to illustrate the same: Example: C++ // C++ program to illustrate the// above conversion#include <bits/stdc++.h>using namespace std; // Tie Classclass Time { int hrs, mins; public: // Constructor Time(int, int); // Casting operator operator int(); // Destructor ~Time() { cout << "Destructor is called." << endl; }}; // Function that assigns value to the// member variable of the classTime::Time(int a, int b){ hrs = a; mins = b;} // int() operator is used for Data// conversion of class to primitiveTime::operator int(){ cout << "Conversion of Class" << " Type to Primitive Type" << endl; return (hrs * 60 + mins);} // Function performs type conversion// from the Time class type object// to int data typevoid TypeConversion(int hour, int mins){ int duration; // Create Time Class object Time t(hour, mins); // Conversion OR duration = (int)t duration = t; cout << "Total Minutes are " << duration << endl; // Conversion from Class type to // Primitive type cout << "2nd method operator" << " overloading " << endl; duration = t.operator int(); cout << "Total Minutes are " << duration << endl; return;} // Driver Codeint main(){ // Input value int hour, mins; hour = 2; mins = 20; // Function call to illustrate // type conversion TypeConversion(hour, mins); return 0;} Conversion of Class Type to Primitive Type Total Minutes are 140 2nd method operator overloading Conversion of Class Type to Primitive Type Total Minutes are 140 Destructor is called. Conversion of Class Type to Primitive Type Total Minutes are 140 2nd method operator overloading Conversion of Class Type to Primitive Type Total Minutes are 140 Destructor is called. Now, the function will convert the vector to scalar magnitude. The operator double() can be used as: double len = double(S1); Or, double len = S1; where S1 is an object of type vector. Conversion of one class type to another class type: In this type, one class type is converted into another class type. It can be done in 2 ways : 1.Using constructor 2.Using Overloading casting operator 1.Using constructor : In the Destination class we use the constructor method //Objects of different types ObjectX=ObjectY; Here ObjectX is Destination object and ObjectY is source object Example: C++ #include<iostream>using namespace std;//cgs systemclass CGS { int mts; //meters int cms; //centimeters public: void showdata() { cout<<"Meters and centimeters in CGS system:"; std::cout << mts<<" meters "<<cms<<" centimeters" << std::endl; } CGS(int x,int y) // parameterized constructor { mts=x; cms=y; } int getcms() { return cms; } int getmts() { return mts; } }; class FPS { int feet; int inches; public: FPS() // default constructor { feet=0; inches=0; } FPS(CGS d2) { int x; x=d2.getcms()+d2.getmts()*100; x=x/2.5; feet=x/12; inches=x%12; } void showdata() { cout<<"feet and inches in FPS system:"; std::cout << feet<<" feet "<<inches<<" inches" << std::endl; } }; int main() { CGS d1(9,10); FPS d2; d2=d1; d1.showdata(); //to display CGS values d2.showdata(); //to display FPS values return 0; } Meters and centimeters in CGS system:9 meters 10 centimeters feet and inches in FPS system:30 feet 4 inches 2.Using Overloading casting operator // Objects of different types objectX = objectY; Here we use Overloading casting operator in source class i.e. overloading destination class in source class See the below example in which we have two classes Time and Minute respectively and will convert one class Time to another Minute class. In the below example minute class is destination class and time class is source class so we need to overload the destination class in the source class Here we should not tell the return type but we returns the overloaded class object i.e. returning value without specifying return type C++ // C++ program to illustrate the// above conversion#include <bits/stdc++.h>using namespace std;//minutes classclass Minute { public: int mins; // Constructors Minute() { mins = 0; } // Function to print the value of // hours and minutes void show() { cout << "\nTotal Minute : " << mins << endl; }}; // Time Classclass Time { int hr, mins; public: // Constructors Time(int h, int m) { hr = h; mins = m; } Time() { cout << "\nTime's Object Created"; } operator Minute () //overloading minute class { Minute m; m.mins = (hr * 60) + mins; return m; } //driver code // Function to print the value of // hours and minutes void show() { cout << "Hour: " << hr << endl; cout << "Minute : " << mins << endl; }}; // Minutes Classint main(){ Time T1(3,40); Minute m; m=T1; //minute class is destination and Time class is source class T1.show(); m.show(); return 0;} Hour: 3 Minute : 40 Total Minute : 220 tupakulateja3 varshagumber28 gulshankumarar231 C-Data Types cpp-data-types Articles C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction Time complexities of different data structures SQL | DROP, TRUNCATE Difference Between Object And Class Implementation of LinkedList in Javascript Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) std::sort() in C++ STL Bitwise Operators in C/C++
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Oct, 2021" }, { "code": null, "e": 297, "s": 54, "text": "A user-defined data types are designed by the user to suit their requirements, the compiler does not support automatic type conversions for such data types therefore, the user needs to design the conversion routines by themselves if required." }, { "code": null, "e": 402, "s": 297, "text": "There can be 3 types of situations that may come in the data conversion between incompatible data types:" }, { "code": null, "e": 640, "s": 402, "text": "Conversion of primitive data type to user-defined type: To perform this conversion, the idea is to use the constructor to perform type conversion during the object creation. Below is the example to convert int to user-defined data type: " }, { "code": null, "e": 649, "s": 640, "text": "Example:" }, { "code": null, "e": 653, "s": 649, "text": "C++" }, { "code": "// C++ program to illustrate the// type-conversion#include <bits/stdc++.h>using namespace std; // Time Classclass Time { int hour; int mins; public: // Default Constructor Time() { hour = 0; mins = 0; } // Parameterized Constructor Time(int t) { hour = t / 60; mins = t % 60; } // Function to print the value // of class variables void Display() { cout << \"Time = \" << hour << \" hrs and \" << mins << \" mins\\n\"; }}; // Driver Codeint main(){ // Object of Time class Time T1; int dur = 95; // Conversion of int type to // class type T1 = dur; T1.Display(); return 0;}", "e": 1351, "s": 653, "text": null }, { "code": null, "e": 1376, "s": 1351, "text": "Time = 1 hrs and 35 mins" }, { "code": null, "e": 1650, "s": 1376, "text": "Conversion of class object to primitive data type: In this conversion, the from type is a class object and the to type is primitive data type. The normal form of an overloaded casting operator function, also known as a conversion function. Below is the syntax for the same:" }, { "code": null, "e": 1658, "s": 1650, "text": "Syntax:" }, { "code": null, "e": 1693, "s": 1658, "text": "operator typename()\n{\n // Code\n}" }, { "code": null, "e": 1965, "s": 1693, "text": "Now, this function converts a user-defined data type to a primitive data type. For Example, the operator double() converts a class object to type double, the operator int() converts a class type object to type int, and so on. Below is the program to illustrate the same: " }, { "code": null, "e": 1974, "s": 1965, "text": "Example:" }, { "code": null, "e": 1978, "s": 1974, "text": "C++" }, { "code": "// C++ program to illustrate the// above conversion#include <bits/stdc++.h>using namespace std; // Tie Classclass Time { int hrs, mins; public: // Constructor Time(int, int); // Casting operator operator int(); // Destructor ~Time() { cout << \"Destructor is called.\" << endl; }}; // Function that assigns value to the// member variable of the classTime::Time(int a, int b){ hrs = a; mins = b;} // int() operator is used for Data// conversion of class to primitiveTime::operator int(){ cout << \"Conversion of Class\" << \" Type to Primitive Type\" << endl; return (hrs * 60 + mins);} // Function performs type conversion// from the Time class type object// to int data typevoid TypeConversion(int hour, int mins){ int duration; // Create Time Class object Time t(hour, mins); // Conversion OR duration = (int)t duration = t; cout << \"Total Minutes are \" << duration << endl; // Conversion from Class type to // Primitive type cout << \"2nd method operator\" << \" overloading \" << endl; duration = t.operator int(); cout << \"Total Minutes are \" << duration << endl; return;} // Driver Codeint main(){ // Input value int hour, mins; hour = 2; mins = 20; // Function call to illustrate // type conversion TypeConversion(hour, mins); return 0;}", "e": 3383, "s": 1978, "text": null }, { "code": null, "e": 3568, "s": 3383, "text": "Conversion of Class Type to Primitive Type\nTotal Minutes are 140\n2nd method operator overloading \nConversion of Class Type to Primitive Type\nTotal Minutes are 140\nDestructor is called." }, { "code": null, "e": 3753, "s": 3568, "text": "Conversion of Class Type to Primitive Type\nTotal Minutes are 140\n2nd method operator overloading \nConversion of Class Type to Primitive Type\nTotal Minutes are 140\nDestructor is called." }, { "code": null, "e": 3858, "s": 3755, "text": "Now, the function will convert the vector to scalar magnitude. The operator double() can be used as: " }, { "code": null, "e": 3954, "s": 3858, "text": "double len = double(S1);\n Or,\ndouble len = S1;\nwhere S1 is an object of type vector." }, { "code": null, "e": 4101, "s": 3954, "text": "Conversion of one class type to another class type: In this type, one class type is converted into another class type. It can be done in 2 ways :" }, { "code": null, "e": 4121, "s": 4101, "text": "1.Using constructor" }, { "code": null, "e": 4158, "s": 4121, "text": "2.Using Overloading casting operator" }, { "code": null, "e": 4180, "s": 4158, "text": "1.Using constructor :" }, { "code": null, "e": 4238, "s": 4180, "text": "In the Destination class we use the constructor method " }, { "code": null, "e": 4349, "s": 4238, "text": "//Objects of different types \nObjectX=ObjectY;\nHere ObjectX is Destination object and ObjectY is source object" }, { "code": null, "e": 4358, "s": 4349, "text": "Example:" }, { "code": null, "e": 4362, "s": 4358, "text": "C++" }, { "code": "#include<iostream>using namespace std;//cgs systemclass CGS { int mts; //meters int cms; //centimeters public: void showdata() { cout<<\"Meters and centimeters in CGS system:\"; std::cout << mts<<\" meters \"<<cms<<\" centimeters\" << std::endl; } CGS(int x,int y) // parameterized constructor { mts=x; cms=y; } int getcms() { return cms; } int getmts() { return mts; } }; class FPS { int feet; int inches; public: FPS() // default constructor { feet=0; inches=0; } FPS(CGS d2) { int x; x=d2.getcms()+d2.getmts()*100; x=x/2.5; feet=x/12; inches=x%12; } void showdata() { cout<<\"feet and inches in FPS system:\"; std::cout << feet<<\" feet \"<<inches<<\" inches\" << std::endl; } }; int main() { CGS d1(9,10); FPS d2; d2=d1; d1.showdata(); //to display CGS values d2.showdata(); //to display FPS values return 0; }", "e": 5347, "s": 4362, "text": null }, { "code": null, "e": 5455, "s": 5347, "text": "Meters and centimeters in CGS system:9 meters 10 centimeters\nfeet and inches in FPS system:30 feet 4 inches" }, { "code": null, "e": 5493, "s": 5455, "text": "2.Using Overloading casting operator " }, { "code": null, "e": 5542, "s": 5493, "text": "// Objects of different types\nobjectX = objectY;" }, { "code": null, "e": 5651, "s": 5542, "text": "Here we use Overloading casting operator in source class i.e. overloading destination class in source class " }, { "code": null, "e": 5788, "s": 5651, "text": "See the below example in which we have two classes Time and Minute respectively and will convert one class Time to another Minute class." }, { "code": null, "e": 5874, "s": 5788, "text": "In the below example minute class is destination class and time class is source class" }, { "code": null, "e": 5939, "s": 5874, "text": "so we need to overload the destination class in the source class" }, { "code": null, "e": 6023, "s": 5939, "text": "Here we should not tell the return type but we returns the overloaded class object " }, { "code": null, "e": 6076, "s": 6023, "text": "i.e. returning value without specifying return type " }, { "code": null, "e": 6080, "s": 6076, "text": "C++" }, { "code": "// C++ program to illustrate the// above conversion#include <bits/stdc++.h>using namespace std;//minutes classclass Minute { public: int mins; // Constructors Minute() { mins = 0; } // Function to print the value of // hours and minutes void show() { cout << \"\\nTotal Minute : \" << mins << endl; }}; // Time Classclass Time { int hr, mins; public: // Constructors Time(int h, int m) { hr = h; mins = m; } Time() { cout << \"\\nTime's Object Created\"; } operator Minute () //overloading minute class { Minute m; m.mins = (hr * 60) + mins; return m; } //driver code // Function to print the value of // hours and minutes void show() { cout << \"Hour: \" << hr << endl; cout << \"Minute : \" << mins << endl; }}; // Minutes Classint main(){ Time T1(3,40); Minute m; m=T1; //minute class is destination and Time class is source class T1.show(); m.show(); return 0;}", "e": 7109, "s": 6080, "text": null }, { "code": null, "e": 7149, "s": 7109, "text": "Hour: 3\nMinute : 40\n\nTotal Minute : 220" }, { "code": null, "e": 7163, "s": 7149, "text": "tupakulateja3" }, { "code": null, "e": 7178, "s": 7163, "text": "varshagumber28" }, { "code": null, "e": 7196, "s": 7178, "text": "gulshankumarar231" }, { "code": null, "e": 7209, "s": 7196, "text": "C-Data Types" }, { "code": null, "e": 7224, "s": 7209, "text": "cpp-data-types" }, { "code": null, "e": 7233, "s": 7224, "text": "Articles" }, { "code": null, "e": 7237, "s": 7233, "text": "C++" }, { "code": null, "e": 7250, "s": 7237, "text": "C++ Programs" }, { "code": null, "e": 7254, "s": 7250, "text": "CPP" }, { "code": null, "e": 7352, "s": 7254, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7378, "s": 7352, "text": "Docker - COPY Instruction" }, { "code": null, "e": 7425, "s": 7378, "text": "Time complexities of different data structures" }, { "code": null, "e": 7446, "s": 7425, "text": "SQL | DROP, TRUNCATE" }, { "code": null, "e": 7482, "s": 7446, "text": "Difference Between Object And Class" }, { "code": null, "e": 7525, "s": 7482, "text": "Implementation of LinkedList in Javascript" }, { "code": null, "e": 7543, "s": 7525, "text": "Vector in C++ STL" }, { "code": null, "e": 7586, "s": 7543, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 7632, "s": 7586, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 7655, "s": 7632, "text": "std::sort() in C++ STL" } ]
How to validate time in 24-hour format using Regular Expression
10 Feb, 2021 Given a string str, the task is to check whether the string is valid time in 24-hour format or not by using Regular Expression. The valid time in the 24-hour format must satisfy the following conditions. It should start from 0-23 or 00-23.It should be followed by a ‘:'(colon).It should be followed by two digits from 00 to 59.It should not end with ‘am’, ‘pm’ or ‘AM’, ‘PM’. It should start from 0-23 or 00-23. It should be followed by a ‘:'(colon). It should be followed by two digits from 00 to 59. It should not end with ‘am’, ‘pm’ or ‘AM’, ‘PM’. Examples: Input: str = “13:05” Output: true Explanation: The given string satisfies all the above mentioned conditions.Input: str = “02:15” Output: true Explanation: The given string satisfies all the above mentioned conditions.Input: str = “24:00” Output: false Explanation: The given string doesn’t be in the range of 0-23 or 00-23(i.e., hour is out of range), therefore it is not a valid time in 24-hour format.Input: str = “10:60” Output: false Explanation: The given string doesn’t be in the range of 00 to 59(i.e., minute is out of range), therefore it is not a valid time in 24-hour format.Input: str = “10:15 PM” Output: false Explanation: The given string end with ‘AM’ or ‘PM’, therefore it is not a valid time in 24-hour format. Approach: This problem can be solved by using Regular Expression. Get the string.Create a regular expression to check time in 24-hour format as mentioned below: Get the string. Create a regular expression to check time in 24-hour format as mentioned below: regex = "([01]?[0-9]|2[0-3]):[0-5][0-9]"; Where: ( represents the start of the group.[01]?[0-9] represents the time starts with 0-9, 1-9, 00-09, 10-19.| represents or.2[0-3] represents the time starts with 20-23.) represents the end of the group. : represents the time should be followed by a colon(:).[0-5][0-9] represents the time followed by 00 to 59Match the given string with the regex, in Java this can be done by using Pattern.matcher().Return true if the string matches with the given regex, else return false. Where: ( represents the start of the group.[01]?[0-9] represents the time starts with 0-9, 1-9, 00-09, 10-19.| represents or.2[0-3] represents the time starts with 20-23.) represents the end of the group. : represents the time should be followed by a colon(:).[0-5][0-9] represents the time followed by 00 to 59 ( represents the start of the group. [01]?[0-9] represents the time starts with 0-9, 1-9, 00-09, 10-19. | represents or. 2[0-3] represents the time starts with 20-23. ) represents the end of the group. : represents the time should be followed by a colon(:). [0-5][0-9] represents the time followed by 00 to 59 Match the given string with the regex, in Java this can be done by using Pattern.matcher(). Return true if the string matches with the given regex, else return false. Below is the implementation of the above approach: C++ Java Python3 // C++ program to validate// time in 24-hour format// using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate time in 24-hour formatbool isValidTime(string str){ // Regex to check valid time in 24-hour format const regex pattern("([01]?[0-9]|2[0-3]):[0-5][0-9]"); // If the time in 24-hour format // is empty return false if (str.empty()) { return false; } // Return true if the time in 24-hour format // matched the ReGex if(regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = "13:05"; cout << str1 + ": "<< isValidTime(str1) << endl; // Test Case 2: string str2 = "02:15"; cout << str2 + ": "<< isValidTime(str2) << endl; // Test Case 3: string str3 = "24:00"; cout << str3 + ": "<< isValidTime(str3) << endl; // Test Case 4: string str4 = "10:60"; cout << str4 + ": "<< isValidTime(str4) << endl; // Test Case 5: string str5 = "10:15 PM"; cout << str5 + ": "<< isValidTime(str5) << endl; return 0;} // This code is contributed by yuvraj_chandra // Java program to validate the time in// 24-hour format using Regular Expression. import java.util.regex.*; class GFG { // Function to validate the time in 24-hour format public static boolean isValidTime(String time) { // Regex to check valid time in 24-hour format. String regex = "([01]?[0-9]|2[0-3]):[0-5][0-9]"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the time is empty // return false if (time == null) { return false; } // Pattern class contains matcher() method // to find matching between given time // and regular expression. Matcher m = p.matcher(time); // Return if the time // matched the ReGex return m.matches(); } // Driver Code. public static void main(String args[]) { // Test Case 1: String str1 = "13:05"; System.out.println(str1 + ": " + isValidTime(str1)); // Test Case 2: String str2 = "02:15"; System.out.println(str2 + ": " + isValidTime(str2)); // Test Case 3: String str3 = "24:00"; System.out.println(str3 + ": " + isValidTime(str3)); // Test Case 4: String str4 = "10:60"; System.out.println(str4 + ": " + isValidTime(str4)); // Test Case 5: String str5 = "10:15 PM"; System.out.println(str5 + ": " + isValidTime(str5)); }} # Python3 program to validate the time in# 24-hour format using Regular Expression.import re # Function to validate the time# in 24-hour formatdef isValidTime(time): # Regex to check valid time in 24-hour format. regex = "^([01]?[0-9]|2[0-3]):[0-5][0-9]$"; # Compile the ReGex p = re.compile(regex); # If the time is empty # return false if (time == "") : return False; # Pattern class contains matcher() method # to find matching between given time # and regular expression. m = re.search(p, time); # Return True if the time # matched the ReGex otherwise False if m is None : return False; else : return True # Driver Code.if __name__ == "__main__" : # Test Case 1: str1 = "13:05"; print(str1, ": ", isValidTime(str1)); # Test Case 2: str2 = "02:15"; print(str2, ": ", isValidTime(str2)); # Test Case 3: str3 = "24:00"; print(str3, ": ", isValidTime(str3)); # Test Case 4: str4 = "10:60"; print(str4, ": ", isValidTime(str4)); # Test Case 5: str5 = "10:15 PM"; print(str5, ": ", isValidTime(str5)); # This code is contributed by AnkitRai01 13:05: true 02:15: true 24:00: false 10:60: false 10:15 PM: false ankthon yuvraj_chandra CPP-regex java-regular-expression Pattern Searching Strings Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check if an URL is valid or not using Regular Expression Wildcard Pattern Matching Split the binary string into substrings with equal number of 0s and 1s Search a Word in a 2D Grid of characters Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 1 Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Different Methods to Reverse a String in C++
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Feb, 2021" }, { "code": null, "e": 158, "s": 28, "text": "Given a string str, the task is to check whether the string is valid time in 24-hour format or not by using Regular Expression. " }, { "code": null, "e": 236, "s": 158, "text": "The valid time in the 24-hour format must satisfy the following conditions. " }, { "code": null, "e": 408, "s": 236, "text": "It should start from 0-23 or 00-23.It should be followed by a ‘:'(colon).It should be followed by two digits from 00 to 59.It should not end with ‘am’, ‘pm’ or ‘AM’, ‘PM’." }, { "code": null, "e": 444, "s": 408, "text": "It should start from 0-23 or 00-23." }, { "code": null, "e": 483, "s": 444, "text": "It should be followed by a ‘:'(colon)." }, { "code": null, "e": 534, "s": 483, "text": "It should be followed by two digits from 00 to 59." }, { "code": null, "e": 583, "s": 534, "text": "It should not end with ‘am’, ‘pm’ or ‘AM’, ‘PM’." }, { "code": null, "e": 595, "s": 583, "text": "Examples: " }, { "code": null, "e": 1327, "s": 595, "text": "Input: str = “13:05” Output: true Explanation: The given string satisfies all the above mentioned conditions.Input: str = “02:15” Output: true Explanation: The given string satisfies all the above mentioned conditions.Input: str = “24:00” Output: false Explanation: The given string doesn’t be in the range of 0-23 or 00-23(i.e., hour is out of range), therefore it is not a valid time in 24-hour format.Input: str = “10:60” Output: false Explanation: The given string doesn’t be in the range of 00 to 59(i.e., minute is out of range), therefore it is not a valid time in 24-hour format.Input: str = “10:15 PM” Output: false Explanation: The given string end with ‘AM’ or ‘PM’, therefore it is not a valid time in 24-hour format. " }, { "code": null, "e": 1397, "s": 1329, "text": "Approach: This problem can be solved by using Regular Expression. " }, { "code": null, "e": 1494, "s": 1397, "text": "Get the string.Create a regular expression to check time in 24-hour format as mentioned below: " }, { "code": null, "e": 1510, "s": 1494, "text": "Get the string." }, { "code": null, "e": 1592, "s": 1510, "text": "Create a regular expression to check time in 24-hour format as mentioned below: " }, { "code": null, "e": 1634, "s": 1592, "text": "regex = \"([01]?[0-9]|2[0-3]):[0-5][0-9]\";" }, { "code": null, "e": 2112, "s": 1634, "text": "Where: ( represents the start of the group.[01]?[0-9] represents the time starts with 0-9, 1-9, 00-09, 10-19.| represents or.2[0-3] represents the time starts with 20-23.) represents the end of the group. : represents the time should be followed by a colon(:).[0-5][0-9] represents the time followed by 00 to 59Match the given string with the regex, in Java this can be done by using Pattern.matcher().Return true if the string matches with the given regex, else return false." }, { "code": null, "e": 2425, "s": 2112, "text": "Where: ( represents the start of the group.[01]?[0-9] represents the time starts with 0-9, 1-9, 00-09, 10-19.| represents or.2[0-3] represents the time starts with 20-23.) represents the end of the group. : represents the time should be followed by a colon(:).[0-5][0-9] represents the time followed by 00 to 59" }, { "code": null, "e": 2462, "s": 2425, "text": "( represents the start of the group." }, { "code": null, "e": 2529, "s": 2462, "text": "[01]?[0-9] represents the time starts with 0-9, 1-9, 00-09, 10-19." }, { "code": null, "e": 2546, "s": 2529, "text": "| represents or." }, { "code": null, "e": 2592, "s": 2546, "text": "2[0-3] represents the time starts with 20-23." }, { "code": null, "e": 2629, "s": 2592, "text": ") represents the end of the group. " }, { "code": null, "e": 2685, "s": 2629, "text": ": represents the time should be followed by a colon(:)." }, { "code": null, "e": 2737, "s": 2685, "text": "[0-5][0-9] represents the time followed by 00 to 59" }, { "code": null, "e": 2829, "s": 2737, "text": "Match the given string with the regex, in Java this can be done by using Pattern.matcher()." }, { "code": null, "e": 2904, "s": 2829, "text": "Return true if the string matches with the given regex, else return false." }, { "code": null, "e": 2957, "s": 2904, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 2961, "s": 2957, "text": "C++" }, { "code": null, "e": 2966, "s": 2961, "text": "Java" }, { "code": null, "e": 2974, "s": 2966, "text": "Python3" }, { "code": "// C++ program to validate// time in 24-hour format// using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate time in 24-hour formatbool isValidTime(string str){ // Regex to check valid time in 24-hour format const regex pattern(\"([01]?[0-9]|2[0-3]):[0-5][0-9]\"); // If the time in 24-hour format // is empty return false if (str.empty()) { return false; } // Return true if the time in 24-hour format // matched the ReGex if(regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = \"13:05\"; cout << str1 + \": \"<< isValidTime(str1) << endl; // Test Case 2: string str2 = \"02:15\"; cout << str2 + \": \"<< isValidTime(str2) << endl; // Test Case 3: string str3 = \"24:00\"; cout << str3 + \": \"<< isValidTime(str3) << endl; // Test Case 4: string str4 = \"10:60\"; cout << str4 + \": \"<< isValidTime(str4) << endl; // Test Case 5: string str5 = \"10:15 PM\"; cout << str5 + \": \"<< isValidTime(str5) << endl; return 0;} // This code is contributed by yuvraj_chandra", "e": 4094, "s": 2974, "text": null }, { "code": "// Java program to validate the time in// 24-hour format using Regular Expression. import java.util.regex.*; class GFG { // Function to validate the time in 24-hour format public static boolean isValidTime(String time) { // Regex to check valid time in 24-hour format. String regex = \"([01]?[0-9]|2[0-3]):[0-5][0-9]\"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the time is empty // return false if (time == null) { return false; } // Pattern class contains matcher() method // to find matching between given time // and regular expression. Matcher m = p.matcher(time); // Return if the time // matched the ReGex return m.matches(); } // Driver Code. public static void main(String args[]) { // Test Case 1: String str1 = \"13:05\"; System.out.println(str1 + \": \" + isValidTime(str1)); // Test Case 2: String str2 = \"02:15\"; System.out.println(str2 + \": \" + isValidTime(str2)); // Test Case 3: String str3 = \"24:00\"; System.out.println(str3 + \": \" + isValidTime(str3)); // Test Case 4: String str4 = \"10:60\"; System.out.println(str4 + \": \" + isValidTime(str4)); // Test Case 5: String str5 = \"10:15 PM\"; System.out.println(str5 + \": \" + isValidTime(str5)); }}", "e": 5658, "s": 4094, "text": null }, { "code": "# Python3 program to validate the time in# 24-hour format using Regular Expression.import re # Function to validate the time# in 24-hour formatdef isValidTime(time): # Regex to check valid time in 24-hour format. regex = \"^([01]?[0-9]|2[0-3]):[0-5][0-9]$\"; # Compile the ReGex p = re.compile(regex); # If the time is empty # return false if (time == \"\") : return False; # Pattern class contains matcher() method # to find matching between given time # and regular expression. m = re.search(p, time); # Return True if the time # matched the ReGex otherwise False if m is None : return False; else : return True # Driver Code.if __name__ == \"__main__\" : # Test Case 1: str1 = \"13:05\"; print(str1, \": \", isValidTime(str1)); # Test Case 2: str2 = \"02:15\"; print(str2, \": \", isValidTime(str2)); # Test Case 3: str3 = \"24:00\"; print(str3, \": \", isValidTime(str3)); # Test Case 4: str4 = \"10:60\"; print(str4, \": \", isValidTime(str4)); # Test Case 5: str5 = \"10:15 PM\"; print(str5, \": \", isValidTime(str5)); # This code is contributed by AnkitRai01", "e": 6860, "s": 5658, "text": null }, { "code": null, "e": 6926, "s": 6860, "text": "13:05: true\n02:15: true\n24:00: false\n10:60: false\n10:15 PM: false" }, { "code": null, "e": 6936, "s": 6928, "text": "ankthon" }, { "code": null, "e": 6951, "s": 6936, "text": "yuvraj_chandra" }, { "code": null, "e": 6961, "s": 6951, "text": "CPP-regex" }, { "code": null, "e": 6985, "s": 6961, "text": "java-regular-expression" }, { "code": null, "e": 7003, "s": 6985, "text": "Pattern Searching" }, { "code": null, "e": 7011, "s": 7003, "text": "Strings" }, { "code": null, "e": 7019, "s": 7011, "text": "Strings" }, { "code": null, "e": 7037, "s": 7019, "text": "Pattern Searching" }, { "code": null, "e": 7135, "s": 7037, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7192, "s": 7135, "text": "Check if an URL is valid or not using Regular Expression" }, { "code": null, "e": 7218, "s": 7192, "text": "Wildcard Pattern Matching" }, { "code": null, "e": 7289, "s": 7218, "text": "Split the binary string into substrings with equal number of 0s and 1s" }, { "code": null, "e": 7330, "s": 7289, "text": "Search a Word in a 2D Grid of characters" }, { "code": null, "e": 7404, "s": 7330, "text": "Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 1" }, { "code": null, "e": 7450, "s": 7404, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 7475, "s": 7450, "text": "Reverse a string in Java" }, { "code": null, "e": 7535, "s": 7475, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 7550, "s": 7535, "text": "C++ Data Types" } ]
p5.js | loadStrings() Function
13 Mar, 2020 The loadStrings() function is used to read the contents of a file and create an array of strings with each of the lines of the file. The file to be read must be located at the sketch directory if the file name is used, otherwise, a URL to the file can be specified. This function is recommended to be called in the preload() function to ensure that the function is executed before the other functions. Syntax: loadStrings( filename, callback, errorCallback ) Parameters: This function accept three parameter as mentioned above and described below: filename: This is a string which denotes the name of the file or the url to load the file from. callback: This is a function which is called after the function is successfully executed. The first argument for this function is the strings array. errorCallback: This is a function which is called if there is any error in executing the function. The first argument for this function is the error response. Below examples illustrate the loadStrings() function in p5.js: Example 1: let result; function preload() { result = loadStrings("test_file.txt");} function setup() { createCanvas(600, 300); textSize(22);} function draw() { clear(); text("The contents of the file " + "are shown below:", 20, 20); // Check if the strings array // is non-empty before displaying // the contents if (result.length > 0) { for (let i = 0; i < result.length; i++) { text(result[i], 20, 60 + i * 20); } } else { text("File is empty", 20, 60); }} Output: Example 2: let result; function setup() { createCanvas(600, 300); textSize(22); text("The file would be loaded" + " below...", 20, 20); result = loadStrings( "test_file.txt", fileLoaded);} function fileLoaded() { text("The contents of the file " + "are shown below:", 20, 60); // Check if the strings array // is non-empty before // displaying the contents if (result.length > 0) { for (let i = 0; i < result.length; i++) { text(result[i], 20, 100 + i * 20); } } else { text("File is empty", 20, 60); }} Output: Online editor: https://editor.p5js.org/ Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Reference: https://p5js.org/reference/#/p5/loadStrings JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Mar, 2020" }, { "code": null, "e": 294, "s": 28, "text": "The loadStrings() function is used to read the contents of a file and create an array of strings with each of the lines of the file. The file to be read must be located at the sketch directory if the file name is used, otherwise, a URL to the file can be specified." }, { "code": null, "e": 430, "s": 294, "text": "This function is recommended to be called in the preload() function to ensure that the function is executed before the other functions." }, { "code": null, "e": 438, "s": 430, "text": "Syntax:" }, { "code": null, "e": 487, "s": 438, "text": "loadStrings( filename, callback, errorCallback )" }, { "code": null, "e": 576, "s": 487, "text": "Parameters: This function accept three parameter as mentioned above and described below:" }, { "code": null, "e": 672, "s": 576, "text": "filename: This is a string which denotes the name of the file or the url to load the file from." }, { "code": null, "e": 821, "s": 672, "text": "callback: This is a function which is called after the function is successfully executed. The first argument for this function is the strings array." }, { "code": null, "e": 980, "s": 821, "text": "errorCallback: This is a function which is called if there is any error in executing the function. The first argument for this function is the error response." }, { "code": null, "e": 1043, "s": 980, "text": "Below examples illustrate the loadStrings() function in p5.js:" }, { "code": null, "e": 1054, "s": 1043, "text": "Example 1:" }, { "code": "let result; function preload() { result = loadStrings(\"test_file.txt\");} function setup() { createCanvas(600, 300); textSize(22);} function draw() { clear(); text(\"The contents of the file \" + \"are shown below:\", 20, 20); // Check if the strings array // is non-empty before displaying // the contents if (result.length > 0) { for (let i = 0; i < result.length; i++) { text(result[i], 20, 60 + i * 20); } } else { text(\"File is empty\", 20, 60); }}", "e": 1586, "s": 1054, "text": null }, { "code": null, "e": 1594, "s": 1586, "text": "Output:" }, { "code": null, "e": 1605, "s": 1594, "text": "Example 2:" }, { "code": "let result; function setup() { createCanvas(600, 300); textSize(22); text(\"The file would be loaded\" + \" below...\", 20, 20); result = loadStrings( \"test_file.txt\", fileLoaded);} function fileLoaded() { text(\"The contents of the file \" + \"are shown below:\", 20, 60); // Check if the strings array // is non-empty before // displaying the contents if (result.length > 0) { for (let i = 0; i < result.length; i++) { text(result[i], 20, 100 + i * 20); } } else { text(\"File is empty\", 20, 60); }}", "e": 2209, "s": 1605, "text": null }, { "code": null, "e": 2217, "s": 2209, "text": "Output:" }, { "code": null, "e": 2257, "s": 2217, "text": "Online editor: https://editor.p5js.org/" }, { "code": null, "e": 2355, "s": 2257, "text": "Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/" }, { "code": null, "e": 2410, "s": 2355, "text": "Reference: https://p5js.org/reference/#/p5/loadStrings" }, { "code": null, "e": 2427, "s": 2410, "text": "JavaScript-p5.js" }, { "code": null, "e": 2438, "s": 2427, "text": "JavaScript" }, { "code": null, "e": 2455, "s": 2438, "text": "Web Technologies" }, { "code": null, "e": 2553, "s": 2455, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2614, "s": 2553, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2686, "s": 2614, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2726, "s": 2686, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2779, "s": 2726, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2820, "s": 2779, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2853, "s": 2820, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2915, "s": 2853, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2976, "s": 2915, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3026, "s": 2976, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Memento design pattern
01 Sep, 2021 Memento pattern is a behavioral design pattern. Memento pattern is used to restore state of an object to a previous state. As your application is progressing, you may want to save checkpoints in your application and restore back to those checkpoints later. UML Diagram Memento design pattern Design components originator : the object for which the state is to be saved. It creates the memento and uses it in future to undo. memento : the object that is going to maintain the state of originator. Its just a POJO. caretaker : the object that keeps track of multiple memento. Like maintaining savepoints. A Caretaker would like to perform an operation on the Originator while having the possibility to rollback. The caretaker calls the createMemento() method on the originator asking the originator to pass it a memento object. At this point the originator creates a memento object saving its internal state and passes the memento to the caretaker. The caretaker maintains the memento object and performs the operation. In case of the need to undo the operation, the caretaker calls the setMemento() method on the originator passing the maintained memento object. The originator would accept the memento, using it to restore its previous state. Let’s see an example of Memento design pattern. import java.util.List;import java.util.ArrayList; class Life{ private String time; public void set(String time) { System.out.println("Setting time to " + time); this.time = time; } public Memento saveToMemento() { System.out.println("Saving time to Memento"); return new Memento(time); } public void restoreFromMemento(Memento memento) { time = memento.getSavedTime(); System.out.println("Time restored from Memento: " + time); } public static class Memento { private final String time; public Memento(String timeToSave) { time = timeToSave; } public String getSavedTime() { return time; } }} class Design { public static void main(String[] args) { List<Life.Memento> savedTimes = new ArrayList<Life.Memento>(); Life life = new Life(); //time travel and record the eras life.set("1000 B.C."); savedTimes.add(life.saveToMemento()); life.set("1000 A.D."); savedTimes.add(life.saveToMemento()); life.set("2000 A.D."); savedTimes.add(life.saveToMemento()); life.set("4000 A.D."); life.restoreFromMemento(savedTimes.get(0)); }} Output: Setting time to 1000 B.C. Saving time to Memento Setting time to 1000 A.D. Saving time to Memento Setting time to 2000 A.D. Saving time to Memento Setting time to 4000 A.D. Time restored from Memento: 1000 B.C. Advantage We can use Serialization to achieve memento pattern implementation that is more generic rather than Memento pattern where every object needs to have it’s own Memento class implementation. Disadvantage If Originator object is very huge then Memento object size will also be huge and use a lot of memory. Further Read – Memento Method in Python This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Design Pattern Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Factory method design pattern in Java Builder Design Pattern Unified Modeling Language (UML) | An Introduction Introduction of Programming Paradigms MVC Design Pattern Abstract Factory Pattern Monolithic vs Microservices architecture Composite Design Pattern Unified Modeling Language (UML) | Activity Diagrams Unified Modeling Language (UML) | State Diagrams
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Sep, 2021" }, { "code": null, "e": 309, "s": 52, "text": "Memento pattern is a behavioral design pattern. Memento pattern is used to restore state of an object to a previous state. As your application is progressing, you may want to save checkpoints in your application and restore back to those checkpoints later." }, { "code": null, "e": 344, "s": 309, "text": "UML Diagram Memento design pattern" }, { "code": null, "e": 362, "s": 344, "text": "Design components" }, { "code": null, "e": 476, "s": 362, "text": "originator : the object for which the state is to be saved. It creates the memento and uses it in future to undo." }, { "code": null, "e": 565, "s": 476, "text": "memento : the object that is going to maintain the state of originator. Its just a POJO." }, { "code": null, "e": 655, "s": 565, "text": "caretaker : the object that keeps track of multiple memento. Like maintaining savepoints." }, { "code": null, "e": 1295, "s": 655, "text": "A Caretaker would like to perform an operation on the Originator while having the possibility to rollback. The caretaker calls the createMemento() method on the originator asking the originator to pass it a memento object. At this point the originator creates a memento object saving its internal state and passes the memento to the caretaker. The caretaker maintains the memento object and performs the operation. In case of the need to undo the operation, the caretaker calls the setMemento() method on the originator passing the maintained memento object. The originator would accept the memento, using it to restore its previous state." }, { "code": null, "e": 1343, "s": 1295, "text": "Let’s see an example of Memento design pattern." }, { "code": "import java.util.List;import java.util.ArrayList; class Life{ private String time; public void set(String time) { System.out.println(\"Setting time to \" + time); this.time = time; } public Memento saveToMemento() { System.out.println(\"Saving time to Memento\"); return new Memento(time); } public void restoreFromMemento(Memento memento) { time = memento.getSavedTime(); System.out.println(\"Time restored from Memento: \" + time); } public static class Memento { private final String time; public Memento(String timeToSave) { time = timeToSave; } public String getSavedTime() { return time; } }} class Design { public static void main(String[] args) { List<Life.Memento> savedTimes = new ArrayList<Life.Memento>(); Life life = new Life(); //time travel and record the eras life.set(\"1000 B.C.\"); savedTimes.add(life.saveToMemento()); life.set(\"1000 A.D.\"); savedTimes.add(life.saveToMemento()); life.set(\"2000 A.D.\"); savedTimes.add(life.saveToMemento()); life.set(\"4000 A.D.\"); life.restoreFromMemento(savedTimes.get(0)); }}", "e": 2662, "s": 1343, "text": null }, { "code": null, "e": 2670, "s": 2662, "text": "Output:" }, { "code": null, "e": 2882, "s": 2670, "text": "Setting time to 1000 B.C.\nSaving time to Memento\nSetting time to 1000 A.D.\nSaving time to Memento\nSetting time to 2000 A.D.\nSaving time to Memento\nSetting time to 4000 A.D.\nTime restored from Memento: 1000 B.C.\n" }, { "code": null, "e": 2892, "s": 2882, "text": "Advantage" }, { "code": null, "e": 3080, "s": 2892, "text": "We can use Serialization to achieve memento pattern implementation that is more generic rather than Memento pattern where every object needs to have it’s own Memento class implementation." }, { "code": null, "e": 3093, "s": 3080, "text": "Disadvantage" }, { "code": null, "e": 3195, "s": 3093, "text": "If Originator object is very huge then Memento object size will also be huge and use a lot of memory." }, { "code": null, "e": 3235, "s": 3195, "text": "Further Read – Memento Method in Python" }, { "code": null, "e": 3530, "s": 3235, "text": "This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 3655, "s": 3530, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3670, "s": 3655, "text": "Design Pattern" }, { "code": null, "e": 3768, "s": 3670, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3806, "s": 3768, "text": "Factory method design pattern in Java" }, { "code": null, "e": 3829, "s": 3806, "text": "Builder Design Pattern" }, { "code": null, "e": 3879, "s": 3829, "text": "Unified Modeling Language (UML) | An Introduction" }, { "code": null, "e": 3917, "s": 3879, "text": "Introduction of Programming Paradigms" }, { "code": null, "e": 3936, "s": 3917, "text": "MVC Design Pattern" }, { "code": null, "e": 3961, "s": 3936, "text": "Abstract Factory Pattern" }, { "code": null, "e": 4002, "s": 3961, "text": "Monolithic vs Microservices architecture" }, { "code": null, "e": 4027, "s": 4002, "text": "Composite Design Pattern" }, { "code": null, "e": 4079, "s": 4027, "text": "Unified Modeling Language (UML) | Activity Diagrams" } ]
HTML | <li> value Attribute
30 Apr, 2019 The <li> value attribute in HTML is used to specify the initial value of the list item. It is only applicable on the ordered list. Syntax: <li value="number">list items </li> Attribute Value: This attribute contains single value number which is used to specify the value of the list items. Example 1: This example uses <li> value attribute to create list of items. <!DOCTYPE html><html> <head> <title> HTML list item value Attribute </title> </head> <body> <center> <h1 style = "color: green;"> GeeksforGeeks </h1> <h2> HTML list item value Attribute </h2> <p>Sorting Algorithms</p> </center> <ol style="margin-left:42%"> <li value="50">Merge sort</li> <li>Quick sort</li> <li>Insertion sort</li> </ol> </body></html> Output: Example 2: This example uses <li> value attribute to create list of items. <!DOCTYPE html><html> <head> <title> HTML li value Attribute </title> </head> <body> <h1 style = "color: green;"> GeeksforGeeks </h1> <h2> HTML li value Attribute </h2> <p>Sorting Algorithms</p> <ol type = "A"> <li value="6">Merge sort</li> <li>Quick sort</li> <li>Insertion sort</li> </ol> </body></html> Output: Supported Browsers: The browser supported by <li> value attribute are listed below: Apple Safari Google Chrome Firefox Opera Internet Explorer HTML-Attributes PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Apr, 2019" }, { "code": null, "e": 159, "s": 28, "text": "The <li> value attribute in HTML is used to specify the initial value of the list item. It is only applicable on the ordered list." }, { "code": null, "e": 167, "s": 159, "text": "Syntax:" }, { "code": null, "e": 203, "s": 167, "text": "<li value=\"number\">list items </li>" }, { "code": null, "e": 318, "s": 203, "text": "Attribute Value: This attribute contains single value number which is used to specify the value of the list items." }, { "code": null, "e": 393, "s": 318, "text": "Example 1: This example uses <li> value attribute to create list of items." }, { "code": "<!DOCTYPE html><html> <head> <title> HTML list item value Attribute </title> </head> <body> <center> <h1 style = \"color: green;\"> GeeksforGeeks </h1> <h2> HTML list item value Attribute </h2> <p>Sorting Algorithms</p> </center> <ol style=\"margin-left:42%\"> <li value=\"50\">Merge sort</li> <li>Quick sort</li> <li>Insertion sort</li> </ol> </body></html> ", "e": 1003, "s": 393, "text": null }, { "code": null, "e": 1011, "s": 1003, "text": "Output:" }, { "code": null, "e": 1086, "s": 1011, "text": "Example 2: This example uses <li> value attribute to create list of items." }, { "code": "<!DOCTYPE html><html> <head> <title> HTML li value Attribute </title> </head> <body> <h1 style = \"color: green;\"> GeeksforGeeks </h1> <h2> HTML li value Attribute </h2> <p>Sorting Algorithms</p> <ol type = \"A\"> <li value=\"6\">Merge sort</li> <li>Quick sort</li> <li>Insertion sort</li> </ol> </body></html> ", "e": 1589, "s": 1086, "text": null }, { "code": null, "e": 1597, "s": 1589, "text": "Output:" }, { "code": null, "e": 1681, "s": 1597, "text": "Supported Browsers: The browser supported by <li> value attribute are listed below:" }, { "code": null, "e": 1694, "s": 1681, "text": "Apple Safari" }, { "code": null, "e": 1708, "s": 1694, "text": "Google Chrome" }, { "code": null, "e": 1716, "s": 1708, "text": "Firefox" }, { "code": null, "e": 1722, "s": 1716, "text": "Opera" }, { "code": null, "e": 1740, "s": 1722, "text": "Internet Explorer" }, { "code": null, "e": 1756, "s": 1740, "text": "HTML-Attributes" }, { "code": null, "e": 1760, "s": 1756, "text": "PHP" }, { "code": null, "e": 1777, "s": 1760, "text": "Web Technologies" }, { "code": null, "e": 1781, "s": 1777, "text": "PHP" }, { "code": null, "e": 1879, "s": 1781, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1929, "s": 1879, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 1969, "s": 1929, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 2030, "s": 1969, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 2080, "s": 2030, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 2125, "s": 2080, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 2158, "s": 2125, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2220, "s": 2158, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2281, "s": 2220, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2331, "s": 2281, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
CSS | grid-template-columns Property
07 Jun, 2022 The grid-template-columns property in CSS is used to set the number of columns and size of the columns of the grid. This property accepts more than one values. The number of columns is set by the number of values given to this property. Syntax: grid-template-columns: none|auto|max-content|min-content|length| initial|inherit; Property Values: none: It is the default value of grid-template-columns property. The grid doesn’t contain any columns unless needed. Syntax: grid-template-columns: none; length: It sets the grid-template-columns property in length. The length can be set in form of px, em, percentage, etc specifies the size of the columns. Syntax: grid-template-columns: length; auto: The size of columns is set automatically based on the content and element size. Syntax: grid-template-columns: auto; min-content: It sets the size of column based on the largest minimum content size. Syntax: grid-template-columns: min-content; max-content: It sets the size of column based on the largest maximum content size. Syntax: grid-template-columns: max-content; initial: It sets the grid-template-columns property to default value. Syntax: grid-template-columns: initial; inherit: It sets the grid-template-columns property from its parent element. Syntax: grid-template-columns: inherit; Example 1: html <!DOCTYPE html><html> <head> <title> CSS grid-template-columns Property </title> <style> .geeks { background-color:green; padding:30px; display: grid; grid-template-columns: auto auto 200px 150px; grid-gap: 10px; } .GFG { background-color: white; border: 1px solid white; font-size: 30px; text-align: center; } </style> </head> <body> <div class="geeks"> <div class="GFG">A</div> <div class="GFG">B</div> <div class="GFG">C</div> <div class="GFG">D</div> <div class="GFG">E</div> <div class="GFG">F</div> <div class="GFG">G</div> <div class="GFG">H</div> </div> </body></html> Output: Example 2: html <!DOCTYPE html><html> <head> <title> CSS grid-template-columns Property </title> <style> .geeks { background-color:green; padding:30px; display: grid; grid-template-columns: min-content max-content 400px min-content; grid-gap: 10px; } .GFG { background-color: white; border: 1px solid white; font-size: 30px; text-align: center; } </style> </head> <body> <div class="geeks"> <div class="GFG">Geeks</div> <div class="GFG">GFG</div> <div class="GFG">C</div> <div class="GFG">D</div> <div class="GFG">E</div> <div class="GFG">F</div> <div class="GFG">G</div> <div class="GFG">H</div> </div> </body></html> Output: Supported Browsers: The browser supported by grid-template-columns property are listed below: Google Chrome 57.0 and above Edge 16.0 and above Internet Explorer 10.0 and above Firefox 52.0 and above Opera 44.0 and above Safari 10.1 and above kumargaurav97520 CSS-Properties Picked CSS 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": "\n07 Jun, 2022" }, { "code": null, "e": 266, "s": 28, "text": "The grid-template-columns property in CSS is used to set the number of columns and size of the columns of the grid. This property accepts more than one values. The number of columns is set by the number of values given to this property. " }, { "code": null, "e": 274, "s": 266, "text": "Syntax:" }, { "code": null, "e": 356, "s": 274, "text": "grid-template-columns: none|auto|max-content|min-content|length|\ninitial|inherit;" }, { "code": null, "e": 373, "s": 356, "text": "Property Values:" }, { "code": null, "e": 491, "s": 373, "text": "none: It is the default value of grid-template-columns property. The grid doesn’t contain any columns unless needed. " }, { "code": null, "e": 499, "s": 491, "text": "Syntax:" }, { "code": null, "e": 528, "s": 499, "text": "grid-template-columns: none;" }, { "code": null, "e": 683, "s": 528, "text": "length: It sets the grid-template-columns property in length. The length can be set in form of px, em, percentage, etc specifies the size of the columns. " }, { "code": null, "e": 691, "s": 683, "text": "Syntax:" }, { "code": null, "e": 722, "s": 691, "text": "grid-template-columns: length;" }, { "code": null, "e": 809, "s": 722, "text": "auto: The size of columns is set automatically based on the content and element size. " }, { "code": null, "e": 817, "s": 809, "text": "Syntax:" }, { "code": null, "e": 846, "s": 817, "text": "grid-template-columns: auto;" }, { "code": null, "e": 930, "s": 846, "text": "min-content: It sets the size of column based on the largest minimum content size. " }, { "code": null, "e": 938, "s": 930, "text": "Syntax:" }, { "code": null, "e": 974, "s": 938, "text": "grid-template-columns: min-content;" }, { "code": null, "e": 1058, "s": 974, "text": "max-content: It sets the size of column based on the largest maximum content size. " }, { "code": null, "e": 1066, "s": 1058, "text": "Syntax:" }, { "code": null, "e": 1102, "s": 1066, "text": "grid-template-columns: max-content;" }, { "code": null, "e": 1173, "s": 1102, "text": "initial: It sets the grid-template-columns property to default value. " }, { "code": null, "e": 1181, "s": 1173, "text": "Syntax:" }, { "code": null, "e": 1213, "s": 1181, "text": "grid-template-columns: initial;" }, { "code": null, "e": 1291, "s": 1213, "text": "inherit: It sets the grid-template-columns property from its parent element. " }, { "code": null, "e": 1299, "s": 1291, "text": "Syntax:" }, { "code": null, "e": 1331, "s": 1299, "text": "grid-template-columns: inherit;" }, { "code": null, "e": 1343, "s": 1331, "text": "Example 1: " }, { "code": null, "e": 1348, "s": 1343, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS grid-template-columns Property </title> <style> .geeks { background-color:green; padding:30px; display: grid; grid-template-columns: auto auto 200px 150px; grid-gap: 10px; } .GFG { background-color: white; border: 1px solid white; font-size: 30px; text-align: center; } </style> </head> <body> <div class=\"geeks\"> <div class=\"GFG\">A</div> <div class=\"GFG\">B</div> <div class=\"GFG\">C</div> <div class=\"GFG\">D</div> <div class=\"GFG\">E</div> <div class=\"GFG\">F</div> <div class=\"GFG\">G</div> <div class=\"GFG\">H</div> </div> </body></html> ", "e": 2290, "s": 1348, "text": null }, { "code": null, "e": 2298, "s": 2290, "text": "Output:" }, { "code": null, "e": 2313, "s": 2301, "text": "Example 2: " }, { "code": null, "e": 2318, "s": 2313, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS grid-template-columns Property </title> <style> .geeks { background-color:green; padding:30px; display: grid; grid-template-columns: min-content max-content 400px min-content; grid-gap: 10px; } .GFG { background-color: white; border: 1px solid white; font-size: 30px; text-align: center; } </style> </head> <body> <div class=\"geeks\"> <div class=\"GFG\">Geeks</div> <div class=\"GFG\">GFG</div> <div class=\"GFG\">C</div> <div class=\"GFG\">D</div> <div class=\"GFG\">E</div> <div class=\"GFG\">F</div> <div class=\"GFG\">G</div> <div class=\"GFG\">H</div> </div> </body></html> ", "e": 3301, "s": 2318, "text": null }, { "code": null, "e": 3309, "s": 3301, "text": "Output:" }, { "code": null, "e": 3406, "s": 3312, "text": "Supported Browsers: The browser supported by grid-template-columns property are listed below:" }, { "code": null, "e": 3435, "s": 3406, "text": "Google Chrome 57.0 and above" }, { "code": null, "e": 3455, "s": 3435, "text": "Edge 16.0 and above" }, { "code": null, "e": 3488, "s": 3455, "text": "Internet Explorer 10.0 and above" }, { "code": null, "e": 3511, "s": 3488, "text": "Firefox 52.0 and above" }, { "code": null, "e": 3532, "s": 3511, "text": "Opera 44.0 and above" }, { "code": null, "e": 3554, "s": 3532, "text": "Safari 10.1 and above" }, { "code": null, "e": 3571, "s": 3554, "text": "kumargaurav97520" }, { "code": null, "e": 3586, "s": 3571, "text": "CSS-Properties" }, { "code": null, "e": 3593, "s": 3586, "text": "Picked" }, { "code": null, "e": 3597, "s": 3593, "text": "CSS" }, { "code": null, "e": 3614, "s": 3597, "text": "Web Technologies" } ]
HTML | DOM Input Number placeholder Property
11 Mar, 2019 The DOM Input Number placeholder Property in HTML DOM is used to set or return the value of the placeholder attribute of a number field. The placeholder attribute specifies the short hint that describes the expected value of an input field. The short hint is displayed in the field before the user enters a value. Syntax: It returns the Input number Placeholder property.numberObject.placeholder numberObject.placeholder It is used to set Input number Placeholder property.numberObject.placeholder = text numberObject.placeholder = text Property Value: It contains single value text which is used to define a short hint that describes an expected value of the number Field. Return Value: It returns a string value which represented a short hint that describes the expected value of the number Field. Example 1: This example illustrates how to return Input number Placeholder property. <!DOCTYPE html> <html> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2>DOM Input Number placeholder Property</h2> <input type="number" id="myNumber" step="5" placeholder="multiples of 5" > <br><br> <button onclick="myFunction()"> Click Here! </button> <p id="demo" style="font-size:23px;color:green;"></p> <script> function myFunction() { // Accessing input value var x = document.getElementById("myNumber").placeholder; document.getElementById("demo").innerHTML = x; } </script> </body> </html> Output:Before Clicking On Button:After Clicking On Button:Example-2: This Example illustrates how to set the Input number placeholder Property. <!DOCTYPE html> <html> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2>DOM Input Number placeholder Property</h2> <input type="number" id="myNumber" step="5" placeholder="multiples of 5" > <br><br> <button onclick="myFunction()"> Click Here! </button> <p id="demo" style="font-size:23px;color:green;"></p> <script> function myFunction() { // Accessing input value var x = document.getElementById("myNumber").placeholder = "10"; document.getElementById("demo").innerHTML = "The value of the placeholder attribute was changed to " + x; } </script> </body> </html> Output :Before Clicking On Button :After Clicking On Button : Supported Browsers: The browser supported by DOM input number placeholderProperty are listed below: Google Chrome Internet Explorer 10.0 + Firefox Opera Safari HTML-DOM HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) CSS to put icon inside an input element in a form Design a Tribute Page using HTML & CSS Types of CSS (Cascading Style Sheet) Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Mar, 2019" }, { "code": null, "e": 367, "s": 53, "text": "The DOM Input Number placeholder Property in HTML DOM is used to set or return the value of the placeholder attribute of a number field. The placeholder attribute specifies the short hint that describes the expected value of an input field. The short hint is displayed in the field before the user enters a value." }, { "code": null, "e": 375, "s": 367, "text": "Syntax:" }, { "code": null, "e": 449, "s": 375, "text": "It returns the Input number Placeholder property.numberObject.placeholder" }, { "code": null, "e": 474, "s": 449, "text": "numberObject.placeholder" }, { "code": null, "e": 558, "s": 474, "text": "It is used to set Input number Placeholder property.numberObject.placeholder = text" }, { "code": null, "e": 590, "s": 558, "text": "numberObject.placeholder = text" }, { "code": null, "e": 727, "s": 590, "text": "Property Value: It contains single value text which is used to define a short hint that describes an expected value of the number Field." }, { "code": null, "e": 853, "s": 727, "text": "Return Value: It returns a string value which represented a short hint that describes the expected value of the number Field." }, { "code": null, "e": 938, "s": 853, "text": "Example 1: This example illustrates how to return Input number Placeholder property." }, { "code": "<!DOCTYPE html> <html> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2>DOM Input Number placeholder Property</h2> <input type=\"number\" id=\"myNumber\" step=\"5\" placeholder=\"multiples of 5\" > <br><br> <button onclick=\"myFunction()\"> Click Here! </button> <p id=\"demo\" style=\"font-size:23px;color:green;\"></p> <script> function myFunction() { // Accessing input value var x = document.getElementById(\"myNumber\").placeholder; document.getElementById(\"demo\").innerHTML = x; } </script> </body> </html> ", "e": 1719, "s": 938, "text": null }, { "code": null, "e": 1863, "s": 1719, "text": "Output:Before Clicking On Button:After Clicking On Button:Example-2: This Example illustrates how to set the Input number placeholder Property." }, { "code": "<!DOCTYPE html> <html> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2>DOM Input Number placeholder Property</h2> <input type=\"number\" id=\"myNumber\" step=\"5\" placeholder=\"multiples of 5\" > <br><br> <button onclick=\"myFunction()\"> Click Here! </button> <p id=\"demo\" style=\"font-size:23px;color:green;\"></p> <script> function myFunction() { // Accessing input value var x = document.getElementById(\"myNumber\").placeholder = \"10\"; document.getElementById(\"demo\").innerHTML = \"The value of the placeholder attribute was changed to \" + x; } </script> </body> </html> ", "e": 2725, "s": 1863, "text": null }, { "code": null, "e": 2787, "s": 2725, "text": "Output :Before Clicking On Button :After Clicking On Button :" }, { "code": null, "e": 2887, "s": 2787, "text": "Supported Browsers: The browser supported by DOM input number placeholderProperty are listed below:" }, { "code": null, "e": 2901, "s": 2887, "text": "Google Chrome" }, { "code": null, "e": 2926, "s": 2901, "text": "Internet Explorer 10.0 +" }, { "code": null, "e": 2934, "s": 2926, "text": "Firefox" }, { "code": null, "e": 2940, "s": 2934, "text": "Opera" }, { "code": null, "e": 2947, "s": 2940, "text": "Safari" }, { "code": null, "e": 2956, "s": 2947, "text": "HTML-DOM" }, { "code": null, "e": 2961, "s": 2956, "text": "HTML" }, { "code": null, "e": 2978, "s": 2961, "text": "Web Technologies" }, { "code": null, "e": 2983, "s": 2978, "text": "HTML" }, { "code": null, "e": 3081, "s": 2983, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3129, "s": 3081, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3153, "s": 3129, "text": "REST API (Introduction)" }, { "code": null, "e": 3203, "s": 3153, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 3242, "s": 3203, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3279, "s": 3242, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 3312, "s": 3279, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3373, "s": 3312, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3416, "s": 3373, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 3488, "s": 3416, "text": "Differences between Functional Components and Class Components in React" } ]
C++ Program to Implement Set_Difference in STL
The difference of two sets is formed only by the elements that are present in the first set, not in the second set. The elements copied by the function come always from the first set in the same order. The elements in both the sets shall already be ordered. Common set operations are − Set Union Set Intersection Symmetric Set Difference or Exclusive-OR Set Difference or Subtraction Begin Declare set vector v and iterator st. Initialize st = set_difference (set1, set1 + n, set2, set2 +n, v.begin())) Print the number of elements different between two sets. End. #include<iostream> #include <algorithm> #include <vector> using namespace std; int main () { int set1[] = {5,6,7,8,9,10}; int set2[] = {1,2,3,4,6,7}; vector<int> v(10); vector<int>::iterator it; sort (set1, set1 + 6); sort (set2, set2 + 6); it = set_difference(set1, set1 + 6, set2, set2 + 6, v.begin()); v.resize(it - v.begin()); cout << "The difference between the sets has " << (v.size()) << " elements: "<<endl; for (it = v.begin(); it != v.end(); ++it) cout<< *it<<" "; cout <<endl; return 0; } The difference between the sets has 4 elements 5,8,9,10
[ { "code": null, "e": 1320, "s": 1062, "text": "The difference of two sets is formed only by the elements that are present in the first set, not in the second set. The elements copied by the function come always from the first set in the same order. The elements in both the sets shall already be ordered." }, { "code": null, "e": 1348, "s": 1320, "text": "Common set operations are −" }, { "code": null, "e": 1358, "s": 1348, "text": "Set Union" }, { "code": null, "e": 1375, "s": 1358, "text": "Set Intersection" }, { "code": null, "e": 1416, "s": 1375, "text": "Symmetric Set Difference or Exclusive-OR" }, { "code": null, "e": 1446, "s": 1416, "text": "Set Difference or Subtraction" }, { "code": null, "e": 1636, "s": 1446, "text": "Begin\n Declare set vector v and iterator st.\n Initialize st = set_difference (set1, set1 + n, set2, set2 +n, v.begin()))\n Print the number of elements different between two sets.\nEnd." }, { "code": null, "e": 2181, "s": 1636, "text": "#include<iostream>\n#include <algorithm>\n#include <vector>\nusing namespace std;\nint main () {\n int set1[] = {5,6,7,8,9,10};\n int set2[] = {1,2,3,4,6,7};\n vector<int> v(10);\n vector<int>::iterator it;\n sort (set1, set1 + 6);\n sort (set2, set2 + 6);\n it = set_difference(set1, set1 + 6, set2, set2 + 6, v.begin());\n v.resize(it - v.begin());\n cout << \"The difference between the sets has \" << (v.size()) << \" elements: \"<<endl;\n for (it = v.begin(); it != v.end(); ++it)\n cout<< *it<<\" \";\n cout <<endl;\n return 0;\n}" }, { "code": null, "e": 2237, "s": 2181, "text": "The difference between the sets has 4 elements\n5,8,9,10" } ]
Find the first non-repeating character from a stream of characters in Python
Suppose we have a stream of characters, or we can consider a string and we have to find the first non-repeating character in the string. So, if the string is like “people”, the first letter whose occurrence is one is ‘o’. So, the index will be returned, that is 2 here. If there is no such character, then return -1. To solve this, we will follow these steps − create one frequency map create one frequency map for each character c in string, doif c is not in frequency, then insert it into frequency, and put value 1otherwise increase the count in frequency for each character c in string, do if c is not in frequency, then insert it into frequency, and put value 1 if c is not in frequency, then insert it into frequency, and put value 1 otherwise increase the count in frequency otherwise increase the count in frequency Scan the frequency map, if the value of specific key is 1, then return that key, otherwise return -1 Scan the frequency map, if the value of specific key is 1, then return that key, otherwise return -1 Let us see the following implementation to get better understanding − Live Demo class Solution(object): def firstUniqChar(self, s): """ :type s: str :rtype: int """ frequency = {} for i in s: if i not in frequency: frequency[i] = 1 else: frequency[i] +=1 for i in range(len(s)): if frequency[s[i]] == 1: return i return -1 ob1 = Solution() print(ob1.firstUniqChar("people")) print(ob1.firstUniqChar("abaabba")) "people" "abaabba" Output 2 -1
[ { "code": null, "e": 1379, "s": 1062, "text": "Suppose we have a stream of characters, or we can consider a string and we have to find the first non-repeating character in the string. So, if the string is like “people”, the first letter whose occurrence is one is ‘o’. So, the index will be returned, that is 2 here. If there is no such character, then return -1." }, { "code": null, "e": 1423, "s": 1379, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1448, "s": 1423, "text": "create one frequency map" }, { "code": null, "e": 1473, "s": 1448, "text": "create one frequency map" }, { "code": null, "e": 1621, "s": 1473, "text": "for each character c in string, doif c is not in frequency, then insert it into frequency, and put value 1otherwise increase the count in frequency" }, { "code": null, "e": 1656, "s": 1621, "text": "for each character c in string, do" }, { "code": null, "e": 1729, "s": 1656, "text": "if c is not in frequency, then insert it into frequency, and put value 1" }, { "code": null, "e": 1802, "s": 1729, "text": "if c is not in frequency, then insert it into frequency, and put value 1" }, { "code": null, "e": 1844, "s": 1802, "text": "otherwise increase the count in frequency" }, { "code": null, "e": 1886, "s": 1844, "text": "otherwise increase the count in frequency" }, { "code": null, "e": 1987, "s": 1886, "text": "Scan the frequency map, if the value of specific key is 1, then return that key, otherwise return -1" }, { "code": null, "e": 2088, "s": 1987, "text": "Scan the frequency map, if the value of specific key is 1, then return that key, otherwise return -1" }, { "code": null, "e": 2158, "s": 2088, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2169, "s": 2158, "text": " Live Demo" }, { "code": null, "e": 2614, "s": 2169, "text": "class Solution(object):\n def firstUniqChar(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n frequency = {}\n for i in s:\n if i not in frequency:\n frequency[i] = 1\n else:\n frequency[i] +=1\n for i in range(len(s)):\n if frequency[s[i]] == 1:\n return i\n return -1\nob1 = Solution()\nprint(ob1.firstUniqChar(\"people\"))\nprint(ob1.firstUniqChar(\"abaabba\"))" }, { "code": null, "e": 2633, "s": 2614, "text": "\"people\"\n\"abaabba\"" }, { "code": null, "e": 2640, "s": 2633, "text": "Output" }, { "code": null, "e": 2645, "s": 2640, "text": "2\n-1" } ]
Does main() method accept arguments other than string array, in java?
The public static void main() method accepts an array of values of the type String Java from the user. public class{ public static void main(String[] args){ } } You can pass them at the time of execution right after the class name separated with spaces as − java ClassName 10 20 30 And, in the program (from the main method) you can extract these values from the String array and use. For example, you can use command line arguments to pass a and b in the above program as − public class Sample { public static void main(String[] args){ int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int c = a+b; System.out.println("Sum of the two numbers is "+c); } } You can compile and, run the program by passing the values at execution line through command prompt as shown below − You can write the public static void main() method with arguments other than String the program gets compiled. Since the main method is the entry point of the Java program, whenever you execute one the JVM searches for the main method, which is public, static, with return type void, and a String array as an argument. Public static void main(String args[]){ } If anything is missing the JVM raises an error. Therefore, if you write a method with other data types (except String array) as arguments, at the time of execution, JVM does not consider this new method as the entry point of Java and generates an error. In the following Java program, we are trying to use an integer array as arguments of the main method. Live Demo public class MainExample { public static void main(int args[]) { System.out.println("Hello how are you"); } } On executing, this program generates the following error − Error: Main method not found in class MainMethodExample, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
[ { "code": null, "e": 1165, "s": 1062, "text": "The public static void main() method accepts an array of values of the type String Java from the user." }, { "code": null, "e": 1229, "s": 1165, "text": "public class{\n public static void main(String[] args){\n }\n}" }, { "code": null, "e": 1326, "s": 1229, "text": "You can pass them at the time of execution right after the class name separated with spaces as −" }, { "code": null, "e": 1350, "s": 1326, "text": "java ClassName 10 20 30" }, { "code": null, "e": 1453, "s": 1350, "text": "And, in the program (from the main method) you can extract these values from the String array and use." }, { "code": null, "e": 1543, "s": 1453, "text": "For example, you can use command line arguments to pass a and b in the above program as −" }, { "code": null, "e": 1774, "s": 1543, "text": "public class Sample {\n public static void main(String[] args){\n int a = Integer.parseInt(args[0]);\n int b = Integer.parseInt(args[1]);\n int c = a+b;\n System.out.println(\"Sum of the two numbers is \"+c);\n }\n}" }, { "code": null, "e": 1891, "s": 1774, "text": "You can compile and, run the program by passing the values at execution line through command prompt as shown below −" }, { "code": null, "e": 2002, "s": 1891, "text": "You can write the public static void main() method with arguments other than String the program gets compiled." }, { "code": null, "e": 2210, "s": 2002, "text": "Since the main method is the entry point of the Java program, whenever you execute one the JVM searches for the main method, which is public, static, with return type void, and a String array as an argument." }, { "code": null, "e": 2252, "s": 2210, "text": "Public static void main(String args[]){\n}" }, { "code": null, "e": 2506, "s": 2252, "text": "If anything is missing the JVM raises an error. Therefore, if you write a method with other data types (except String array) as arguments, at the time of execution, JVM does not consider this new method as the entry point of Java and generates an error." }, { "code": null, "e": 2608, "s": 2506, "text": "In the following Java program, we are trying to use an integer array as arguments of the main method." }, { "code": null, "e": 2619, "s": 2608, "text": " Live Demo" }, { "code": null, "e": 2741, "s": 2619, "text": "public class MainExample {\n public static void main(int args[]) {\n System.out.println(\"Hello how are you\");\n }\n}" }, { "code": null, "e": 2800, "s": 2741, "text": "On executing, this program generates the following error −" }, { "code": null, "e": 3003, "s": 2800, "text": "Error: Main method not found in class MainMethodExample, please define the main\nmethod as:\npublic static void main(String[] args)\nor a JavaFX application class must extend javafx.application.Application" } ]
Apache Flink - Libraries
In this chapter, we will learn about the different libraries of Apache Flink. FlinkCEP is an API in Apache Flink, which analyses event patterns on continuous streaming data. These events are near real time, which have high throughput and low latency. This API is used mostly on Sensor data, which come in real-time and are very complex to process. CEP analyses the pattern of the input stream and gives the result very soon. It has the ability to provide real-time notifications and alerts in case the event pattern is complex. FlinkCEP can connect to different kind of input sources and analyse patterns in them. This how a sample architecture with CEP looks like − Sensor data will be coming in from different sources, Kafka will act as a distributed messaging framework, which will distribute the streams to Apache Flink, and FlinkCEP will analyse the complex event patterns. You can write programs in Apache Flink for complex event processing using Pattern API. It allows you to decide the event patterns to detect from the continuous stream data. Below are some of the most commonly used CEP patterns − It is used to define the starting state. The following program shows how it is defined in a Flink program − Pattern<Event, ?> next = start.next("next"); It is used to define a filter condition in the current state. patternState.where(new FilterFunction <Event>() { @Override public boolean filter(Event value) throws Exception { } }); It is used to append a new pattern state and the matching event needed to pass the previous pattern. Pattern<Event, ?> next = start.next("next"); It is used to append a new pattern state but here other events can occur b/w two matching events. Pattern<Event, ?> followedBy = start.followedBy("next"); Apache Flink's Graph API is Gelly. Gelly is used to perform graph analysis on Flink applications using a set of methods and utilities. You can analyse huge graphs using Apache Flink API in a distributed fashion with Gelly. There are other graph libraries also like Apache Giraph for the same purpose, but since Gelly is used on top of Apache Flink, it uses single API. This is very helpful from development and operation point of view. Let us run an example using Apache Flink API − Gelly. Firstly, you need to copy 2 Gelly jar files from opt directory of Apache Flink to its lib directory. Then run flink-gelly-examples jar. cp opt/flink-gelly* lib/ ./bin/flink run examples/gelly/flink-gelly-examples_*.jar Let us now run the PageRank example. PageRank computes a per-vertex score, which is the sum of PageRank scores transmitted over in-edges. Each vertex's score is divided evenly among out-edges. High-scoring vertices are linked to by other high-scoring vertices. The result contains the vertex ID and the PageRank score. usage: flink run examples/flink-gelly-examples_<version>.jar --algorithm PageRank [algorithm options] --input <input> [input options] --output <output> [output options] ./bin/flink run examples/gelly/flink-gelly-examples_*.jar --algorithm PageRank --input CycleGraph --vertex_count 2 --output Print 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": 2147, "s": 2069, "text": "In this chapter, we will learn about the different libraries of Apache Flink." }, { "code": null, "e": 2417, "s": 2147, "text": "FlinkCEP is an API in Apache Flink, which analyses event patterns on continuous streaming data. These events are near real time, which have high throughput and low latency. This API is used mostly on Sensor data, which come in real-time and are very complex to process." }, { "code": null, "e": 2683, "s": 2417, "text": "CEP analyses the pattern of the input stream and gives the result very soon. It has the ability to provide real-time notifications and alerts in case the event pattern is complex. FlinkCEP can connect to different kind of input sources and analyse patterns in them." }, { "code": null, "e": 2736, "s": 2683, "text": "This how a sample architecture with CEP looks like −" }, { "code": null, "e": 2948, "s": 2736, "text": "Sensor data will be coming in from different sources, Kafka will act as a distributed messaging framework, which will distribute the streams to Apache Flink, and FlinkCEP will analyse the complex event patterns." }, { "code": null, "e": 3177, "s": 2948, "text": "You can write programs in Apache Flink for complex event processing using Pattern API. It allows you to decide the event patterns to detect from the continuous stream data. Below are some of the most commonly used CEP patterns −" }, { "code": null, "e": 3285, "s": 3177, "text": "It is used to define the starting state. The following program shows how it is defined in a Flink program −" }, { "code": null, "e": 3331, "s": 3285, "text": "Pattern<Event, ?> next = start.next(\"next\");\n" }, { "code": null, "e": 3393, "s": 3331, "text": "It is used to define a filter condition in the current state." }, { "code": null, "e": 3531, "s": 3393, "text": "patternState.where(new FilterFunction <Event>() { \n @Override \n public boolean filter(Event value) throws Exception { \n } \n});\n" }, { "code": null, "e": 3632, "s": 3531, "text": "It is used to append a new pattern state and the matching event needed to pass the previous pattern." }, { "code": null, "e": 3678, "s": 3632, "text": "Pattern<Event, ?> next = start.next(\"next\");\n" }, { "code": null, "e": 3776, "s": 3678, "text": "It is used to append a new pattern state but here other events can occur b/w two matching events." }, { "code": null, "e": 3834, "s": 3776, "text": "Pattern<Event, ?> followedBy = start.followedBy(\"next\");\n" }, { "code": null, "e": 4270, "s": 3834, "text": "Apache Flink's Graph API is Gelly. Gelly is used to perform graph analysis on Flink applications using a set of methods and utilities. You can analyse huge graphs using Apache Flink API in a distributed fashion with Gelly. There are other graph libraries also like Apache Giraph for the same purpose, but since Gelly is used on top of Apache Flink, it uses single API. This is very helpful from development and operation point of view." }, { "code": null, "e": 4325, "s": 4270, "text": "Let us run an example using Apache Flink API − Gelly." }, { "code": null, "e": 4461, "s": 4325, "text": "Firstly, you need to copy 2 Gelly jar files from opt directory of Apache Flink to its lib directory. Then run flink-gelly-examples jar." }, { "code": null, "e": 4547, "s": 4461, "text": "cp opt/flink-gelly* lib/ \n./bin/flink run examples/gelly/flink-gelly-examples_*.jar \n" }, { "code": null, "e": 4584, "s": 4547, "text": "Let us now run the PageRank example." }, { "code": null, "e": 4808, "s": 4584, "text": "PageRank computes a per-vertex score, which is the sum of PageRank scores transmitted over in-edges. Each vertex's score is divided evenly among out-edges. High-scoring vertices are linked to by other high-scoring vertices." }, { "code": null, "e": 4866, "s": 4808, "text": "The result contains the vertex ID and the PageRank score." }, { "code": null, "e": 5169, "s": 4866, "text": "usage: flink run examples/flink-gelly-examples_<version>.jar --algorithm PageRank [algorithm options] --input <input> [input options] --output <output> [output options] \n\n./bin/flink run examples/gelly/flink-gelly-examples_*.jar --algorithm PageRank --input CycleGraph --vertex_count 2 --output Print \n" }, { "code": null, "e": 5204, "s": 5169, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5223, "s": 5204, "text": " Arnab Chakraborty" }, { "code": null, "e": 5258, "s": 5223, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5279, "s": 5258, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 5312, "s": 5279, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 5325, "s": 5312, "text": " Nilay Mehta" }, { "code": null, "e": 5360, "s": 5325, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5378, "s": 5360, "text": " Bigdata Engineer" }, { "code": null, "e": 5411, "s": 5378, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 5429, "s": 5411, "text": " Bigdata Engineer" }, { "code": null, "e": 5462, "s": 5429, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 5480, "s": 5462, "text": " Bigdata Engineer" }, { "code": null, "e": 5487, "s": 5480, "text": " Print" }, { "code": null, "e": 5498, "s": 5487, "text": " Add Notes" } ]
The Secret Guide To Human-Like Text Summarization | by Louis Teo | Medium | Towards Data Science
Summarization has become a very helpful way of tackling the issue of data overburden. In my earlier story, I shared how you can create your personal text summarizer using extractive method — if you have tried that, you may have noticed that, because no new sentences were generated from the original content, at times you may have difficulties understanding the generated extractive summary. In this story, I will share how I use Google’s T5 (Text-to-Text Transfer Transformer) model to create a human-like summarizer with just a few lines of codes! As a bonus, I will also share my text summarizer pipelines where I combine both extractive and abstractive methods to generate meaningful summaries for PDF documents of any length... There are two techniques to summarize a long content: i. Extractive summary — extracts important sentences from a long content. ii. Abstractive summary — creates a summary by generating new sentences from an original content. Abstractive summary is a comparatively more difficult technique as it involves deep learning, but thanks to Google’s pre-trained models that are made available to public, creating a meaningful abstractive summary is no longer a daunting machine learning task! You can build simple yet incredibly powerful abstractive text summarizer using Google’ T5 pre-trained model. I will use HuggingFace’s state-of-the-art Transformers framework and PyTorch to build a summarizer. Install packages Please ensure you have both Python packages installed. pip install torchpip install transformers Load model and tokenizer Load T5’s pre-trained model and its tokenizer. import torchfrom transformers import AutoTokenizer, AutoModelForSeq2SeqLMmodel = AutoModelForSeq2SeqLM.from_pretrained('t5-base')tokenizer = AutoTokenizer.from_pretrained('t5-base') There are a total of five T5 models to choose from: t5-small, t5-base, t5-large, t-3B & t5–11B. They each have different parameters. I will choose the ‘t5-base’ model, which has a total of 220 millions parameters. Feel free to try different T5 models. Input text Let’s load a CNN news article about ‘Netflix needs a Next Big Thing’ — simply because this is rather interesting business news — and see how well our summarizer performs. text = """New York (CNN Business)Netflix is synonymous with streaming, but its competitors have a distinct advantage that threatens the streaming leader's position at the top.Disney has Disney+, but it also has theme parks, plush Baby Yoda dolls, blockbuster Marvel movies and ESPN. Comcast (CMCSA), Amazon (AMZN), ViacomCBS (VIACA), CNN's parent company WarnerMedia and Apple (AAPL) all have their own streaming services, too, but they also have other forms of revenue.As for Netflix (NFLX), its revenue driver is based entirely on building its subscriber base. It's worked out well for the company — so far. But it's starting to look like the king of streaming will soon need something other than new subscribers to keep growing.The streaming service reported Tuesday it now has 208 million subscribers globally, after adding 4 million subscribers in the first quarter of 2021. But that number missed expectations and the forecasts for its next quarter were also pretty weak.That was a big whiff for Netflix — a company coming off a massive year of growth thanks in large part to the pandemic driving people indoors — and Wall Street's reaction has not been great.The company's stock dropped as much as 8% on Wednesday, leading some to wonder what the future of the streamer looks like if competition continues to gain strength, people start heading outdoors and if, most importantly, its growth slows."If you hit a wall with [subscriptions] then you pretty much don't have a super growth strategy anymore in your most developed markets," Michael Nathanson, a media analyst and founding partner at MoffettNathanson, told CNN Business. "What can they do to take even more revenue out of the market, above and beyond streaming revenues?"Or put another way, the company's lackluster user growth last quarter is a signal that it wouldn't hurt if Netflix — a company that's lived and died with its subscriber numbers — started thinking about other ways to make money.An ad-supported Netflix? Not so fastThere are ways for Netflix to make money other than raising prices or adding subscribers. The most obvious: selling advertising.Netflix could have 30-second commercials on their programming or get sponsors for their biggest series and films. TV has worked that way forever, why not Netflix?That's probably not going to happen, given that CEO Reed Hastings has been vocal about the unlikelihood of an ad-supported Netflix service. His reasoning: It doesn't make business sense."It's a judgment call... It's a belief we can build a better business, a more valuable business [without advertising]," Hastings told Variety in September. "You know, advertising looks easy until you get in it. Then you realize you have to rip that revenue away from other places because the total ad market isn't growing, and in fact right now it's shrinking. It's hand-to-hand combat to get people to spend less on, you know, ABC and to spend more on Netflix."Hastings added that "there's much more growth in the consumer market than there is in advertising, which is pretty flat."He's also expressed doubts about Netflix getting into live sports or news, which could boost the service's allure to subscribers, so that's likely out, too, at least for now.So if Netflix is looking for other forms of near-term revenue to help support its hefty content budget ($17 billion in 2021 alone) then what can it do? There is one place that could be a revenue driver for Netflix, but if you're borrowing your mother's account you won't like it.Netflix could crack down on password sharing — a move that the company has been considering lately."Basically you're going to clean up some subscribers that are free riders," Nathanson said. "That's going to help them get to a higher level of penetration, definitely, but not in long-term."Lackluster growth is still growthMissing projections is never good, but it's hardly the end of the world for Netflix. The company remains the market leader and most competitors are still far from taking the company on. And while Netflix's first-quarter subscriber growth wasn't great, and its forecasts for the next quarter alarmed investors, it was just one quarter.Netflix has had subscriber misses before and it's still the most dominant name in all of streaming, and even lackluster growth is still growth. It's not as if people are canceling Netflix in droves.Asked about Netflix's "second act" during the company's post-earnings call on Tuesday, Hastings again placed the company's focus on pleasing subscribers."We do want to expand. We used to do that thing shipping DVDs, and luckily we didn't get stuck with that. We didn't define that as the main thing. We define entertainment as the main thing," Hastings said.He added that he doesn't think Netflix will have a second act in the way Amazon has had with Amazon shopping and Amazon Web Services. Rather, Netflix will continue to improve and grow on what it already does best."I'll bet we end with one hopefully gigantic, hopefully defensible profit pool, and continue to improve the service for our members," he said. "I wouldn't look for any large secondary pool of profits. There will be a bunch of supporting pools, like consumer products, that can be both profitable and can support the title brands."""" Tokenize Text T5 can be used to perform other tasks, such as text generation, translation, etc.; adding T5 specific prefix “summarize: ” will tell the model to perform the summarizing task. tokens_input = tokenizer.encode("summarize: " + text, return_tensors='pt', max_length=tokenizer.model_max_length, truncation=True) Here we will tokenize our text to the model’s maximum acceptable token input length. If the tokenized input exceeds the model’s maximum token length, it will be truncated. Generate Summary Let’s generate a summary by passing in the encoded tokens and then decode the generated summary back to text. summary_ids = model.generate(tokens_input, min_length=80, max_length=150, length_penalty=15, num_beams=2)summary = tokenizer.decode(summary_ids[0], skip_special_tokens=True) The model takes encoded tokens and the following input arguments: min_length: minimum length of sentences. max_length: maximum length of sentences. length_penalty: value > 1 forces the model to generate a longer summary, value < 1 forces the model to generate a shorter summary. num_beams: value 2 allows the model to explore tokens that generate more promising predictions. Note: Keeping the minimum and maximum sentence lengths between 80 and 150 and a length penalty of 15 will allow the model to generate a reasonable summary of 60 to 90 words. We will use the default values for the rest of input arguments (not shown above). Output Summary Netflix (NFLX) reported Tuesday it now has 208 million subscribers globally. that number missed expectations and the forecasts for its next quarter were also pretty weak. the streaming service's stock dropped as much as 8% on Wednesday, leading some to wonder what the future of the streamer looks like. if competition continues to gain strength, people start heading outdoors and if, most importantly, its growth slows, it wouldn't hurt if Netflix started thinking about other ways to make money - like selling ads. Wow! It looks like a pretty decent summary. ...but if you read the full text and read the summary again, you will notice that the latter part of the full text did not get summarized — this is because the tokenized input get truncated after it exceeds the maximum model token input length of 512. If you are worried about missing out some important details in the latter text, you can use a simple trick to solve the issue: perform extractive summarization to the original text first, followed by abstractive summarization. Before we proceed, make sure you have pip installed BERT extractive summarizer on your terminal. pip install bert-extractive-summarizer BERT stands for Bidirectional Encoder Representations from Transformers. It’s a Transformer-based machine learning technique for Natural Language Processing (NLP) developed by Google. It uses a powerful flat architecture with inter sentence transform layers to get the best result in summarization. from summarizer import Summarizerbert_model = Summarizer()ext_summary = bert_model(text, ratio=0.5) Below is the extractive summary generated by BERT. I purposely set it to produce a summary that is 50% in length of the original text by setting the summary ratio to 0.5. Feel free to use a different ratio to adjust your long document to the appropriate length. New York (CNN Business)Netflix is synonymous with streaming, but its competitors have a distinct advantage that threatens the streaming leader's position at the top. Disney has Disney+, but it also has theme parks, plush Baby Yoda dolls, blockbuster Marvel movies and ESPN. It's worked out well for the company - so far. But that number missed expectations and the forecasts for its next quarter were also pretty weak. Or put another way, the company's lackluster user growth last quarter is a signal that it wouldn't hurt if Netflix - a company that's lived and died with its subscriber numbers - started thinking about other ways to make money. Not so fastThere are ways for Netflix to make money other than raising prices or adding subscribers. His reasoning: It doesn't make business sense. "It's a judgment call... It's a belief we can build a better business, a more valuable business [without advertising]," Hastings told Variety in September. " You know, advertising looks easy until you get in it. Then you realize you have to rip that revenue away from other places because the total ad market isn't growing, and in fact right now it's shrinking. It's hand-to-hand combat to get people to spend less on, you know, ABC and to spend more on Netflix." So if Netflix is looking for other forms of near-term revenue to help support its hefty content budget ($17 billion in 2021 alone) then what can it do? Netflix could crack down on password sharing - a move that the company has been considering lately. "Basically you're going to clean up some subscribers that are free riders," Nathanson said. " That's going to help them get to a higher level of penetration, definitely, but not in long-term." The company remains the market leader and most competitors are still far from taking the company on. We used to do that thing shipping DVDs, and luckily we didn't get stuck with that. We define entertainment as the main thing," Hastings said. He added that he doesn't think Netflix will have a second act in the way Amazon has had with Amazon shopping and Amazon Web Services. Rather, Netflix will continue to improve and grow on what it already does best. I wouldn't look for any large secondary pool of profits. Let’s now feed the extractive summary through our T5 model. Netflix's lackluster user growth is a signal that it wouldn't hurt if it started thinking about other ways to make money. the company remains the market leader and most competitors are still far from taking the company on. the company could crack down on password sharing - a move that the company has been considering lately. "it's a judgment call... it's a belief we can build a better business, a more valuable business," hastings said. Wow... the generated summary now covers the entire context of the original text. For your convenience, I have summarized the codes below. You can also click here to go to my GitHub to get the Jupyter Notebooks for T5 text summarizer and text summarizer pipelines preparation, and the pipeline scripts that you can run on your terminal to summarize multiple PDF documents. I have built a text summarizer pipelines that can extract text from PDF documents, summarize the text and store both the original text and the summary into a SQLite database and output the summary to a text file. To summarize a long PDF document, you can first apply extractive summarization to shorten the text before you feed it through the T5 model to generate a human-like summary. Note: key in ‘1.0' if you only want to summarize the text with T5 model. Note: key in a ratio below ‘1.0’ (e.g. ‘0.5’) if you wish to shorten the text with BERT extractive summarization before running it through T5 summarization. It takes longer to generate a summary this way because each text is run through two different summarizers. There you go — you only need 7 lines of codes (including importing libraries and modules) to get the Google’s T5 pre-trained model to summarize a content for you. To make the summary of a long content more meaningful, you can apply extractive summarization to shorten the text first, followed by abstractive summarization. T5 pre-trained models support Transfer-Learning: that means we can train the models further with our custom datasets. For future work, it will be interesting to see how the models perform after they have been custom-trained to summarize specific contents, e.g. medical journals and engineering journals.
[ { "code": null, "e": 439, "s": 47, "text": "Summarization has become a very helpful way of tackling the issue of data overburden. In my earlier story, I shared how you can create your personal text summarizer using extractive method — if you have tried that, you may have noticed that, because no new sentences were generated from the original content, at times you may have difficulties understanding the generated extractive summary." }, { "code": null, "e": 597, "s": 439, "text": "In this story, I will share how I use Google’s T5 (Text-to-Text Transfer Transformer) model to create a human-like summarizer with just a few lines of codes!" }, { "code": null, "e": 780, "s": 597, "text": "As a bonus, I will also share my text summarizer pipelines where I combine both extractive and abstractive methods to generate meaningful summaries for PDF documents of any length..." }, { "code": null, "e": 834, "s": 780, "text": "There are two techniques to summarize a long content:" }, { "code": null, "e": 908, "s": 834, "text": "i. Extractive summary — extracts important sentences from a long content." }, { "code": null, "e": 1006, "s": 908, "text": "ii. Abstractive summary — creates a summary by generating new sentences from an original content." }, { "code": null, "e": 1266, "s": 1006, "text": "Abstractive summary is a comparatively more difficult technique as it involves deep learning, but thanks to Google’s pre-trained models that are made available to public, creating a meaningful abstractive summary is no longer a daunting machine learning task!" }, { "code": null, "e": 1475, "s": 1266, "text": "You can build simple yet incredibly powerful abstractive text summarizer using Google’ T5 pre-trained model. I will use HuggingFace’s state-of-the-art Transformers framework and PyTorch to build a summarizer." }, { "code": null, "e": 1492, "s": 1475, "text": "Install packages" }, { "code": null, "e": 1547, "s": 1492, "text": "Please ensure you have both Python packages installed." }, { "code": null, "e": 1589, "s": 1547, "text": "pip install torchpip install transformers" }, { "code": null, "e": 1614, "s": 1589, "text": "Load model and tokenizer" }, { "code": null, "e": 1661, "s": 1614, "text": "Load T5’s pre-trained model and its tokenizer." }, { "code": null, "e": 1843, "s": 1661, "text": "import torchfrom transformers import AutoTokenizer, AutoModelForSeq2SeqLMmodel = AutoModelForSeq2SeqLM.from_pretrained('t5-base')tokenizer = AutoTokenizer.from_pretrained('t5-base')" }, { "code": null, "e": 2095, "s": 1843, "text": "There are a total of five T5 models to choose from: t5-small, t5-base, t5-large, t-3B & t5–11B. They each have different parameters. I will choose the ‘t5-base’ model, which has a total of 220 millions parameters. Feel free to try different T5 models." }, { "code": null, "e": 2106, "s": 2095, "text": "Input text" }, { "code": null, "e": 2277, "s": 2106, "text": "Let’s load a CNN news article about ‘Netflix needs a Next Big Thing’ — simply because this is rather interesting business news — and see how well our summarizer performs." }, { "code": null, "e": 7549, "s": 2277, "text": "text = \"\"\"New York (CNN Business)Netflix is synonymous with streaming, but its competitors have a distinct advantage that threatens the streaming leader's position at the top.Disney has Disney+, but it also has theme parks, plush Baby Yoda dolls, blockbuster Marvel movies and ESPN. Comcast (CMCSA), Amazon (AMZN), ViacomCBS (VIACA), CNN's parent company WarnerMedia and Apple (AAPL) all have their own streaming services, too, but they also have other forms of revenue.As for Netflix (NFLX), its revenue driver is based entirely on building its subscriber base. It's worked out well for the company — so far. But it's starting to look like the king of streaming will soon need something other than new subscribers to keep growing.The streaming service reported Tuesday it now has 208 million subscribers globally, after adding 4 million subscribers in the first quarter of 2021. But that number missed expectations and the forecasts for its next quarter were also pretty weak.That was a big whiff for Netflix — a company coming off a massive year of growth thanks in large part to the pandemic driving people indoors — and Wall Street's reaction has not been great.The company's stock dropped as much as 8% on Wednesday, leading some to wonder what the future of the streamer looks like if competition continues to gain strength, people start heading outdoors and if, most importantly, its growth slows.\"If you hit a wall with [subscriptions] then you pretty much don't have a super growth strategy anymore in your most developed markets,\" Michael Nathanson, a media analyst and founding partner at MoffettNathanson, told CNN Business. \"What can they do to take even more revenue out of the market, above and beyond streaming revenues?\"Or put another way, the company's lackluster user growth last quarter is a signal that it wouldn't hurt if Netflix — a company that's lived and died with its subscriber numbers — started thinking about other ways to make money.An ad-supported Netflix? Not so fastThere are ways for Netflix to make money other than raising prices or adding subscribers. The most obvious: selling advertising.Netflix could have 30-second commercials on their programming or get sponsors for their biggest series and films. TV has worked that way forever, why not Netflix?That's probably not going to happen, given that CEO Reed Hastings has been vocal about the unlikelihood of an ad-supported Netflix service. His reasoning: It doesn't make business sense.\"It's a judgment call... It's a belief we can build a better business, a more valuable business [without advertising],\" Hastings told Variety in September. \"You know, advertising looks easy until you get in it. Then you realize you have to rip that revenue away from other places because the total ad market isn't growing, and in fact right now it's shrinking. It's hand-to-hand combat to get people to spend less on, you know, ABC and to spend more on Netflix.\"Hastings added that \"there's much more growth in the consumer market than there is in advertising, which is pretty flat.\"He's also expressed doubts about Netflix getting into live sports or news, which could boost the service's allure to subscribers, so that's likely out, too, at least for now.So if Netflix is looking for other forms of near-term revenue to help support its hefty content budget ($17 billion in 2021 alone) then what can it do? There is one place that could be a revenue driver for Netflix, but if you're borrowing your mother's account you won't like it.Netflix could crack down on password sharing — a move that the company has been considering lately.\"Basically you're going to clean up some subscribers that are free riders,\" Nathanson said. \"That's going to help them get to a higher level of penetration, definitely, but not in long-term.\"Lackluster growth is still growthMissing projections is never good, but it's hardly the end of the world for Netflix. The company remains the market leader and most competitors are still far from taking the company on. And while Netflix's first-quarter subscriber growth wasn't great, and its forecasts for the next quarter alarmed investors, it was just one quarter.Netflix has had subscriber misses before and it's still the most dominant name in all of streaming, and even lackluster growth is still growth. It's not as if people are canceling Netflix in droves.Asked about Netflix's \"second act\" during the company's post-earnings call on Tuesday, Hastings again placed the company's focus on pleasing subscribers.\"We do want to expand. We used to do that thing shipping DVDs, and luckily we didn't get stuck with that. We didn't define that as the main thing. We define entertainment as the main thing,\" Hastings said.He added that he doesn't think Netflix will have a second act in the way Amazon has had with Amazon shopping and Amazon Web Services. Rather, Netflix will continue to improve and grow on what it already does best.\"I'll bet we end with one hopefully gigantic, hopefully defensible profit pool, and continue to improve the service for our members,\" he said. \"I wouldn't look for any large secondary pool of profits. There will be a bunch of supporting pools, like consumer products, that can be both profitable and can support the title brands.\"\"\"\"" }, { "code": null, "e": 7563, "s": 7549, "text": "Tokenize Text" }, { "code": null, "e": 7739, "s": 7563, "text": "T5 can be used to perform other tasks, such as text generation, translation, etc.; adding T5 specific prefix “summarize: ” will tell the model to perform the summarizing task." }, { "code": null, "e": 7957, "s": 7739, "text": "tokens_input = tokenizer.encode(\"summarize: \" + text, return_tensors='pt', max_length=tokenizer.model_max_length, truncation=True)" }, { "code": null, "e": 8129, "s": 7957, "text": "Here we will tokenize our text to the model’s maximum acceptable token input length. If the tokenized input exceeds the model’s maximum token length, it will be truncated." }, { "code": null, "e": 8146, "s": 8129, "text": "Generate Summary" }, { "code": null, "e": 8256, "s": 8146, "text": "Let’s generate a summary by passing in the encoded tokens and then decode the generated summary back to text." }, { "code": null, "e": 8484, "s": 8256, "text": "summary_ids = model.generate(tokens_input, min_length=80, max_length=150, length_penalty=15, num_beams=2)summary = tokenizer.decode(summary_ids[0], skip_special_tokens=True)" }, { "code": null, "e": 8550, "s": 8484, "text": "The model takes encoded tokens and the following input arguments:" }, { "code": null, "e": 8591, "s": 8550, "text": "min_length: minimum length of sentences." }, { "code": null, "e": 8632, "s": 8591, "text": "max_length: maximum length of sentences." }, { "code": null, "e": 8763, "s": 8632, "text": "length_penalty: value > 1 forces the model to generate a longer summary, value < 1 forces the model to generate a shorter summary." }, { "code": null, "e": 8859, "s": 8763, "text": "num_beams: value 2 allows the model to explore tokens that generate more promising predictions." }, { "code": null, "e": 9115, "s": 8859, "text": "Note: Keeping the minimum and maximum sentence lengths between 80 and 150 and a length penalty of 15 will allow the model to generate a reasonable summary of 60 to 90 words. We will use the default values for the rest of input arguments (not shown above)." }, { "code": null, "e": 9130, "s": 9115, "text": "Output Summary" }, { "code": null, "e": 9647, "s": 9130, "text": "Netflix (NFLX) reported Tuesday it now has 208 million subscribers globally. that number missed expectations and the forecasts for its next quarter were also pretty weak. the streaming service's stock dropped as much as 8% on Wednesday, leading some to wonder what the future of the streamer looks like. if competition continues to gain strength, people start heading outdoors and if, most importantly, its growth slows, it wouldn't hurt if Netflix started thinking about other ways to make money - like selling ads." }, { "code": null, "e": 9691, "s": 9647, "text": "Wow! It looks like a pretty decent summary." }, { "code": null, "e": 9943, "s": 9691, "text": "...but if you read the full text and read the summary again, you will notice that the latter part of the full text did not get summarized — this is because the tokenized input get truncated after it exceeds the maximum model token input length of 512." }, { "code": null, "e": 10170, "s": 9943, "text": "If you are worried about missing out some important details in the latter text, you can use a simple trick to solve the issue: perform extractive summarization to the original text first, followed by abstractive summarization." }, { "code": null, "e": 10267, "s": 10170, "text": "Before we proceed, make sure you have pip installed BERT extractive summarizer on your terminal." }, { "code": null, "e": 10306, "s": 10267, "text": "pip install bert-extractive-summarizer" }, { "code": null, "e": 10605, "s": 10306, "text": "BERT stands for Bidirectional Encoder Representations from Transformers. It’s a Transformer-based machine learning technique for Natural Language Processing (NLP) developed by Google. It uses a powerful flat architecture with inter sentence transform layers to get the best result in summarization." }, { "code": null, "e": 10705, "s": 10605, "text": "from summarizer import Summarizerbert_model = Summarizer()ext_summary = bert_model(text, ratio=0.5)" }, { "code": null, "e": 10967, "s": 10705, "text": "Below is the extractive summary generated by BERT. I purposely set it to produce a summary that is 50% in length of the original text by setting the summary ratio to 0.5. Feel free to use a different ratio to adjust your long document to the appropriate length." }, { "code": null, "e": 13185, "s": 10967, "text": "New York (CNN Business)Netflix is synonymous with streaming, but its competitors have a distinct advantage that threatens the streaming leader's position at the top. Disney has Disney+, but it also has theme parks, plush Baby Yoda dolls, blockbuster Marvel movies and ESPN. It's worked out well for the company - so far. But that number missed expectations and the forecasts for its next quarter were also pretty weak. Or put another way, the company's lackluster user growth last quarter is a signal that it wouldn't hurt if Netflix - a company that's lived and died with its subscriber numbers - started thinking about other ways to make money. Not so fastThere are ways for Netflix to make money other than raising prices or adding subscribers. His reasoning: It doesn't make business sense. \"It's a judgment call... It's a belief we can build a better business, a more valuable business [without advertising],\" Hastings told Variety in September. \" You know, advertising looks easy until you get in it. Then you realize you have to rip that revenue away from other places because the total ad market isn't growing, and in fact right now it's shrinking. It's hand-to-hand combat to get people to spend less on, you know, ABC and to spend more on Netflix.\" So if Netflix is looking for other forms of near-term revenue to help support its hefty content budget ($17 billion in 2021 alone) then what can it do? Netflix could crack down on password sharing - a move that the company has been considering lately. \"Basically you're going to clean up some subscribers that are free riders,\" Nathanson said. \" That's going to help them get to a higher level of penetration, definitely, but not in long-term.\" The company remains the market leader and most competitors are still far from taking the company on. We used to do that thing shipping DVDs, and luckily we didn't get stuck with that. We define entertainment as the main thing,\" Hastings said. He added that he doesn't think Netflix will have a second act in the way Amazon has had with Amazon shopping and Amazon Web Services. Rather, Netflix will continue to improve and grow on what it already does best. I wouldn't look for any large secondary pool of profits." }, { "code": null, "e": 13245, "s": 13185, "text": "Let’s now feed the extractive summary through our T5 model." }, { "code": null, "e": 13685, "s": 13245, "text": "Netflix's lackluster user growth is a signal that it wouldn't hurt if it started thinking about other ways to make money. the company remains the market leader and most competitors are still far from taking the company on. the company could crack down on password sharing - a move that the company has been considering lately. \"it's a judgment call... it's a belief we can build a better business, a more valuable business,\" hastings said." }, { "code": null, "e": 13766, "s": 13685, "text": "Wow... the generated summary now covers the entire context of the original text." }, { "code": null, "e": 13823, "s": 13766, "text": "For your convenience, I have summarized the codes below." }, { "code": null, "e": 14057, "s": 13823, "text": "You can also click here to go to my GitHub to get the Jupyter Notebooks for T5 text summarizer and text summarizer pipelines preparation, and the pipeline scripts that you can run on your terminal to summarize multiple PDF documents." }, { "code": null, "e": 14270, "s": 14057, "text": "I have built a text summarizer pipelines that can extract text from PDF documents, summarize the text and store both the original text and the summary into a SQLite database and output the summary to a text file." }, { "code": null, "e": 14443, "s": 14270, "text": "To summarize a long PDF document, you can first apply extractive summarization to shorten the text before you feed it through the T5 model to generate a human-like summary." }, { "code": null, "e": 14516, "s": 14443, "text": "Note: key in ‘1.0' if you only want to summarize the text with T5 model." }, { "code": null, "e": 14780, "s": 14516, "text": "Note: key in a ratio below ‘1.0’ (e.g. ‘0.5’) if you wish to shorten the text with BERT extractive summarization before running it through T5 summarization. It takes longer to generate a summary this way because each text is run through two different summarizers." }, { "code": null, "e": 14943, "s": 14780, "text": "There you go — you only need 7 lines of codes (including importing libraries and modules) to get the Google’s T5 pre-trained model to summarize a content for you." }, { "code": null, "e": 15103, "s": 14943, "text": "To make the summary of a long content more meaningful, you can apply extractive summarization to shorten the text first, followed by abstractive summarization." }, { "code": null, "e": 15221, "s": 15103, "text": "T5 pre-trained models support Transfer-Learning: that means we can train the models further with our custom datasets." } ]
Objective-C - switch statement
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. The syntax for a switch statement in Objective-C programming language is as follows − switch(expression){ case constant-expression : statement(s); break; /* optional */ case constant-expression : statement(s); break; /* optional */ /* you can have any number of case statements */ default : /* Optional */ statement(s); } The following rules apply to a switch statement − The expression used in a switch statement must have an integral or enumerated type or be of a class type in which the class has a single conversion function to an integral or enumerated type. The expression used in a switch statement must have an integral or enumerated type or be of a class type in which the class has a single conversion function to an integral or enumerated type. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal. The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case. A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case. #import <Foundation/Foundation.h> int main () { /* local variable definition */ char grade = 'B'; switch(grade) { case 'A' : NSLog(@"Excellent!\n" ); break; case 'B' : case 'C' : NSLog(@"Well done\n" ); break; case 'D' : NSLog(@"You passed\n" ); break; case 'F' : NSLog(@"Better try again\n" ); break; default : NSLog(@"Invalid grade\n" ); } NSLog(@"Your grade is %c\n", grade ); return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-07 22:44:26.928 demo[17555] Well done 2013-09-07 22:44:26.929 demo[17555] Your grade is B 18 Lectures 1 hours PARTHA MAJUMDAR 6 Lectures 25 mins Ken Burke Print Add Notes Bookmark this page
[ { "code": null, "e": 2746, "s": 2560, "text": "A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case." }, { "code": null, "e": 2832, "s": 2746, "text": "The syntax for a switch statement in Objective-C programming language is as follows −" }, { "code": null, "e": 3115, "s": 2832, "text": "switch(expression){\n case constant-expression :\n statement(s);\n break; /* optional */\n case constant-expression :\n statement(s);\n break; /* optional */\n \n /* you can have any number of case statements */\n default : /* Optional */\n statement(s);\n}" }, { "code": null, "e": 3165, "s": 3115, "text": "The following rules apply to a switch statement −" }, { "code": null, "e": 3357, "s": 3165, "text": "The expression used in a switch statement must have an integral or enumerated type or be of a class type in which the class has a single conversion function to an integral or enumerated type." }, { "code": null, "e": 3549, "s": 3357, "text": "The expression used in a switch statement must have an integral or enumerated type or be of a class type in which the class has a single conversion function to an integral or enumerated type." }, { "code": null, "e": 3675, "s": 3549, "text": "You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon." }, { "code": null, "e": 3801, "s": 3675, "text": "You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon." }, { "code": null, "e": 3934, "s": 3801, "text": "The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal." }, { "code": null, "e": 4067, "s": 3934, "text": "The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal." }, { "code": null, "e": 4207, "s": 4067, "text": "When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached." }, { "code": null, "e": 4347, "s": 4207, "text": "When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached." }, { "code": null, "e": 4484, "s": 4347, "text": "When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement." }, { "code": null, "e": 4621, "s": 4484, "text": "When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement." }, { "code": null, "e": 4767, "s": 4621, "text": "Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached." }, { "code": null, "e": 4913, "s": 4767, "text": "Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached." }, { "code": null, "e": 5134, "s": 4913, "text": "A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case." }, { "code": null, "e": 5355, "s": 5134, "text": "A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case." }, { "code": null, "e": 5849, "s": 5355, "text": "#import <Foundation/Foundation.h>\n \nint main () {\n \n /* local variable definition */\n char grade = 'B';\n\n switch(grade) {\n case 'A' :\n NSLog(@\"Excellent!\\n\" );\n break;\n case 'B' :\n case 'C' :\n NSLog(@\"Well done\\n\" );\n break;\n case 'D' :\n NSLog(@\"You passed\\n\" );\n break;\n case 'F' :\n NSLog(@\"Better try again\\n\" );\n break;\n default :\n NSLog(@\"Invalid grade\\n\" );\n }\n \n NSLog(@\"Your grade is %c\\n\", grade );\n return 0;\n}" }, { "code": null, "e": 5930, "s": 5849, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 6030, "s": 5930, "text": "2013-09-07 22:44:26.928 demo[17555] Well done\n2013-09-07 22:44:26.929 demo[17555] Your grade is B\n" }, { "code": null, "e": 6063, "s": 6030, "text": "\n 18 Lectures \n 1 hours \n" }, { "code": null, "e": 6080, "s": 6063, "text": " PARTHA MAJUMDAR" }, { "code": null, "e": 6111, "s": 6080, "text": "\n 6 Lectures \n 25 mins\n" }, { "code": null, "e": 6122, "s": 6111, "text": " Ken Burke" }, { "code": null, "e": 6129, "s": 6122, "text": " Print" }, { "code": null, "e": 6140, "s": 6129, "text": " Add Notes" } ]
Estimating Time until Contract Termination — Survival Analysis with Lifelines | by Cornellius Yudha Wijaya | Towards Data Science
I am sure everyone at some point of their data career would meet a case when you want to estimate a specific event to happen, e.g., “When someone would churn?” or “When the death claim of insurance would happen?”. We would commonly use a time-series approach to solve this problem, but Survival Analysis is the typical approach. In this article, I want to introduce to you what is Survival Analysis and its application with the Lifelines Python package using real-life Contract Termination data. Let’s get into it. What is Survival Analysis? Survival analysis is a statistical analysis developed to measure individuals' lifespans; for example, “how long does this population live for?”. This would be answered using the survival analysis. While initially it is used to measure individual lifespan (life or death), the analysis is versatile enough to answer all kinds of questions. You might be interested in the time between people buying the insurance until the time of the claim or when people come into the theme park until they are exiting the park. What is important is the data have the duration of the event. You might have a follow-up question after my explanation above “I might have the data, but what if I did not have all the data with the duration of the event I want.” For example, you might need to wait until 60 years until all the individuals you analyze claim their death insurance — but you want to decide in a time faster than that (possibly right now). This is why we have the right-censored concept. The concept defines the individual with the non-occurring event lifetime (or duration) excluded, and the only information we had is the current duration. To clarify, we would use a dataset example from Kaggle regarding the Employment Attrition where their contract is terminated. import pandas as pddf = pd.read_csv('MFG10YearTerminationData.csv') df[['length_of_service', 'STATUS']] We might ask this question from the data “What is the duration of the time until employee contracts are terminated?”. As we are interested in the termination time, we need the employee data with their contract status (ACTIVE or TERMINATED). If you see the data above, we would have the length_of_service. This is the time in months of the employee serving within the company until now or until their contract is terminated. If the status is still ACTIVE, then we have right-censored the data as we still did not know when their employment contract would be terminated (we put the length_of_service for the ACTIVE status with the months between their hired time until the current time). The censoring is also done to alleviate the problem of different times of entering for some individuals. The data we have would certainly not have the employee hired simultaneously; some are employed a long time ago, and some are a recent addition. Why do we need to know about right-censored? This is because Survival Analysis is developed to deal with the estimation using the right-censored data. All our estimates would be based on the data we right-censored. If you are still not comfortable with the concept, let’s get into the application using the Lifelines Python package. I would skip the Survival Analysis mathematical part as the central part of this article is to use the Lifeline package to estimate the time until the contract termination. If you are interested in an in-depth math explanation of the Survival Analysis, you could visit the Lifeline package here. For the preparation, let’s install the Lifelines package. #install with pippip install lifelines or #install via condaconda install -c conda-forge lifelines With the package installed, we are now ready to do our Survival Analysis with the Lifelines package. As a starter, we would estimate the Survival Function using the Kaplan-Meier estimation. from lifelines import KaplanMeierFitterkmf = KaplanMeierFitter() While the dataset is ready, we would do one feature engineering to transform the ‘STATUS’ variable into 0 or 1 instead of text (This feature would be called ‘Observed’). df['Observed'] = df['STATUS'].apply(lambda x: 1 if x == 'TERMINATED' else 0) Now we have all the data we need; the duration and the event observed. Let’s start by creating the Survival Function. #Kaplan-Meier estimationkmf.fit(df['length_of_service'], df['Observed']) If it is successful, this notification will show up in your notebook. Next, we could try to plot the survival function to see the survival probability (probability of employee contract termination is not happening) throughout the time. import matplotlib.pyplot as pltplt.figure(figsize = (8,8))plt.title('Employee Contract Termination Survival Function')kmf.plot_survival_function() The plot above shows the probability of the employment contract would not terminate following the time. The plot showing interesting information; during the first 23 months, the likelihood of your contract terminated is relatively low, but when you are entering the 24 months and 25 months, your survival probability (contract not terminated) becomes significantly lowered. This means that most of the termination happens in the month 24 or 25 of your contract times. If you are more interested in the actual number than the plot shows, you can show the survival function estimation by running the following code. kmf.survival_function_ Or, if you are more interested in the cumulative density of the termination probability, you could run the following code. kmf.cumulative_density_ We might have another question; “Is there a contract termination time difference between the gender?”. To answering this question, we could set up two different datasets and survival functions. #Separate the Male and Female datadf_m = df[df['gender_short'] == 'M']df_f = df[df['gender_short'] == 'F']#Prepare the survival functionkmf_m = KaplanMeierFitter()kmf_f = KaplanMeierFitter()#Estimate both dataset to acquire the survival functionkmf_m.fit(df_m['length_of_service'], df_m['Observed'], label = 'Male')kmf_f.fit(df_f['length_of_service'], df_f['Observed'], label = 'Female')#Produce the survival function plotplt.figure(figsize = (8,8))plt.title('Employee Contract Termination Survival Function based on Gender')kmf_m.plot_survival_function()kmf_f.plot_survival_function() Here we have another exciting result. The plot shows that the survival probability for the Female is way lower than the Male. In month 25, we have a significant survival probability drop for the females compared to the males. We can use statistical hypothesis testing to assess our assumption if there is a difference between males and females for their contract termination time. The standard test to use is the log-rank test, which Lifelines provide within the package. from lifelines.statistics import logrank_testresults = logrank_test(df_m['length_of_service'], df_f['length_of_service'], df_m['Observed'], df_f['Observed'], alpha=.95)results.print_summary() From the test result, we acquired P-value less than 0.05, which means we reject the Null Hypothesis and accepting that there is a difference between males and females in their contract termination time. It is a disturbing thing but let’s put aside the conclusion until we analyze things even further. Previously we talk about the survival function, but you might be more interested in the probability of death (contract termination) event happening at the time of t. Itis what the Hazard function was about, estimating the probability of death. We would use the Nelson-Aalen estimation as the way to estimate the Hazard Function. Luckily, the lifelines packages have provided this function. from lifelines import NelsonAalenFitternaf = NelsonAalenFitter()naf.fit(df['length_of_service'], df['Observed'])plt.figure(figsize = (8,8))plt.title('Employee Contract Termination Hazard Function')naf.plot_cumulative_hazard() The Hazard function feels like the reverse of the Survival function. From the plot, we can see that it starts slow and going high at the end in the month 24 and 25. Although, what you see here in this plot is the cumulative hazard rate, and we interpret the result by looking at the rate at the time t. If we want to get the actual number of times t, you could run the following code. naf.cumulative_hazard_ Cumulatively, the hazard rate would get higher as the time probability of contract termination event happening is increasing following the time. Often, you would have another data other than the duration you assume would affect the Survival analysis. This technique is what we called the Survival Regression. There are a few popular models in survival regression, but Cox's model is most commonly used for this problem. Let’s try this model with the dataset we own before. I assume that only Age, Gender, and Business Unit affects the duration of the employee contracts. training = df[['age', 'gender_short', 'BUSINESS_UNIT', 'length_of_service','Observed']].copy() From this data, we need to prepare it to be Machine Learning ready. It means we need to One-Hot Encode the categorical variable. training = pd.get_dummies(data = training, columns = ['gender_short', 'BUSINESS_UNIT'], drop_first = True)training.head() This is the dataset that we would use for Cox’s model. Let’s see if these variables are affecting the employee contract termination time. from lifelines import CoxPHFittercph = CoxPHFitter()cph.fit(training, duration_col='length_of_service', event_col='Observed')cph.print_summary() From the model summary above, we can see that the BUSINESS_UNIT_STORES is the only variable that did not affect the duration because the P-value is more than 0.05 while the rest has a significant result. For the interpretation, we can assess the coefficient of the variable. Let’s take the age coefficient, which is -0.01. It means, one unit of increase in the age would decrease the baseline hazard function by exp(-0.01) or 0.99. You could interpret this by saying that with an increase in age, the chance of contract termination would decrease by around ~1%. After fitting the model, we can use this model to predict the new data's survival function. cph.predict_survival_function(training[['age', 'gender_short_M', 'BUSINESS_UNIT_STORES']].loc[0]).plot() The data we give to the model produce us this following survival function where the probability of the survival would decrease significantly on the month 25 (around ~50%). To understand the model even better, we can plot the survival curves to look like we vary a single variable while holding everything else equal. This is used to understand the impact of the variable given the model we had. We want to understand the age variable impact on our model; we can plot using the following code. cph.plot_partial_effects_on_outcome(covariates='age', values=[20,30, 40, 50], cmap='coolwarm', figsize = (8,8)) Given the age, we can see that the survival probability increases with the increase of age. This means we can assume that older people are less likely to have their contract terminated than younger people. Survival Analysis is an analysis that tries to solve a problem with a question such as “When someone would churn?” or “When the death claim of insurance would happen?”. Using the Lifeline package, we could do Survival Analysis easier, as we can see from the Contract Termination data. Using the Survival Analysis, we found out that the probability of someone would have their contract terminated is the highest when the employee is reaching 24 and 25 months of their working time. Moreover, females and younger people having a higher probability of having their contract terminated. If you are not subscribed as a Medium Member, please consider subscribing through my referral.
[ { "code": null, "e": 500, "s": 171, "text": "I am sure everyone at some point of their data career would meet a case when you want to estimate a specific event to happen, e.g., “When someone would churn?” or “When the death claim of insurance would happen?”. We would commonly use a time-series approach to solve this problem, but Survival Analysis is the typical approach." }, { "code": null, "e": 686, "s": 500, "text": "In this article, I want to introduce to you what is Survival Analysis and its application with the Lifelines Python package using real-life Contract Termination data. Let’s get into it." }, { "code": null, "e": 910, "s": 686, "text": "What is Survival Analysis? Survival analysis is a statistical analysis developed to measure individuals' lifespans; for example, “how long does this population live for?”. This would be answered using the survival analysis." }, { "code": null, "e": 1287, "s": 910, "text": "While initially it is used to measure individual lifespan (life or death), the analysis is versatile enough to answer all kinds of questions. You might be interested in the time between people buying the insurance until the time of the claim or when people come into the theme park until they are exiting the park. What is important is the data have the duration of the event." }, { "code": null, "e": 1645, "s": 1287, "text": "You might have a follow-up question after my explanation above “I might have the data, but what if I did not have all the data with the duration of the event I want.” For example, you might need to wait until 60 years until all the individuals you analyze claim their death insurance — but you want to decide in a time faster than that (possibly right now)." }, { "code": null, "e": 1847, "s": 1645, "text": "This is why we have the right-censored concept. The concept defines the individual with the non-occurring event lifetime (or duration) excluded, and the only information we had is the current duration." }, { "code": null, "e": 1973, "s": 1847, "text": "To clarify, we would use a dataset example from Kaggle regarding the Employment Attrition where their contract is terminated." }, { "code": null, "e": 2077, "s": 1973, "text": "import pandas as pddf = pd.read_csv('MFG10YearTerminationData.csv') df[['length_of_service', 'STATUS']]" }, { "code": null, "e": 2318, "s": 2077, "text": "We might ask this question from the data “What is the duration of the time until employee contracts are terminated?”. As we are interested in the termination time, we need the employee data with their contract status (ACTIVE or TERMINATED)." }, { "code": null, "e": 2763, "s": 2318, "text": "If you see the data above, we would have the length_of_service. This is the time in months of the employee serving within the company until now or until their contract is terminated. If the status is still ACTIVE, then we have right-censored the data as we still did not know when their employment contract would be terminated (we put the length_of_service for the ACTIVE status with the months between their hired time until the current time)." }, { "code": null, "e": 3012, "s": 2763, "text": "The censoring is also done to alleviate the problem of different times of entering for some individuals. The data we have would certainly not have the employee hired simultaneously; some are employed a long time ago, and some are a recent addition." }, { "code": null, "e": 3227, "s": 3012, "text": "Why do we need to know about right-censored? This is because Survival Analysis is developed to deal with the estimation using the right-censored data. All our estimates would be based on the data we right-censored." }, { "code": null, "e": 3345, "s": 3227, "text": "If you are still not comfortable with the concept, let’s get into the application using the Lifelines Python package." }, { "code": null, "e": 3641, "s": 3345, "text": "I would skip the Survival Analysis mathematical part as the central part of this article is to use the Lifeline package to estimate the time until the contract termination. If you are interested in an in-depth math explanation of the Survival Analysis, you could visit the Lifeline package here." }, { "code": null, "e": 3699, "s": 3641, "text": "For the preparation, let’s install the Lifelines package." }, { "code": null, "e": 3738, "s": 3699, "text": "#install with pippip install lifelines" }, { "code": null, "e": 3741, "s": 3738, "text": "or" }, { "code": null, "e": 3798, "s": 3741, "text": "#install via condaconda install -c conda-forge lifelines" }, { "code": null, "e": 3988, "s": 3798, "text": "With the package installed, we are now ready to do our Survival Analysis with the Lifelines package. As a starter, we would estimate the Survival Function using the Kaplan-Meier estimation." }, { "code": null, "e": 4053, "s": 3988, "text": "from lifelines import KaplanMeierFitterkmf = KaplanMeierFitter()" }, { "code": null, "e": 4223, "s": 4053, "text": "While the dataset is ready, we would do one feature engineering to transform the ‘STATUS’ variable into 0 or 1 instead of text (This feature would be called ‘Observed’)." }, { "code": null, "e": 4300, "s": 4223, "text": "df['Observed'] = df['STATUS'].apply(lambda x: 1 if x == 'TERMINATED' else 0)" }, { "code": null, "e": 4418, "s": 4300, "text": "Now we have all the data we need; the duration and the event observed. Let’s start by creating the Survival Function." }, { "code": null, "e": 4491, "s": 4418, "text": "#Kaplan-Meier estimationkmf.fit(df['length_of_service'], df['Observed'])" }, { "code": null, "e": 4561, "s": 4491, "text": "If it is successful, this notification will show up in your notebook." }, { "code": null, "e": 4727, "s": 4561, "text": "Next, we could try to plot the survival function to see the survival probability (probability of employee contract termination is not happening) throughout the time." }, { "code": null, "e": 4874, "s": 4727, "text": "import matplotlib.pyplot as pltplt.figure(figsize = (8,8))plt.title('Employee Contract Termination Survival Function')kmf.plot_survival_function()" }, { "code": null, "e": 5342, "s": 4874, "text": "The plot above shows the probability of the employment contract would not terminate following the time. The plot showing interesting information; during the first 23 months, the likelihood of your contract terminated is relatively low, but when you are entering the 24 months and 25 months, your survival probability (contract not terminated) becomes significantly lowered. This means that most of the termination happens in the month 24 or 25 of your contract times." }, { "code": null, "e": 5488, "s": 5342, "text": "If you are more interested in the actual number than the plot shows, you can show the survival function estimation by running the following code." }, { "code": null, "e": 5511, "s": 5488, "text": "kmf.survival_function_" }, { "code": null, "e": 5634, "s": 5511, "text": "Or, if you are more interested in the cumulative density of the termination probability, you could run the following code." }, { "code": null, "e": 5658, "s": 5634, "text": "kmf.cumulative_density_" }, { "code": null, "e": 5852, "s": 5658, "text": "We might have another question; “Is there a contract termination time difference between the gender?”. To answering this question, we could set up two different datasets and survival functions." }, { "code": null, "e": 6438, "s": 5852, "text": "#Separate the Male and Female datadf_m = df[df['gender_short'] == 'M']df_f = df[df['gender_short'] == 'F']#Prepare the survival functionkmf_m = KaplanMeierFitter()kmf_f = KaplanMeierFitter()#Estimate both dataset to acquire the survival functionkmf_m.fit(df_m['length_of_service'], df_m['Observed'], label = 'Male')kmf_f.fit(df_f['length_of_service'], df_f['Observed'], label = 'Female')#Produce the survival function plotplt.figure(figsize = (8,8))plt.title('Employee Contract Termination Survival Function based on Gender')kmf_m.plot_survival_function()kmf_f.plot_survival_function()" }, { "code": null, "e": 6664, "s": 6438, "text": "Here we have another exciting result. The plot shows that the survival probability for the Female is way lower than the Male. In month 25, we have a significant survival probability drop for the females compared to the males." }, { "code": null, "e": 6910, "s": 6664, "text": "We can use statistical hypothesis testing to assess our assumption if there is a difference between males and females for their contract termination time. The standard test to use is the log-rank test, which Lifelines provide within the package." }, { "code": null, "e": 7102, "s": 6910, "text": "from lifelines.statistics import logrank_testresults = logrank_test(df_m['length_of_service'], df_f['length_of_service'], df_m['Observed'], df_f['Observed'], alpha=.95)results.print_summary()" }, { "code": null, "e": 7403, "s": 7102, "text": "From the test result, we acquired P-value less than 0.05, which means we reject the Null Hypothesis and accepting that there is a difference between males and females in their contract termination time. It is a disturbing thing but let’s put aside the conclusion until we analyze things even further." }, { "code": null, "e": 7647, "s": 7403, "text": "Previously we talk about the survival function, but you might be more interested in the probability of death (contract termination) event happening at the time of t. Itis what the Hazard function was about, estimating the probability of death." }, { "code": null, "e": 7793, "s": 7647, "text": "We would use the Nelson-Aalen estimation as the way to estimate the Hazard Function. Luckily, the lifelines packages have provided this function." }, { "code": null, "e": 8019, "s": 7793, "text": "from lifelines import NelsonAalenFitternaf = NelsonAalenFitter()naf.fit(df['length_of_service'], df['Observed'])plt.figure(figsize = (8,8))plt.title('Employee Contract Termination Hazard Function')naf.plot_cumulative_hazard()" }, { "code": null, "e": 8322, "s": 8019, "text": "The Hazard function feels like the reverse of the Survival function. From the plot, we can see that it starts slow and going high at the end in the month 24 and 25. Although, what you see here in this plot is the cumulative hazard rate, and we interpret the result by looking at the rate at the time t." }, { "code": null, "e": 8404, "s": 8322, "text": "If we want to get the actual number of times t, you could run the following code." }, { "code": null, "e": 8427, "s": 8404, "text": "naf.cumulative_hazard_" }, { "code": null, "e": 8572, "s": 8427, "text": "Cumulatively, the hazard rate would get higher as the time probability of contract termination event happening is increasing following the time." }, { "code": null, "e": 8736, "s": 8572, "text": "Often, you would have another data other than the duration you assume would affect the Survival analysis. This technique is what we called the Survival Regression." }, { "code": null, "e": 8900, "s": 8736, "text": "There are a few popular models in survival regression, but Cox's model is most commonly used for this problem. Let’s try this model with the dataset we own before." }, { "code": null, "e": 8998, "s": 8900, "text": "I assume that only Age, Gender, and Business Unit affects the duration of the employee contracts." }, { "code": null, "e": 9093, "s": 8998, "text": "training = df[['age', 'gender_short', 'BUSINESS_UNIT', 'length_of_service','Observed']].copy()" }, { "code": null, "e": 9222, "s": 9093, "text": "From this data, we need to prepare it to be Machine Learning ready. It means we need to One-Hot Encode the categorical variable." }, { "code": null, "e": 9344, "s": 9222, "text": "training = pd.get_dummies(data = training, columns = ['gender_short', 'BUSINESS_UNIT'], drop_first = True)training.head()" }, { "code": null, "e": 9482, "s": 9344, "text": "This is the dataset that we would use for Cox’s model. Let’s see if these variables are affecting the employee contract termination time." }, { "code": null, "e": 9627, "s": 9482, "text": "from lifelines import CoxPHFittercph = CoxPHFitter()cph.fit(training, duration_col='length_of_service', event_col='Observed')cph.print_summary()" }, { "code": null, "e": 9831, "s": 9627, "text": "From the model summary above, we can see that the BUSINESS_UNIT_STORES is the only variable that did not affect the duration because the P-value is more than 0.05 while the rest has a significant result." }, { "code": null, "e": 10189, "s": 9831, "text": "For the interpretation, we can assess the coefficient of the variable. Let’s take the age coefficient, which is -0.01. It means, one unit of increase in the age would decrease the baseline hazard function by exp(-0.01) or 0.99. You could interpret this by saying that with an increase in age, the chance of contract termination would decrease by around ~1%." }, { "code": null, "e": 10281, "s": 10189, "text": "After fitting the model, we can use this model to predict the new data's survival function." }, { "code": null, "e": 10386, "s": 10281, "text": "cph.predict_survival_function(training[['age', 'gender_short_M', 'BUSINESS_UNIT_STORES']].loc[0]).plot()" }, { "code": null, "e": 10558, "s": 10386, "text": "The data we give to the model produce us this following survival function where the probability of the survival would decrease significantly on the month 25 (around ~50%)." }, { "code": null, "e": 10781, "s": 10558, "text": "To understand the model even better, we can plot the survival curves to look like we vary a single variable while holding everything else equal. This is used to understand the impact of the variable given the model we had." }, { "code": null, "e": 10879, "s": 10781, "text": "We want to understand the age variable impact on our model; we can plot using the following code." }, { "code": null, "e": 10991, "s": 10879, "text": "cph.plot_partial_effects_on_outcome(covariates='age', values=[20,30, 40, 50], cmap='coolwarm', figsize = (8,8))" }, { "code": null, "e": 11197, "s": 10991, "text": "Given the age, we can see that the survival probability increases with the increase of age. This means we can assume that older people are less likely to have their contract terminated than younger people." }, { "code": null, "e": 11366, "s": 11197, "text": "Survival Analysis is an analysis that tries to solve a problem with a question such as “When someone would churn?” or “When the death claim of insurance would happen?”." }, { "code": null, "e": 11780, "s": 11366, "text": "Using the Lifeline package, we could do Survival Analysis easier, as we can see from the Contract Termination data. Using the Survival Analysis, we found out that the probability of someone would have their contract terminated is the highest when the employee is reaching 24 and 25 months of their working time. Moreover, females and younger people having a higher probability of having their contract terminated." } ]
reStructuredText | .rst file to HTML file using Python for Documentations - GeeksforGeeks
21 Jan, 2019 Introduction to .rst file (reStructuredText): reStructuredText is a file format for Textual data majorly used by Python based communities to develop documentation in an easy way similar to other tools like Javadoc for Java. Most of the docs of Python-based software and libraries are written using reStructuredText and hence it’s important to learn it when contributing to any organization. Like Python, RST syntax is also sensitive to Indentation. Example code of reStructuredText:Some basic syntax and their HTML rendering are given below. Some text or code restructured.rst ******************************This is example of rst on GFG****************************** *GeeksforGeeks in italic* **GeeksforGeeks in bold** `Gfg website<www.geeksforgeeks.org>` ``GeeksforGeeks in vebatim`` Save the file with .rst extension. Python Code : Following is the Python code to convert .rst files to HTML files. docutils is a predefined library downloaded while Python is installed. publish_file method is used to convert rst to html by passing file names as parameters. import docutils.core docutils.core.publish_file( source_path ="restructured.rst", destination_path ="Output.html", writer_name ="html") Output.htmlAfter running the python code, a HTML file would be made in the same directory as of rst file. The code of HTML is complicated than normal HTML code written by a person since it’s auto generated. The following image shows HTML rendering of reStructuredText shown above. python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n21 Jan, 2019" }, { "code": null, "e": 24258, "s": 24212, "text": "Introduction to .rst file (reStructuredText):" }, { "code": null, "e": 24603, "s": 24258, "text": "reStructuredText is a file format for Textual data majorly used by Python based communities to develop documentation in an easy way similar to other tools like Javadoc for Java. Most of the docs of Python-based software and libraries are written using reStructuredText and hence it’s important to learn it when contributing to any organization." }, { "code": null, "e": 24661, "s": 24603, "text": "Like Python, RST syntax is also sensitive to Indentation." }, { "code": null, "e": 24754, "s": 24661, "text": "Example code of reStructuredText:Some basic syntax and their HTML rendering are given below." }, { "code": null, "e": 24772, "s": 24754, "text": "Some text or code" }, { "code": null, "e": 24789, "s": 24772, "text": "restructured.rst" }, { "code": "******************************This is example of rst on GFG****************************** *GeeksforGeeks in italic* **GeeksforGeeks in bold** `Gfg website<www.geeksforgeeks.org>` ``GeeksforGeeks in vebatim``", "e": 25001, "s": 24789, "text": null }, { "code": null, "e": 25036, "s": 25001, "text": "Save the file with .rst extension." }, { "code": null, "e": 25050, "s": 25036, "text": "Python Code :" }, { "code": null, "e": 25275, "s": 25050, "text": "Following is the Python code to convert .rst files to HTML files. docutils is a predefined library downloaded while Python is installed. publish_file method is used to convert rst to html by passing file names as parameters." }, { "code": "import docutils.core docutils.core.publish_file( source_path =\"restructured.rst\", destination_path =\"Output.html\", writer_name =\"html\")", "e": 25421, "s": 25275, "text": null }, { "code": null, "e": 25702, "s": 25421, "text": "Output.htmlAfter running the python code, a HTML file would be made in the same directory as of rst file. The code of HTML is complicated than normal HTML code written by a person since it’s auto generated. The following image shows HTML rendering of reStructuredText shown above." }, { "code": null, "e": 25717, "s": 25702, "text": "python-utility" }, { "code": null, "e": 25724, "s": 25717, "text": "Python" }, { "code": null, "e": 25822, "s": 25724, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25831, "s": 25822, "text": "Comments" }, { "code": null, "e": 25844, "s": 25831, "text": "Old Comments" }, { "code": null, "e": 25876, "s": 25844, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25932, "s": 25876, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25953, "s": 25932, "text": "Python OOPs Concepts" }, { "code": null, "e": 25992, "s": 25953, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26034, "s": 25992, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26061, "s": 26034, "text": "Python Classes and Objects" }, { "code": null, "e": 26092, "s": 26061, "text": "Python | os.path.join() method" }, { "code": null, "e": 26134, "s": 26092, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26170, "s": 26134, "text": "Python | Pandas dataframe.groupby()" } ]
Toeplitz matrix | Practice | GeeksforGeeks
A Toeplitz (or diagonal-constant) matrix is a matrix in which each descending diagonal from left to right is constant, i.e., all elements in a diagonal are same. Given a matrix A of order N X M your task is to complete the function isToeplitz which returns true if the matrix is Toeplitz otherwise returns false. Example 1: Input: 3 3 6 7 8 4 6 7 1 4 6 Output: 1 Explanation: The test case represents a 3x3 matrix which looks like 6 7 8 4 6 7 1 4 6 Output: 1(True) as values in all diagonals are same. Example 2: Input: 2 3 1 2 3 4 5 6 Output: 0 Explanation: Matrix of order 2x3 will be 1 2 3 4 5 6 Output: 0(False) as values in all diagonals are not same. Your task: You don't need to read input or print anything. Your task is to complete the function isToepliz() which takes the matrix and size of matrix as input parameters and returns 1 if the matrix is a Toepliz matrix , otherwise return 0. Constraints: 1<=N,M<=40 1<=A[i][j]<=100 1<=i<=N,1<=j<=M Expected time complexity:O(nxn) Expected space complexity:O(1) 0 abhayjcs202 months ago time taken -0.00 for(int i=0;i<N-1;i++){ for(int j=0;j<M-1;j++){ if(A[i][j]!=A[i+1][j+1]){ return false; } } } return true; 0 cshubham4393 months ago int num = mat[0][0]; for(int i = 0; i<N; i++){ for(int j = 0; j<M; j++){ if(i==j){ if(num!=mat[i][j]){ return false; } } } } return true; 0 keshrishivam41143 months ago Python code def isToepliz(lis, n, m): for i in range(n-1): for j in range(m-1): if lis[i][j]!=lis[i+1][j+1]: return 0 return 1 0 bhoomikasahu00104 months ago bool isToepliz(int A[MAX][MAX],int N,int M){ for(int i=0; i<N-1; i++){ for(int j=0; j<M-1; j++){ if(A[i][j] != A[i+1][j+1]) return 0; } } return 1;} 0 pankajkumarravi6 months ago ********************* java solution *************** boolean isToepliz(int mat[][], int N, int M) { int i =0,j=0; int resp = mat[i][j]; while (++i<N && ++j <M){ // found mismatch if (resp != mat[i][j]) return false; } return true; } 0 mrshobhit7 months ago Python 3: Execution Time - 0.0 Sec def isToepliz(lis, n, m): #code here for i in range(n): for j in range(m): if i==0 or j==0: continue if lis[i][j] != lis[i-1][j-1]: return False return True 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": 551, "s": 238, "text": "A Toeplitz (or diagonal-constant) matrix is a matrix in which each descending diagonal from left to right is constant, i.e., all elements in a diagonal are same.\nGiven a matrix A of order N X M your task is to complete the function isToeplitz which returns true if the matrix is Toeplitz otherwise returns false." }, { "code": null, "e": 563, "s": 551, "text": "Example 1: " }, { "code": null, "e": 748, "s": 563, "text": "Input: 3 3 6 7 8 4 6 7 1 4 6 \nOutput: 1\nExplanation:\nThe test case represents a 3x3 matrix which looks like \n 6 7 8 \n 4 6 7 \n 1 4 6\nOutput: 1(True) as values in all diagonals are same." }, { "code": null, "e": 759, "s": 748, "text": "Example 2:" }, { "code": null, "e": 917, "s": 759, "text": "Input:\n2 3\n1 2 3 4 5 6\nOutput: 0\nExplanation: \nMatrix of order 2x3 will be \n 1 2 3\n 4 5 6\nOutput: 0(False) as values in all diagonals \nare not same.\n" }, { "code": null, "e": 1159, "s": 917, "text": "Your task: You don't need to read input or print anything. Your task is to complete the function isToepliz() which takes the matrix and size of matrix as input parameters and returns 1 if the matrix is a Toepliz matrix , otherwise return 0. " }, { "code": null, "e": 1173, "s": 1159, "text": "Constraints: " }, { "code": null, "e": 1185, "s": 1173, "text": "1<=N,M<=40 " }, { "code": null, "e": 1201, "s": 1185, "text": "1<=A[i][j]<=100" }, { "code": null, "e": 1217, "s": 1201, "text": "1<=i<=N,1<=j<=M" }, { "code": null, "e": 1249, "s": 1217, "text": "Expected time complexity:O(nxn)" }, { "code": null, "e": 1280, "s": 1249, "text": "Expected space complexity:O(1)" }, { "code": null, "e": 1282, "s": 1280, "text": "0" }, { "code": null, "e": 1305, "s": 1282, "text": "abhayjcs202 months ago" }, { "code": null, "e": 1322, "s": 1305, "text": "time taken -0.00" }, { "code": null, "e": 1502, "s": 1322, "text": "for(int i=0;i<N-1;i++){ for(int j=0;j<M-1;j++){ if(A[i][j]!=A[i+1][j+1]){ return false; } } } return true;" }, { "code": null, "e": 1504, "s": 1502, "text": "0" }, { "code": null, "e": 1528, "s": 1504, "text": "cshubham4393 months ago" }, { "code": null, "e": 1790, "s": 1528, "text": "int num = mat[0][0]; for(int i = 0; i<N; i++){ for(int j = 0; j<M; j++){ if(i==j){ if(num!=mat[i][j]){ return false; } } } } return true;" }, { "code": null, "e": 1792, "s": 1790, "text": "0" }, { "code": null, "e": 1821, "s": 1792, "text": "keshrishivam41143 months ago" }, { "code": null, "e": 1833, "s": 1821, "text": "Python code" }, { "code": null, "e": 1987, "s": 1835, "text": "def isToepliz(lis, n, m): for i in range(n-1): for j in range(m-1): if lis[i][j]!=lis[i+1][j+1]: return 0 return 1" }, { "code": null, "e": 1989, "s": 1987, "text": "0" }, { "code": null, "e": 2018, "s": 1989, "text": "bhoomikasahu00104 months ago" }, { "code": null, "e": 2209, "s": 2018, "text": "bool isToepliz(int A[MAX][MAX],int N,int M){ for(int i=0; i<N-1; i++){ for(int j=0; j<M-1; j++){ if(A[i][j] != A[i+1][j+1]) return 0; } } return 1;}" }, { "code": null, "e": 2211, "s": 2209, "text": "0" }, { "code": null, "e": 2239, "s": 2211, "text": "pankajkumarravi6 months ago" }, { "code": null, "e": 2291, "s": 2239, "text": "********************* java solution ***************" }, { "code": null, "e": 2588, "s": 2293, "text": " boolean isToepliz(int mat[][], int N, int M) { int i =0,j=0; int resp = mat[i][j]; while (++i<N && ++j <M){ // found mismatch if (resp != mat[i][j]) return false; } return true;" }, { "code": null, "e": 2591, "s": 2588, "text": " }" }, { "code": null, "e": 2593, "s": 2591, "text": "0" }, { "code": null, "e": 2615, "s": 2593, "text": "mrshobhit7 months ago" }, { "code": null, "e": 2625, "s": 2615, "text": "Python 3:" }, { "code": null, "e": 2650, "s": 2625, "text": "Execution Time - 0.0 Sec" }, { "code": null, "e": 2887, "s": 2654, "text": "def isToepliz(lis, n, m):\n #code here\n for i in range(n):\n for j in range(m):\n if i==0 or j==0:\n continue\n if lis[i][j] != lis[i-1][j-1]:\n return False\n return True" }, { "code": null, "e": 3033, "s": 2887, "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": 3069, "s": 3033, "text": " Login to access your submissions. " }, { "code": null, "e": 3079, "s": 3069, "text": "\nProblem\n" }, { "code": null, "e": 3089, "s": 3079, "text": "\nContest\n" }, { "code": null, "e": 3152, "s": 3089, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3300, "s": 3152, "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": 3508, "s": 3300, "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": 3614, "s": 3508, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to get current state of activity in android?
This example demonstrates How to get current state of activity in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent" tools:context = ".MainActivity"> <TextView android:id = "@+id/text" android:textSize = "30sp" android:layout_width = "match_parent" android:layout_height = "match_parent" /> </LinearLayout> In the above code, we have taken text view to show activity state. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.app.ActivityManager; import android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Context; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView textView; @RequiresApi(api = Build.VERSION_CODES.N) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.text); textView.setText(" "+getLifecycle().getCurrentState()); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code
[ { "code": null, "e": 1137, "s": 1062, "text": "This example demonstrates How to get current state of activity in android." }, { "code": null, "e": 1266, "s": 1137, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1331, "s": 1266, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1891, "s": 1331, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"30sp\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>" }, { "code": null, "e": 1958, "s": 1891, "text": "In the above code, we have taken text view to show activity state." }, { "code": null, "e": 2015, "s": 1958, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2867, "s": 2015, "text": "package com.example.myapplication;\nimport android.app.ActivityManager;\nimport android.app.admin.DevicePolicyManager;\nimport android.content.ComponentName;\nimport android.content.Context;\nimport android.net.wifi.WifiInfo;\nimport android.net.wifi.WifiManager;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n textView.setText(\" \"+getLifecycle().getCurrentState());\n }\n}" }, { "code": null, "e": 3214, "s": 2867, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 3254, "s": 3214, "text": "Click here to download the project code" } ]
How to Use Nano Text Editor
Are you confused by all of the other text editors? then, this article is for you! Linux amateurs are often put off by other advanced text editors such as Vim and Emacs. While they are decent programs, they does require a bit of learning curve. Nano offers a perfect solution if you are looking for a small and friendly text editor. It offers many useful and productive features. Nano is a text editor for Unix-like systems or any other environments using a command line interface. It emulates the Pico text editor, a part of the Pine email client, which also provides additional functionality. In contrast to Pico, Nano is licensed under the GNU General Public License (GPL). Nano follows the path and opens the file if it exists. However, If it does not exist, it’ll start a new buffer with that filename in a directory. To run Nano Text editor, use the following command – To run Nano Text editor, use the following command – $ nano text_files/testfile The output should be like this − Nano text editor “commands” are commonly referred to as “shortcuts” such as read file, save file, close file etc. The most common commands are placed at the bottom of the screen, but there are many more. Note that, nano text editor does not use the Shiftkey. All shortcuts use lowercase letters and unmodified number keys. To see a list of valid shortcuts hitCtrl+G (in your Keyboard), the output should be like this – When you’re done looking at shortcuts, hit theCTRL+X to exit the help window. Suppose, if you’re working on a new text file and you want to save it, then call it as “writing out”(Ctrl+O). The output window should be like this – To move the cursor forward or backward, you can hit Ctrl+F andCtrl+B respectively. To move up and down one line at a time, then you can hit Ctrl+P andCtrl+N. In other words, you can use Right, Left, Up, and Down arrow keys (in your keyboard) respectively. If you want to mark any text hit CTRL+^ shortcut key. The output window should be like this- In the above image, we have marked “their drawing rooms.” To cut the marked text hitCtrl+K shortcut. If you want to paste your marked text, hitCtrl+U shortcut. The below are a list of shortcuts which can ease your work – Congratulations! Hope you perfect these basics of Nano text editor. In our next articles, we will come up with more such Linux based tricks and tips. Keep reading!
[ { "code": null, "e": 1441, "s": 1062, "text": "Are you confused by all of the other text editors? then, this article is for you! Linux amateurs are often put off by other advanced text editors such as Vim and Emacs. While they are decent programs, they does require a bit of learning curve. Nano offers a perfect solution if you are looking for a small and friendly text editor. It offers many useful and productive features." }, { "code": null, "e": 1738, "s": 1441, "text": "Nano is a text editor for Unix-like systems or any other environments using a command line interface. It emulates the Pico text editor, a part of the Pine email client, which also provides additional functionality. In contrast to Pico, Nano is licensed under the GNU General Public License (GPL)." }, { "code": null, "e": 1937, "s": 1738, "text": "Nano follows the path and opens the file if it exists. However, If it does not exist, it’ll start a new buffer with that filename in a directory. To run Nano Text editor, use the following command –" }, { "code": null, "e": 1990, "s": 1937, "text": "To run Nano Text editor, use the following command –" }, { "code": null, "e": 2017, "s": 1990, "text": "$ nano text_files/testfile" }, { "code": null, "e": 2050, "s": 2017, "text": "The output should be like this −" }, { "code": null, "e": 2373, "s": 2050, "text": "Nano text editor “commands” are commonly referred to as “shortcuts” such as read file, save file, close file etc. The most common commands are placed at the bottom of the screen, but there are many more. Note that, nano text editor does not use the Shiftkey. All shortcuts use lowercase letters and unmodified number keys." }, { "code": null, "e": 2469, "s": 2373, "text": "To see a list of valid shortcuts hitCtrl+G (in your Keyboard), the output should be like this –" }, { "code": null, "e": 2547, "s": 2469, "text": "When you’re done looking at shortcuts, hit theCTRL+X to exit the help window." }, { "code": null, "e": 2697, "s": 2547, "text": "Suppose, if you’re working on a new text file and you want to save it, then call it as “writing out”(Ctrl+O). The output window should be like this –" }, { "code": null, "e": 2781, "s": 2697, "text": "To move the cursor forward or backward, you can hit Ctrl+F andCtrl+B respectively." }, { "code": null, "e": 2954, "s": 2781, "text": "To move up and down one line at a time, then you can hit Ctrl+P andCtrl+N. In other words, you can use Right, Left, Up, and Down arrow keys (in your keyboard) respectively." }, { "code": null, "e": 3008, "s": 2954, "text": "If you want to mark any text hit CTRL+^ shortcut key." }, { "code": null, "e": 3047, "s": 3008, "text": "The output window should be like this-" }, { "code": null, "e": 3105, "s": 3047, "text": "In the above image, we have marked “their drawing rooms.”" }, { "code": null, "e": 3148, "s": 3105, "text": "To cut the marked text hitCtrl+K shortcut." }, { "code": null, "e": 3207, "s": 3148, "text": "If you want to paste your marked text, hitCtrl+U shortcut." }, { "code": null, "e": 3268, "s": 3207, "text": "The below are a list of shortcuts which can ease your work –" }, { "code": null, "e": 3432, "s": 3268, "text": "Congratulations! Hope you perfect these basics of Nano text editor. In our next articles, we will come up with more such Linux based tricks and tips. Keep reading!" } ]
How to Make A.I. That Looks into Trade Charts (And Use It for Trading) | by Ceyhun Derinbogaz | Towards Data Science
We are living in a world most of the things are increasingly depending on computer vision and deep learning. From tagging your summer photos automatically to facial detection by security cameras, it feels like we are living in a dystopian future. While AI revolution is still happening around us, spring of 2019 was interesting times for me. After finishing a deep learning course, I began tinkering with many different use cases of deep learning such as image classification to Natural Language Processing (NLP). After spending around a couple hours using Python and Keras libraries, I trained a simple Convolutional Neural Network (CNN) which was able to distinguish between a cat and a dog image. Sounds simple enough, some years ago that was a huge task to do and I was having a hard time to believe how simple neural networks solved a complex problem! Normally if you want to do image recognition using CV libraries, you have to do feature engineering, develop your own filters and hard code many features into the code. Even after many attempts, you would be left with an algorithm maybe %60–70 accurate which is far away from what we are able to do with machine learning today. I was completely blown away by the simplicity of deep learning. First I defined a very simple CNN architecture, then labelled my dataset with cat and dog images. After that start the training and watch training accuracy and validation accuracy to go up until a satisfactory metric is reached. That’s it!! Next up, load your model and weights file then run the model.predict command with the file you want to predict and boom! Result is there with the accuracy score! The simplicity and the accuracy of the deep learning was just beautiful! Around the same time, I developed an interest over economics and how this day trading thing works. I started reading the Life and Work Principles by Ray Dalio. (If you haven’t read it yet, I can only recommend it ) In his book, he talks about how his company created proprietary algorithms that made financial decisions to run his Hedge fund and become one of the most successful fund in the world. While the story was super inspiring, it led me to start thinking how about we don’t teach the computer anything and let itself figure things out. Unlike feature engineering in the past with Computer Vision, deep learning can also be used for creating algorithms which decide on when to buy or sell stocks, forex, oil whatever you can think of. If there is a pattern in the data, you don’t need to find it out yourself, it will be found by the Deep Learning and that was the beginning of the Inpredo project. So before we go in and create a money making machine (be cautious with my over optimist comments.) we need training data. LOTS OF IT! Thank god that is not going to be hard because we already have the access to CSV data from above link. All we need to do is create an algorithm which is able to look into historical data and create charts then classify them if the instrument (e.g. Eur/Usd) price was increased in the future or decreased. Because we have the historical data, we know what happened to the price at any given time in the data time frame, it is easy to classify the generated chart image. Creating charts is the easy part, we need couple of libraries and the function that I created just for this purpose which is called graphwerk.py (Kraftwerk, anyone?) So graphwerk is pretty straightforward, you just need to plug in historical data of the chosen instrument in list format. We will be printing charts which covers 12 hours/candles. So your list length must be 12. If you want to cover a bigger time frame then you need to increase your list length. About the granularity, you can go ahead and choose between hourly, daily even minutely data. It is perfectly fine if you wanna print charts with more candles, but I didn’t wanna introduce so much noise into the training data. import matplotlib.pyplot as pltimport mpl_financeimport numpy as npdef graphwerk(open, high, low, close, instrument): # Create Prefixes for correct data if instrument == 'XAU/USD': prefix = 'xau' elif instrument == 'USOil': prefix = 'USOil' elif instrument == 'XAGUSD': prefix = 'xag' else: print('Instrument prefix is not defined in graphwerk') return fig = plt.figure(num=1, figsize=(3, 3), dpi=50, facecolor='w', edgecolor='k') dx = fig.add_subplot(111) mpl_finance.candlestick2_ochl(dx, open, close, high, low, width=1.5, colorup='g', colordown='r', alpha=0.5) plt.autoscale() # Create a moving average overlay sma = convolve_sma(close, 3) smb = list(sma) diff = sma[-1] - sma[-2] for x in range(len(close) - len(smb)): smb.append(smb[-1] + diff) dx2 = dx.twinx() dx2.plot(smb, color="blue", linewidth=8, alpha=0.5) dx2.axis('off') dx.axis('off') timestamp = int(time.time()) file_name = realtime_data + str(prefix) +str(timestamp) + '.jpg' plt.savefig(file_name, bbox_inches='tight') #Uncomment this line to see the plot right after script runs. #plt.show plt.close() return file_name After running this script it will create the chart which looks like the following: I know that the image size is small, but for deep learning, you don’t need 4K resolution photos or graphs. Having something around 200x200 pixels is more than enough for most of the A.I. Deep Learning applications. Actually it is a good thing to use smaller size images because feeding a 4K image for Deep Learning will eventually require to have a super expensive GPU Cluster such as the new Nvidia DGX which costs around 20 Grand. The cool about Deep Learning is, if you are smart you can reduce your processing power substantially using lower resolution images which still carries the same amount of information :) If you also might have noticed, bars don’t really look like what it looks like in real life. The reason is I manipulated them on purpose to kinda embed additional information between the candles and reduced their transparency. This creates overlapping candles which can also carry information in the mixed colors of the overlapping region of the candles. On top of this semi-transparent candles there is a Simple Moving Average line (SMA) which is also reduced in transparency to create additional information when it is crossing over the candles. You can play around with the shape, size and transparency however you like to create your perfect training dataset. Step 2: Creating Loooooots of Images for Training Data Set So the above script is awesome for creating single images but we need more than that to train a neural network. I am talking about having thousands here. So as developers, we don’t just click the button for thousand times, right? We need to automate this to go over the whole csv file in a rolling time window manner and automatically place chart images in correct folders as ‘buy’ and ‘sell’. Logic is pretty simple, define the time window of 12, (which means 12-hour window in hourly csv file) and move the window 1 hour forward in each loop inside the for loop. In this way we will be able to create enough amount of samples depending on the size of the historical data. To be able to create enough amount of training data, you just need your clean csv data in the below format then the rest is only about waiting for the script to finish its complete loop on the data. You will need to create 2 folders for this which will be eventually filled with 2 types of data: Buy and Sell. A created chart will be saved into the ‘buy’ folder when the closing price of the last candle is lower than the next candles closing price. Another way around, ‘sell’ folder will include chart images if the last candle’s closing price is higher than the next candle’s price. Step 3: Training a simple Convolutional Neural Network After creating the dataset, we need to define a Neural Network architecture and then feed the training data for teaching the neural network to distinguish the difference between what is a likely buy or sell signal. If you have noticed, I am not talking about any kind of strategy or some kind of algorithm design to find out these patterns. Amazing thing about artificial intelligence is, it will find out the patterns by itself. At the moment there are many different kinds of convolutional network architectures designed for image classification. Xception is one of the award winning one but we are not going to use something that advanced at the moment. Our Model will be a basic convolutional network with dropout layers and fully connected layers like the following: model = Sequential()model.add(Convolution2D(nb_filters1, conv1_size, conv1_size, border_mode ='same', input_shape=(img_height, img_width , 3)))model.add(Activation('relu'))model.add(MaxPooling2D(pool_size=(pool_size, pool_size)))model.add(Convolution2D(nb_filters2, conv2_size, conv2_size, border_mode ="same"))model.add(Activation('relu'))model.add(MaxPooling2D(pool_size=(pool_size, pool_size), dim_ordering='th'))model.add(Convolution2D(nb_filters3, conv3_size, conv3_size, border_mode ='same'))model.add(Activation('relu'))model.add(MaxPooling2D(pool_size=(pool_size, pool_size), dim_ordering='th'))model.add(Flatten())model.add(Dense(1024))model.add(Activation('relu'))model.add(Dropout(0.5))model.add(Dense(classes_num, activation='softmax'))model.summary()model.compile(loss='categorical_crossentropy', optimizer=optimizers.rmsprop(), metrics=['accuracy']) After countless hours of fiddling with parameters and creating, reducing, filtering training data, ai model was able to ‘guess’ with 63 percent accuracy over a dataset of 2 years! As all sane person would do, I plugged this AI model into kraken’s live trading engine for BTC-USD trading and hopefully making some money and telling rag to riches stories. By the way if you want to get into API trading, I can only recommend Kraken. They are a regulated exchange with secure and stable APIs. Very interestingly, it really made money 10 days in a row reaching to %5.34 gains in this time frame. While this is happening, BTC-USD was down %3.29! So the cool stuff is, it doesn’t care if market is going up or down. It just shorts or longs the instrument according to the situation. So even in a case that everything is losing value in the market, this model is still able to make money. Total spending after creating such model to run the bot continuously costed me around 15$/month thanks to digitalocean’s super easy to use VM deployments. You can also give it a try with the following promo code and receive 100$ in credit to spin up a Virtual Machine. That equals to 3 months of free use. Just choose an ubuntu deployment with 1-click deployment and use the github repo that I attached at the end of the article. So the reason I wrote the article is to show you there is more stuff needs to be done. Predicting if a stock is going up or down is only the half of the story. If you don’t know how much the stock is going up or down in percentage will not help a lot since you don’t know when to take your gain. So obviously this AI model needs to be improved over time. It is also good to take into account that the AI model needs to be updated on a regular basis to adapt to changing market conditions. Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. If you want to run the code by yourself and see the results have a look at the github page: https://github.com/cderinbogaz/inpredo AI Domain Name Generator using GPT-2 Create Your Own Server for Gathering Cryptocurrency Data How to Hack Your Emotional Firmware and Stop Procrastinating How Learning Stoicism Helped Me In The Age Of Anxiety Disclaimer: I am not responsible for your losses if you use my code to trade on the market with your own money. Be safe, don’t take risks that you don’t fully understand. Some rights reserved
[ { "code": null, "e": 419, "s": 172, "text": "We are living in a world most of the things are increasingly depending on computer vision and deep learning. From tagging your summer photos automatically to facial detection by security cameras, it feels like we are living in a dystopian future." }, { "code": null, "e": 1357, "s": 419, "text": "While AI revolution is still happening around us, spring of 2019 was interesting times for me. After finishing a deep learning course, I began tinkering with many different use cases of deep learning such as image classification to Natural Language Processing (NLP). After spending around a couple hours using Python and Keras libraries, I trained a simple Convolutional Neural Network (CNN) which was able to distinguish between a cat and a dog image. Sounds simple enough, some years ago that was a huge task to do and I was having a hard time to believe how simple neural networks solved a complex problem! Normally if you want to do image recognition using CV libraries, you have to do feature engineering, develop your own filters and hard code many features into the code. Even after many attempts, you would be left with an algorithm maybe %60–70 accurate which is far away from what we are able to do with machine learning today." }, { "code": null, "e": 1824, "s": 1357, "text": "I was completely blown away by the simplicity of deep learning. First I defined a very simple CNN architecture, then labelled my dataset with cat and dog images. After that start the training and watch training accuracy and validation accuracy to go up until a satisfactory metric is reached. That’s it!! Next up, load your model and weights file then run the model.predict command with the file you want to predict and boom! Result is there with the accuracy score!" }, { "code": null, "e": 1897, "s": 1824, "text": "The simplicity and the accuracy of the deep learning was just beautiful!" }, { "code": null, "e": 2112, "s": 1897, "text": "Around the same time, I developed an interest over economics and how this day trading thing works. I started reading the Life and Work Principles by Ray Dalio. (If you haven’t read it yet, I can only recommend it )" }, { "code": null, "e": 2640, "s": 2112, "text": "In his book, he talks about how his company created proprietary algorithms that made financial decisions to run his Hedge fund and become one of the most successful fund in the world. While the story was super inspiring, it led me to start thinking how about we don’t teach the computer anything and let itself figure things out. Unlike feature engineering in the past with Computer Vision, deep learning can also be used for creating algorithms which decide on when to buy or sell stocks, forex, oil whatever you can think of." }, { "code": null, "e": 2804, "s": 2640, "text": "If there is a pattern in the data, you don’t need to find it out yourself, it will be found by the Deep Learning and that was the beginning of the Inpredo project." }, { "code": null, "e": 2938, "s": 2804, "text": "So before we go in and create a money making machine (be cautious with my over optimist comments.) we need training data. LOTS OF IT!" }, { "code": null, "e": 3407, "s": 2938, "text": "Thank god that is not going to be hard because we already have the access to CSV data from above link. All we need to do is create an algorithm which is able to look into historical data and create charts then classify them if the instrument (e.g. Eur/Usd) price was increased in the future or decreased. Because we have the historical data, we know what happened to the price at any given time in the data time frame, it is easy to classify the generated chart image." }, { "code": null, "e": 3573, "s": 3407, "text": "Creating charts is the easy part, we need couple of libraries and the function that I created just for this purpose which is called graphwerk.py (Kraftwerk, anyone?)" }, { "code": null, "e": 4096, "s": 3573, "text": "So graphwerk is pretty straightforward, you just need to plug in historical data of the chosen instrument in list format. We will be printing charts which covers 12 hours/candles. So your list length must be 12. If you want to cover a bigger time frame then you need to increase your list length. About the granularity, you can go ahead and choose between hourly, daily even minutely data. It is perfectly fine if you wanna print charts with more candles, but I didn’t wanna introduce so much noise into the training data." }, { "code": null, "e": 5303, "s": 4096, "text": "import matplotlib.pyplot as pltimport mpl_financeimport numpy as npdef graphwerk(open, high, low, close, instrument): # Create Prefixes for correct data if instrument == 'XAU/USD': prefix = 'xau' elif instrument == 'USOil': prefix = 'USOil' elif instrument == 'XAGUSD': prefix = 'xag' else: print('Instrument prefix is not defined in graphwerk') return fig = plt.figure(num=1, figsize=(3, 3), dpi=50, facecolor='w', edgecolor='k') dx = fig.add_subplot(111) mpl_finance.candlestick2_ochl(dx, open, close, high, low, width=1.5, colorup='g', colordown='r', alpha=0.5) plt.autoscale() # Create a moving average overlay sma = convolve_sma(close, 3) smb = list(sma) diff = sma[-1] - sma[-2] for x in range(len(close) - len(smb)): smb.append(smb[-1] + diff) dx2 = dx.twinx() dx2.plot(smb, color=\"blue\", linewidth=8, alpha=0.5) dx2.axis('off') dx.axis('off') timestamp = int(time.time()) file_name = realtime_data + str(prefix) +str(timestamp) + '.jpg' plt.savefig(file_name, bbox_inches='tight') #Uncomment this line to see the plot right after script runs. #plt.show plt.close() return file_name" }, { "code": null, "e": 5386, "s": 5303, "text": "After running this script it will create the chart which looks like the following:" }, { "code": null, "e": 6004, "s": 5386, "text": "I know that the image size is small, but for deep learning, you don’t need 4K resolution photos or graphs. Having something around 200x200 pixels is more than enough for most of the A.I. Deep Learning applications. Actually it is a good thing to use smaller size images because feeding a 4K image for Deep Learning will eventually require to have a super expensive GPU Cluster such as the new Nvidia DGX which costs around 20 Grand. The cool about Deep Learning is, if you are smart you can reduce your processing power substantially using lower resolution images which still carries the same amount of information :)" }, { "code": null, "e": 6359, "s": 6004, "text": "If you also might have noticed, bars don’t really look like what it looks like in real life. The reason is I manipulated them on purpose to kinda embed additional information between the candles and reduced their transparency. This creates overlapping candles which can also carry information in the mixed colors of the overlapping region of the candles." }, { "code": null, "e": 6668, "s": 6359, "text": "On top of this semi-transparent candles there is a Simple Moving Average line (SMA) which is also reduced in transparency to create additional information when it is crossing over the candles. You can play around with the shape, size and transparency however you like to create your perfect training dataset." }, { "code": null, "e": 6727, "s": 6668, "text": "Step 2: Creating Loooooots of Images for Training Data Set" }, { "code": null, "e": 7401, "s": 6727, "text": "So the above script is awesome for creating single images but we need more than that to train a neural network. I am talking about having thousands here. So as developers, we don’t just click the button for thousand times, right? We need to automate this to go over the whole csv file in a rolling time window manner and automatically place chart images in correct folders as ‘buy’ and ‘sell’. Logic is pretty simple, define the time window of 12, (which means 12-hour window in hourly csv file) and move the window 1 hour forward in each loop inside the for loop. In this way we will be able to create enough amount of samples depending on the size of the historical data." }, { "code": null, "e": 7986, "s": 7401, "text": "To be able to create enough amount of training data, you just need your clean csv data in the below format then the rest is only about waiting for the script to finish its complete loop on the data. You will need to create 2 folders for this which will be eventually filled with 2 types of data: Buy and Sell. A created chart will be saved into the ‘buy’ folder when the closing price of the last candle is lower than the next candles closing price. Another way around, ‘sell’ folder will include chart images if the last candle’s closing price is higher than the next candle’s price." }, { "code": null, "e": 8041, "s": 7986, "text": "Step 3: Training a simple Convolutional Neural Network" }, { "code": null, "e": 8256, "s": 8041, "text": "After creating the dataset, we need to define a Neural Network architecture and then feed the training data for teaching the neural network to distinguish the difference between what is a likely buy or sell signal." }, { "code": null, "e": 8471, "s": 8256, "text": "If you have noticed, I am not talking about any kind of strategy or some kind of algorithm design to find out these patterns. Amazing thing about artificial intelligence is, it will find out the patterns by itself." }, { "code": null, "e": 8698, "s": 8471, "text": "At the moment there are many different kinds of convolutional network architectures designed for image classification. Xception is one of the award winning one but we are not going to use something that advanced at the moment." }, { "code": null, "e": 8813, "s": 8698, "text": "Our Model will be a basic convolutional network with dropout layers and fully connected layers like the following:" }, { "code": null, "e": 9719, "s": 8813, "text": "model = Sequential()model.add(Convolution2D(nb_filters1, conv1_size, conv1_size, border_mode ='same', input_shape=(img_height, img_width , 3)))model.add(Activation('relu'))model.add(MaxPooling2D(pool_size=(pool_size, pool_size)))model.add(Convolution2D(nb_filters2, conv2_size, conv2_size, border_mode =\"same\"))model.add(Activation('relu'))model.add(MaxPooling2D(pool_size=(pool_size, pool_size), dim_ordering='th'))model.add(Convolution2D(nb_filters3, conv3_size, conv3_size, border_mode ='same'))model.add(Activation('relu'))model.add(MaxPooling2D(pool_size=(pool_size, pool_size), dim_ordering='th'))model.add(Flatten())model.add(Dense(1024))model.add(Activation('relu'))model.add(Dropout(0.5))model.add(Dense(classes_num, activation='softmax'))model.summary()model.compile(loss='categorical_crossentropy', optimizer=optimizers.rmsprop(), metrics=['accuracy'])" }, { "code": null, "e": 9899, "s": 9719, "text": "After countless hours of fiddling with parameters and creating, reducing, filtering training data, ai model was able to ‘guess’ with 63 percent accuracy over a dataset of 2 years!" }, { "code": null, "e": 10209, "s": 9899, "text": "As all sane person would do, I plugged this AI model into kraken’s live trading engine for BTC-USD trading and hopefully making some money and telling rag to riches stories. By the way if you want to get into API trading, I can only recommend Kraken. They are a regulated exchange with secure and stable APIs." }, { "code": null, "e": 10360, "s": 10209, "text": "Very interestingly, it really made money 10 days in a row reaching to %5.34 gains in this time frame. While this is happening, BTC-USD was down %3.29!" }, { "code": null, "e": 10601, "s": 10360, "text": "So the cool stuff is, it doesn’t care if market is going up or down. It just shorts or longs the instrument according to the situation. So even in a case that everything is losing value in the market, this model is still able to make money." }, { "code": null, "e": 11031, "s": 10601, "text": "Total spending after creating such model to run the bot continuously costed me around 15$/month thanks to digitalocean’s super easy to use VM deployments. You can also give it a try with the following promo code and receive 100$ in credit to spin up a Virtual Machine. That equals to 3 months of free use. Just choose an ubuntu deployment with 1-click deployment and use the github repo that I attached at the end of the article." }, { "code": null, "e": 11327, "s": 11031, "text": "So the reason I wrote the article is to show you there is more stuff needs to be done. Predicting if a stock is going up or down is only the half of the story. If you don’t know how much the stock is going up or down in percentage will not help a lot since you don’t know when to take your gain." }, { "code": null, "e": 11520, "s": 11327, "text": "So obviously this AI model needs to be improved over time. It is also good to take into account that the AI model needs to be updated on a regular basis to adapt to changing market conditions." }, { "code": null, "e": 11820, "s": 11520, "text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details." }, { "code": null, "e": 11951, "s": 11820, "text": "If you want to run the code by yourself and see the results have a look at the github page: https://github.com/cderinbogaz/inpredo" }, { "code": null, "e": 11988, "s": 11951, "text": "AI Domain Name Generator using GPT-2" }, { "code": null, "e": 12045, "s": 11988, "text": "Create Your Own Server for Gathering Cryptocurrency Data" }, { "code": null, "e": 12106, "s": 12045, "text": "How to Hack Your Emotional Firmware and Stop Procrastinating" }, { "code": null, "e": 12160, "s": 12106, "text": "How Learning Stoicism Helped Me In The Age Of Anxiety" }, { "code": null, "e": 12331, "s": 12160, "text": "Disclaimer: I am not responsible for your losses if you use my code to trade on the market with your own money. Be safe, don’t take risks that you don’t fully understand." } ]
How to remove a particular character from a String.
Following example shows how to remove a character from a particular position from a string with the help of removeCharAt(string, position) method. Live Demo public class Sample { public static void main(String args[]) { String str = "this is Java"; System.out.println(removeCharAt(str, 3)); } public static String removeCharAt(String s, int pos) { return s.substring(0, pos) + s.substring(pos + 1); } } this is Java
[ { "code": null, "e": 1209, "s": 1062, "text": "Following example shows how to remove a character from a particular position from a string with the help of removeCharAt(string, position) method." }, { "code": null, "e": 1219, "s": 1209, "text": "Live Demo" }, { "code": null, "e": 1495, "s": 1219, "text": "public class Sample {\n public static void main(String args[]) {\n String str = \"this is Java\";\n System.out.println(removeCharAt(str, 3));\n }\n public static String removeCharAt(String s, int pos) {\n return s.substring(0, pos) + s.substring(pos + 1);\n }\n}" }, { "code": null, "e": 1508, "s": 1495, "text": "this is Java" } ]
Train Your Own Chess AI. Watch your creation defeat you | by Logan Spears | Towards Data Science
TLDR: Colab Link Deep Learning has taken over the computer chess world. In 2017 AlphaZero, an iteration of AlphaGo targeting chess, mesmerized the chess fans by handlely defeating Stockfish. New developments in the space such as Leela Zero (an open source AlphaZero implementation that happens to use my chess lib) and Stockfish NNUE (efficiently updatable neural net reversed) show neural nets will continue to dominate chess for the foreseeable future. As a chess enthusiast and AI practitioner, I set out to create my own chess AI but was discouraged by a daunting rumor: AlphaZero cost $35MM to train. AlphaZero trains entirely through reinforcement learning and self play to avoid outside dependencies. While obviously effective, self play is incredibly inefficient from a cost perspective. Today’s engines can already tell the difference between a good position and bad position. This prior knowledge can be used to bootstrap the learning process and make it possible to train a chess AI with very limited cost (or free on Colab). Lets try it! And train a neural net using supervised machine learning with the dataset coming from existing engines. How does an engine determine if a position is good? Given a position, engines return a score of how good the position is from white perspective. This score is called an evaluation, typically shortened to eval, and the eval function is at the heart of chess engines. The eval is a realitive strength measurement denominated in pawn equivalents. For example if white is up a pawn, the evaluation will be +1. If black is up a knight the eval will be -3. Raw material isn’t the only thing that determines the eval, positional information and future moves are also taken into account. Traditionally the eval function was implemented by handcrafted algorithms measuring concepts like material imbalance, piece mobility, and king safety quantitatively. These direct measurement, combined with iterative deeping alone produce super human results. Neural networks can substitute for these handcrafted algorithms and return the eval directly eliminating the need for specialized coding. Overall the eval function takes in a position and returns an evaluation score. How do we turn that into a model? The output, eval, can be represented by a single float based neuron. The input, representing the board position, can be encoded using bitboards (64 bits, one for each square on the chess board) for each piece type and a few remaining bits for move index, color to move, and en passant square. Together this input data forms a string of 808 bits (1s and 0s) that can be converted to floats and inputted into the model directly. Now that we planned out our inputs, outputs, and general model concept, lets start building a dataset. I play on Lichess.com because it’s free, open source, and run by developers. Lichess hosts downloadable monthly shards of every game played on the website. July 2021 contains 92+ million games. In the notes section it mentioned a very important detail: “About 6% of the games include Stockfish analysis evaluations” which in this case would be 5.5+ million games. With the average chess game lasting around 40 moves, 80 positions (each side gets a turn per “move”), July should contain 441,600,000 non-unique positions. This seems sufficient for creating our initial dataset. Lichess’ monthly shards are encoded as .pgn.bz2 files. The file extension .bz2 is a form of compression and .pgn is “Portable Game Notation” which is a text based format for encoding chess games by as a series of moves in Algebraic Notation. Here is the text of a single PGN file record: [Event "Rated Bullet tournament https://lichess.org/tournament/yc1WW2Ox"][Site "https://lichess.org/PpwPOZMq"][Date "2017.04.01"][Round "-"][White "Abbot"][Black "Costello"][Result "0-1"][UTCDate "2017.04.01"][UTCTime "11:32:01"][WhiteElo "2100"][BlackElo "2000"][WhiteRatingDiff "-4"][BlackRatingDiff "+1"][WhiteTitle "FM"][ECO "B30"][Opening "Sicilian Defense: Old Sicilian"][TimeControl "300+0"][Termination "Time forfeit"]1. e4 { [%eval 0.17] [%clk 0:00:30] } c5 { [%eval 0.19] [%clk 0:00:30] }2. Nf3 { [%eval 0.25] [%clk 0:00:29] } 2... Nc6 { [%eval 0.33] [%clk 0:00:30] }3. Bc4 { [%eval -0.13] [%clk 0:00:28] } 3... e6 { [%eval -0.04] [%clk 0:00:30] }4. c3 { [%eval -0.4] [%clk 0:00:27] } 4... b5? { [%eval 1.18] [%clk 0:00:30] }5. Bb3?! { [%eval 0.21] [%clk 0:00:26] } 5... c4 { [%eval 0.32] [%clk 0:00:29] }6. Bc2 { [%eval 0.2] [%clk 0:00:25] } 6... a5 { [%eval 0.6] [%clk 0:00:29] }7. d4 { [%eval 0.29] [%clk 0:00:23] } 7... cxd3 { [%eval 0.6] [%clk 0:00:27] }8. Qxd3 { [%eval 0.12] [%clk 0:00:22] } 8... Nf6 { [%eval 0.52] [%clk 0:00:26] }9. e5 { [%eval 0.39] [%clk 0:00:21] } 9... Nd5 { [%eval 0.45] [%clk 0:00:25] }10. Bg5?! { [%eval -0.44] [%clk 0:00:18] } 10... Qc7 { [%eval -0.12] [%clk 0:00:23] }11. Nbd2?? { [%eval -3.15] [%clk 0:00:14] } 11... h6 { [%eval -2.99] [%clk 0:00:23] }12. Bh4 { [%eval -3.0] [%clk 0:00:11] } 12... Ba6? { [%eval -0.12] [%clk 0:00:23] }13. b3?? { [%eval -4.14] [%clk 0:00:02] } 13... Nf4? { [%eval -2.73] [%clk 0:00:21] } 0-1 After each move, within a comments section, Stockfish based evaluations are written in a custom text format. 1. e4 { [%eval 0.24] [%clk 0:05:00] } This gives us eval paired with position (computed from the series of moves). The original compressed monthly shard for July 2021 is 25.2 GB so a single CSV file is likely out of the question. An SQLite database with proper indexes seems more appropriate. The schema includes the FEN (text encoding of the position for debugging), binary for direct use by the model, and the evaluation for the training output: > select * from evaluations limit 7;id|fen|binary|eval1|rnbqkbnr/pppppppp/8/8/3P4/8/PPP1PPPP/RNBQKBNR b KQkq d3 0 1|0.02|rnbqkbnr/ppp1pppp/8/3p4/3P4/8/PPP1PPPP/RNBQKBNR w KQkq d6 0 2|0.273|rnbqkbnr/ppp1pppp/8/3p4/2PP4/8/PP2PPPP/RNBQKBNR b KQkq c3 0 2|0.04|rnbqkbnr/ppp2ppp/4p3/3p4/2PP4/8/PP2PPPP/RNBQKBNR w KQkq - 0 3|0.095|rnbqkbnr/ppp2ppp/4p3/3P4/3P4/8/PP2PPPP/RNBQKBNR b KQkq - 0 3|0.16|rnbqkbnr/ppp2ppp/8/3p4/3P4/8/PP2PPPP/RNBQKBNR w KQkq - 0 4|0.07|rnbqkbnr/ppp2ppp/8/3p4/3P4/2N5/PP2PPPP/R1BQKBNR b KQkq - 1 4|0.09 Now that we have our data lets start training! For this project lets use Pytorch Lightning which is a convience layer on top of Pytorch. In order to train, we have to primaily implement two classes: Dataset and LightningModule. Due to the large size of the dataset (the db ended up with 37MM positions), an IterableDataset makes the most sense and treats the data as an infinite stream. The __next__ method just needs to return a random row of the data. Since we aren’t worried about overfitting on tens of millions of positions, we don’t need to split the data into training, validation, and test sets. EvaluationDataset takes single random row from the SQLite table and preprocesses it by extracting the binary value in raw bytes, converting those bytes to floats using numpy’s frombuffer and unpackbits functions, and forming the required 808 length float array as input. The evaluation value is is extracted and bounded between -15 and 15. Bounding protects against extremely winning position dominating the loss function (such as +45 white). +-15 is very certainly winning for each side and evaluating past that is unnecessary for our purposes and will slow down training convergence. The model consists of N layers (initially set to 4) of 808 neurons until a final output layer of 1 neural which directly outputs the evaluation. An L1 loss, or the absolute average difference between labels and predictions, is used because the output is intuitive. For example if the L1 loss is 2.0, then on average the model differs from stockfish by 2 pawns of evaluation. Success, loss is going down! Eventually two versions of our model were trained. One with four layers reaching a loss of 1.29 and one with six layers and a loss of 1.06. The best way to test our AI is to play it! Using alpha beta search, transposition tables, and few other standard chess AI techniques we can create a full chess engine to play against. The AI client was implemented in Go (so I could use my chess lib) and the model was hosted on a colocated python based gRPC server serving the model on Nvidia 2080 accelerated linux server I have at home. The Go based chess engine is less than 300 LOC, here is the code for the primary Move method. And here is the pthon gRPC server implementation serving the model. It takes batches of encoded positions and returns evaluations. Now that we have our bot hooked up and our model serving board evaluations we are ready to play! The bot’s opponent (myself) has a measly ~1200 average rating on Lichess across rapid, blitz, and bullet. There were no time controls on these games. I took as long as a I needed and the AI took around 20 secs per move. In the two games I played against the bot, I charitably gave myself white. Medium unfortunately doesn’t allow the embeddings so I have included a Gif of the entire game as well as a link to the full game on Lichess complete with a Stockfish analysis. lichess.org I played E4 (I always play E4), and the AI chose C5 known as the “Sicilian Defense”. The first move by black is fascinating because the AI has no opening book and no game play experience, yet chose one of the most popular defenses for black. The opening was pretty balanced with no side gaining a clear advantage until I trade my dark square bishop for the black knight on move 10. In hindsight, this opened up black’s dark square bishop and exposed the weakness on the B2 square. I then compounded the error with another bishop for knight trade on move 13 which dropped a pawn and allowed attacking lines from black’s queen. I hunkered down and defended with the best of my ability and got the game close to even by move 25. By neglecting to take my pawn, black underestimated the potential promotion on E8 and blundered on move 26 allowing knight to B3 with the idea that if the knight takes I can force a rook trade and the bishop can’t defend the A pawn from promotion. Unfortunately I didn’t see that either and I let my temporary advantage slip away. The game ended with a serious of uneventful moves and I agreed to a draw (with Stockfish agreeing the position was even). lichess.org Opening with the French, black allowed me to take the center by move 8 resulting in a position stockfish evaluates +1.1 for white. Interestingly Stockfish wanted me to castle queen side and push my advantage in the center. I have a habit of castling king side and played in a more safe style to avoid unfamiliar play. On move 11, black offers a queen trade that I accepted to take the queens off the board reducing tactical opportunities that could favor the AI. I was doing well until I blundered on move 16. I didn’t see that black could skewer my rooks with its light square bishop and win an exchange. With a pawn push on move 32 not resulting in winning chances (even with the balancing of rooks), black gradually picked off my pawns forcing me to resign. While the AI won, I couldn’t tell if the computer had gotten better or my blunder made the comparison unfair. The fairest way to settle the matter was have the AI versions play each other. lichess.org Initially I gave white to the 4 layer AI, but it ended in a bland draw so I revered the color assignments. The second game resulted in an incredibly exciting match. The fast paced action started on move 12 with the bishop taking the G7 pawn and forking the knight and rook on H6 and H8 respectively. Black responded with a wild sacrifice using the dark square bishop followed by a queen check. White calmly deflected and finally claimed the hanging rook. On move 16 black sacrificed another piece, this time a knight, in order to keep the attack on white’s king alive. After defending and throwing in a queen check of its own, white confidently checked the black king on move 22. This was especially dangerous because black, if given a free move, can checkmate in one! White found the force mating sequence, prevailed in an exhilarating checkmate, and proved that its lower training loss resulted in better chess. The most remarkable aspect of analyzing these games is how “human” the AI feels. Common openings, waiting for blunders, and attempting comebacks with wild sacrifices are standard fair in online human play. There is certainly room for improvement in our approach. A lot of well known techniques were not used in order to keep this project’s complexity manageable and focus on the AI portions: Move ordering to prioritize searching “interesting” move sequences Endgame Tablebase for precomputed winning endgame positions Opening Book for precomputed openings Only search a couple hundred thousand positions at 4 ply Many others There is also some flaws in our simplistic model and training procedures Move counts are inputted into the model in bits instead of the number as a float The model architecture was the first design attempted with no optimization Learning rate and batch size schedulers could result in lower total loss Chess positions are unique in the database and therefore later positions that are more likely to be unique are over represented in the dataset Most games are played by amateurs and the search space of superior play might be under represented The model could be trained for MUCH longer Overall this was a lot of fun! Supervised training on existing engine evaluation is a faster and more economical path to weight initialization than self play and monte carlo tree search (a la AlphaZero) and a playable model can be generated in a few GPU hours. Hope you enjoyed this post and I look forward to a link of your AI’s games in the comments!
[ { "code": null, "e": 189, "s": 172, "text": "TLDR: Colab Link" }, { "code": null, "e": 627, "s": 189, "text": "Deep Learning has taken over the computer chess world. In 2017 AlphaZero, an iteration of AlphaGo targeting chess, mesmerized the chess fans by handlely defeating Stockfish. New developments in the space such as Leela Zero (an open source AlphaZero implementation that happens to use my chess lib) and Stockfish NNUE (efficiently updatable neural net reversed) show neural nets will continue to dominate chess for the foreseeable future." }, { "code": null, "e": 1326, "s": 627, "text": "As a chess enthusiast and AI practitioner, I set out to create my own chess AI but was discouraged by a daunting rumor: AlphaZero cost $35MM to train. AlphaZero trains entirely through reinforcement learning and self play to avoid outside dependencies. While obviously effective, self play is incredibly inefficient from a cost perspective. Today’s engines can already tell the difference between a good position and bad position. This prior knowledge can be used to bootstrap the learning process and make it possible to train a chess AI with very limited cost (or free on Colab). Lets try it! And train a neural net using supervised machine learning with the dataset coming from existing engines." }, { "code": null, "e": 1906, "s": 1326, "text": "How does an engine determine if a position is good? Given a position, engines return a score of how good the position is from white perspective. This score is called an evaluation, typically shortened to eval, and the eval function is at the heart of chess engines. The eval is a realitive strength measurement denominated in pawn equivalents. For example if white is up a pawn, the evaluation will be +1. If black is up a knight the eval will be -3. Raw material isn’t the only thing that determines the eval, positional information and future moves are also taken into account." }, { "code": null, "e": 2416, "s": 1906, "text": "Traditionally the eval function was implemented by handcrafted algorithms measuring concepts like material imbalance, piece mobility, and king safety quantitatively. These direct measurement, combined with iterative deeping alone produce super human results. Neural networks can substitute for these handcrafted algorithms and return the eval directly eliminating the need for specialized coding. Overall the eval function takes in a position and returns an evaluation score. How do we turn that into a model?" }, { "code": null, "e": 2843, "s": 2416, "text": "The output, eval, can be represented by a single float based neuron. The input, representing the board position, can be encoded using bitboards (64 bits, one for each square on the chess board) for each piece type and a few remaining bits for move index, color to move, and en passant square. Together this input data forms a string of 808 bits (1s and 0s) that can be converted to floats and inputted into the model directly." }, { "code": null, "e": 2946, "s": 2843, "text": "Now that we planned out our inputs, outputs, and general model concept, lets start building a dataset." }, { "code": null, "e": 3522, "s": 2946, "text": "I play on Lichess.com because it’s free, open source, and run by developers. Lichess hosts downloadable monthly shards of every game played on the website. July 2021 contains 92+ million games. In the notes section it mentioned a very important detail: “About 6% of the games include Stockfish analysis evaluations” which in this case would be 5.5+ million games. With the average chess game lasting around 40 moves, 80 positions (each side gets a turn per “move”), July should contain 441,600,000 non-unique positions. This seems sufficient for creating our initial dataset." }, { "code": null, "e": 3810, "s": 3522, "text": "Lichess’ monthly shards are encoded as .pgn.bz2 files. The file extension .bz2 is a form of compression and .pgn is “Portable Game Notation” which is a text based format for encoding chess games by as a series of moves in Algebraic Notation. Here is the text of a single PGN file record:" }, { "code": null, "e": 5280, "s": 3810, "text": "[Event \"Rated Bullet tournament https://lichess.org/tournament/yc1WW2Ox\"][Site \"https://lichess.org/PpwPOZMq\"][Date \"2017.04.01\"][Round \"-\"][White \"Abbot\"][Black \"Costello\"][Result \"0-1\"][UTCDate \"2017.04.01\"][UTCTime \"11:32:01\"][WhiteElo \"2100\"][BlackElo \"2000\"][WhiteRatingDiff \"-4\"][BlackRatingDiff \"+1\"][WhiteTitle \"FM\"][ECO \"B30\"][Opening \"Sicilian Defense: Old Sicilian\"][TimeControl \"300+0\"][Termination \"Time forfeit\"]1. e4 { [%eval 0.17] [%clk 0:00:30] } c5 { [%eval 0.19] [%clk 0:00:30] }2. Nf3 { [%eval 0.25] [%clk 0:00:29] } 2... Nc6 { [%eval 0.33] [%clk 0:00:30] }3. Bc4 { [%eval -0.13] [%clk 0:00:28] } 3... e6 { [%eval -0.04] [%clk 0:00:30] }4. c3 { [%eval -0.4] [%clk 0:00:27] } 4... b5? { [%eval 1.18] [%clk 0:00:30] }5. Bb3?! { [%eval 0.21] [%clk 0:00:26] } 5... c4 { [%eval 0.32] [%clk 0:00:29] }6. Bc2 { [%eval 0.2] [%clk 0:00:25] } 6... a5 { [%eval 0.6] [%clk 0:00:29] }7. d4 { [%eval 0.29] [%clk 0:00:23] } 7... cxd3 { [%eval 0.6] [%clk 0:00:27] }8. Qxd3 { [%eval 0.12] [%clk 0:00:22] } 8... Nf6 { [%eval 0.52] [%clk 0:00:26] }9. e5 { [%eval 0.39] [%clk 0:00:21] } 9... Nd5 { [%eval 0.45] [%clk 0:00:25] }10. Bg5?! { [%eval -0.44] [%clk 0:00:18] } 10... Qc7 { [%eval -0.12] [%clk 0:00:23] }11. Nbd2?? { [%eval -3.15] [%clk 0:00:14] } 11... h6 { [%eval -2.99] [%clk 0:00:23] }12. Bh4 { [%eval -3.0] [%clk 0:00:11] } 12... Ba6? { [%eval -0.12] [%clk 0:00:23] }13. b3?? { [%eval -4.14] [%clk 0:00:02] } 13... Nf4? { [%eval -2.73] [%clk 0:00:21] } 0-1" }, { "code": null, "e": 5389, "s": 5280, "text": "After each move, within a comments section, Stockfish based evaluations are written in a custom text format." }, { "code": null, "e": 5427, "s": 5389, "text": "1. e4 { [%eval 0.24] [%clk 0:05:00] }" }, { "code": null, "e": 5837, "s": 5427, "text": "This gives us eval paired with position (computed from the series of moves). The original compressed monthly shard for July 2021 is 25.2 GB so a single CSV file is likely out of the question. An SQLite database with proper indexes seems more appropriate. The schema includes the FEN (text encoding of the position for debugging), binary for direct use by the model, and the evaluation for the training output:" }, { "code": null, "e": 6357, "s": 5837, "text": "> select * from evaluations limit 7;id|fen|binary|eval1|rnbqkbnr/pppppppp/8/8/3P4/8/PPP1PPPP/RNBQKBNR b KQkq d3 0 1|0.02|rnbqkbnr/ppp1pppp/8/3p4/3P4/8/PPP1PPPP/RNBQKBNR w KQkq d6 0 2|0.273|rnbqkbnr/ppp1pppp/8/3p4/2PP4/8/PP2PPPP/RNBQKBNR b KQkq c3 0 2|0.04|rnbqkbnr/ppp2ppp/4p3/3p4/2PP4/8/PP2PPPP/RNBQKBNR w KQkq - 0 3|0.095|rnbqkbnr/ppp2ppp/4p3/3P4/3P4/8/PP2PPPP/RNBQKBNR b KQkq - 0 3|0.16|rnbqkbnr/ppp2ppp/8/3p4/3P4/8/PP2PPPP/RNBQKBNR w KQkq - 0 4|0.07|rnbqkbnr/ppp2ppp/8/3p4/3P4/2N5/PP2PPPP/R1BQKBNR b KQkq - 1 4|0.09" }, { "code": null, "e": 6404, "s": 6357, "text": "Now that we have our data lets start training!" }, { "code": null, "e": 6961, "s": 6404, "text": "For this project lets use Pytorch Lightning which is a convience layer on top of Pytorch. In order to train, we have to primaily implement two classes: Dataset and LightningModule. Due to the large size of the dataset (the db ended up with 37MM positions), an IterableDataset makes the most sense and treats the data as an infinite stream. The __next__ method just needs to return a random row of the data. Since we aren’t worried about overfitting on tens of millions of positions, we don’t need to split the data into training, validation, and test sets." }, { "code": null, "e": 7547, "s": 6961, "text": "EvaluationDataset takes single random row from the SQLite table and preprocesses it by extracting the binary value in raw bytes, converting those bytes to floats using numpy’s frombuffer and unpackbits functions, and forming the required 808 length float array as input. The evaluation value is is extracted and bounded between -15 and 15. Bounding protects against extremely winning position dominating the loss function (such as +45 white). +-15 is very certainly winning for each side and evaluating past that is unnecessary for our purposes and will slow down training convergence." }, { "code": null, "e": 7922, "s": 7547, "text": "The model consists of N layers (initially set to 4) of 808 neurons until a final output layer of 1 neural which directly outputs the evaluation. An L1 loss, or the absolute average difference between labels and predictions, is used because the output is intuitive. For example if the L1 loss is 2.0, then on average the model differs from stockfish by 2 pawns of evaluation." }, { "code": null, "e": 8091, "s": 7922, "text": "Success, loss is going down! Eventually two versions of our model were trained. One with four layers reaching a loss of 1.29 and one with six layers and a loss of 1.06." }, { "code": null, "e": 8480, "s": 8091, "text": "The best way to test our AI is to play it! Using alpha beta search, transposition tables, and few other standard chess AI techniques we can create a full chess engine to play against. The AI client was implemented in Go (so I could use my chess lib) and the model was hosted on a colocated python based gRPC server serving the model on Nvidia 2080 accelerated linux server I have at home." }, { "code": null, "e": 8574, "s": 8480, "text": "The Go based chess engine is less than 300 LOC, here is the code for the primary Move method." }, { "code": null, "e": 8705, "s": 8574, "text": "And here is the pthon gRPC server implementation serving the model. It takes batches of encoded positions and returns evaluations." }, { "code": null, "e": 9097, "s": 8705, "text": "Now that we have our bot hooked up and our model serving board evaluations we are ready to play! The bot’s opponent (myself) has a measly ~1200 average rating on Lichess across rapid, blitz, and bullet. There were no time controls on these games. I took as long as a I needed and the AI took around 20 secs per move. In the two games I played against the bot, I charitably gave myself white." }, { "code": null, "e": 9273, "s": 9097, "text": "Medium unfortunately doesn’t allow the embeddings so I have included a Gif of the entire game as well as a link to the full game on Lichess complete with a Stockfish analysis." }, { "code": null, "e": 9285, "s": 9273, "text": "lichess.org" }, { "code": null, "e": 10464, "s": 9285, "text": "I played E4 (I always play E4), and the AI chose C5 known as the “Sicilian Defense”. The first move by black is fascinating because the AI has no opening book and no game play experience, yet chose one of the most popular defenses for black. The opening was pretty balanced with no side gaining a clear advantage until I trade my dark square bishop for the black knight on move 10. In hindsight, this opened up black’s dark square bishop and exposed the weakness on the B2 square. I then compounded the error with another bishop for knight trade on move 13 which dropped a pawn and allowed attacking lines from black’s queen. I hunkered down and defended with the best of my ability and got the game close to even by move 25. By neglecting to take my pawn, black underestimated the potential promotion on E8 and blundered on move 26 allowing knight to B3 with the idea that if the knight takes I can force a rook trade and the bishop can’t defend the A pawn from promotion. Unfortunately I didn’t see that either and I let my temporary advantage slip away. The game ended with a serious of uneventful moves and I agreed to a draw (with Stockfish agreeing the position was even)." }, { "code": null, "e": 10476, "s": 10464, "text": "lichess.org" }, { "code": null, "e": 11237, "s": 10476, "text": "Opening with the French, black allowed me to take the center by move 8 resulting in a position stockfish evaluates +1.1 for white. Interestingly Stockfish wanted me to castle queen side and push my advantage in the center. I have a habit of castling king side and played in a more safe style to avoid unfamiliar play. On move 11, black offers a queen trade that I accepted to take the queens off the board reducing tactical opportunities that could favor the AI. I was doing well until I blundered on move 16. I didn’t see that black could skewer my rooks with its light square bishop and win an exchange. With a pawn push on move 32 not resulting in winning chances (even with the balancing of rooks), black gradually picked off my pawns forcing me to resign." }, { "code": null, "e": 11426, "s": 11237, "text": "While the AI won, I couldn’t tell if the computer had gotten better or my blunder made the comparison unfair. The fairest way to settle the matter was have the AI versions play each other." }, { "code": null, "e": 11438, "s": 11426, "text": "lichess.org" }, { "code": null, "e": 12352, "s": 11438, "text": "Initially I gave white to the 4 layer AI, but it ended in a bland draw so I revered the color assignments. The second game resulted in an incredibly exciting match. The fast paced action started on move 12 with the bishop taking the G7 pawn and forking the knight and rook on H6 and H8 respectively. Black responded with a wild sacrifice using the dark square bishop followed by a queen check. White calmly deflected and finally claimed the hanging rook. On move 16 black sacrificed another piece, this time a knight, in order to keep the attack on white’s king alive. After defending and throwing in a queen check of its own, white confidently checked the black king on move 22. This was especially dangerous because black, if given a free move, can checkmate in one! White found the force mating sequence, prevailed in an exhilarating checkmate, and proved that its lower training loss resulted in better chess." }, { "code": null, "e": 12558, "s": 12352, "text": "The most remarkable aspect of analyzing these games is how “human” the AI feels. Common openings, waiting for blunders, and attempting comebacks with wild sacrifices are standard fair in online human play." }, { "code": null, "e": 12744, "s": 12558, "text": "There is certainly room for improvement in our approach. A lot of well known techniques were not used in order to keep this project’s complexity manageable and focus on the AI portions:" }, { "code": null, "e": 12811, "s": 12744, "text": "Move ordering to prioritize searching “interesting” move sequences" }, { "code": null, "e": 12871, "s": 12811, "text": "Endgame Tablebase for precomputed winning endgame positions" }, { "code": null, "e": 12909, "s": 12871, "text": "Opening Book for precomputed openings" }, { "code": null, "e": 12966, "s": 12909, "text": "Only search a couple hundred thousand positions at 4 ply" }, { "code": null, "e": 12978, "s": 12966, "text": "Many others" }, { "code": null, "e": 13051, "s": 12978, "text": "There is also some flaws in our simplistic model and training procedures" }, { "code": null, "e": 13132, "s": 13051, "text": "Move counts are inputted into the model in bits instead of the number as a float" }, { "code": null, "e": 13207, "s": 13132, "text": "The model architecture was the first design attempted with no optimization" }, { "code": null, "e": 13280, "s": 13207, "text": "Learning rate and batch size schedulers could result in lower total loss" }, { "code": null, "e": 13423, "s": 13280, "text": "Chess positions are unique in the database and therefore later positions that are more likely to be unique are over represented in the dataset" }, { "code": null, "e": 13522, "s": 13423, "text": "Most games are played by amateurs and the search space of superior play might be under represented" }, { "code": null, "e": 13565, "s": 13522, "text": "The model could be trained for MUCH longer" } ]
How to successfully add large data sets to Google Drive | by Magdalena Konkiewicz | Towards Data Science
Introduction In this post, I will explain how to add large data sets to Google Drive so they can be accessed from Google Colab for processing and modeling. Whereas uploading a single file can be done with the drag and drop interface of Google Drive, it becomes more difficult with a large number of files. Dragging the whole folder containing 1GB of files just fails and freezes Google Drive. The alternative is to drag a zipped folder. This process is usually successful and does not take even that long (a couple of minutes with 1GB file) but the problem comes with unzipping the file in Google Drive itself which results in random files missing. My trials for three days to successfully upload photo data for CNN training in order to use free GPU led me to establish this alternative. I am going to describe here step by step how to upload successfully big data sets so they can be processed by Google Colab and take advantage of VMs provided by their services. Steps 1. Zip the folder with the files. In my case, I had a folder called ‘train’ with 70257 .jpg files that were taking around 1GB. 2. Upload the zipped file using Google Drive Interface. I have uploaded mine to an empty directory called data. 3. Open a new Google Colab file and mount it to Google Drive to be able to access the zip file. If you do not have Colab installed you can follow this article that explains how to do it. The command below will start the mounting process. from google.colab import drivedrive.mount('/content/gdrive') You will be asked to authorize access to Google Drive. Follow instructions to give authorization by copy-pasting the code and you should be mounted. 4. Now extract files to the local environment with the following command. !unzip gdrive/My\ Drive/data/train.zip Note that my train.zip file in ‘data’ folder is located in the Google Drive root directory. You will need to modify the path accordingly to where your file is located. You should see file unzipping. It takes less than 1 minute to unzip 1GB so you should not wait too long. Once you are comfortable that this command is working you can use the variation below that suppresses the output. !unzip gdrive/My\ Drive/data/train.zip > /dev/null Once the cell has executed you can see the files have appeared in the local train folder. You can find it on the left-hand side of the colab interface. 5. You can use the files for anything right now. Juts access them from the new ‘train’ folder. In my case, I can display the first image using the following code. import tensorflow as tfimg = tf.keras.preprocessing.image.load_img('train/abs_000.jpg')img You can now use your data for anything you wish. In my case, it was training a CNN using free GPU. Summary The process that I described above worked best for me! So please free to copy it. On the other hand, it would be much better to unzip the files in Google Drive, so they just stay there. This however was ‘mission impossible’ for me for thee days in a row. Every time I have unzipped the files and saved them in Google Drive there were missing photos in the end. I have tried to do it programmatically with Colab as well as using Zip Extractor connected to Google Drive. Both methods resulted in missing files with no warning about it. I have also tried two different Google accounts and the problem persisted. After losing 3 days of trial and error. I came with the process described above and it works smoothly for me every time I rerun the code. I hope it helps others that try to load large data sets to Google Drive in order to process them in Colab. If you are one that has found a better method or was able to unzip large files in Google Drive, I would be curious how this has been done. Happy coding! Originally published at aboutdatablog.com: How to successfully add large data sets to Google Drive and use them in Google Colab, on December 19, 2020. PS: I am writing articles that explain basic Data Science concepts in a simple and comprehensible manner on Medium and aboutdatablog.com. You can subscribe to my email list to get notified every time I write a new article. And if you are not a Medium member yet you can join here. Below there are some other posts you may enjoy:
[ { "code": null, "e": 185, "s": 172, "text": "Introduction" }, { "code": null, "e": 328, "s": 185, "text": "In this post, I will explain how to add large data sets to Google Drive so they can be accessed from Google Colab for processing and modeling." }, { "code": null, "e": 821, "s": 328, "text": "Whereas uploading a single file can be done with the drag and drop interface of Google Drive, it becomes more difficult with a large number of files. Dragging the whole folder containing 1GB of files just fails and freezes Google Drive. The alternative is to drag a zipped folder. This process is usually successful and does not take even that long (a couple of minutes with 1GB file) but the problem comes with unzipping the file in Google Drive itself which results in random files missing." }, { "code": null, "e": 1137, "s": 821, "text": "My trials for three days to successfully upload photo data for CNN training in order to use free GPU led me to establish this alternative. I am going to describe here step by step how to upload successfully big data sets so they can be processed by Google Colab and take advantage of VMs provided by their services." }, { "code": null, "e": 1143, "s": 1137, "text": "Steps" }, { "code": null, "e": 1270, "s": 1143, "text": "1. Zip the folder with the files. In my case, I had a folder called ‘train’ with 70257 .jpg files that were taking around 1GB." }, { "code": null, "e": 1382, "s": 1270, "text": "2. Upload the zipped file using Google Drive Interface. I have uploaded mine to an empty directory called data." }, { "code": null, "e": 1569, "s": 1382, "text": "3. Open a new Google Colab file and mount it to Google Drive to be able to access the zip file. If you do not have Colab installed you can follow this article that explains how to do it." }, { "code": null, "e": 1620, "s": 1569, "text": "The command below will start the mounting process." }, { "code": null, "e": 1681, "s": 1620, "text": "from google.colab import drivedrive.mount('/content/gdrive')" }, { "code": null, "e": 1736, "s": 1681, "text": "You will be asked to authorize access to Google Drive." }, { "code": null, "e": 1830, "s": 1736, "text": "Follow instructions to give authorization by copy-pasting the code and you should be mounted." }, { "code": null, "e": 1904, "s": 1830, "text": "4. Now extract files to the local environment with the following command." }, { "code": null, "e": 1943, "s": 1904, "text": "!unzip gdrive/My\\ Drive/data/train.zip" }, { "code": null, "e": 2111, "s": 1943, "text": "Note that my train.zip file in ‘data’ folder is located in the Google Drive root directory. You will need to modify the path accordingly to where your file is located." }, { "code": null, "e": 2142, "s": 2111, "text": "You should see file unzipping." }, { "code": null, "e": 2330, "s": 2142, "text": "It takes less than 1 minute to unzip 1GB so you should not wait too long. Once you are comfortable that this command is working you can use the variation below that suppresses the output." }, { "code": null, "e": 2381, "s": 2330, "text": "!unzip gdrive/My\\ Drive/data/train.zip > /dev/null" }, { "code": null, "e": 2533, "s": 2381, "text": "Once the cell has executed you can see the files have appeared in the local train folder. You can find it on the left-hand side of the colab interface." }, { "code": null, "e": 2696, "s": 2533, "text": "5. You can use the files for anything right now. Juts access them from the new ‘train’ folder. In my case, I can display the first image using the following code." }, { "code": null, "e": 2787, "s": 2696, "text": "import tensorflow as tfimg = tf.keras.preprocessing.image.load_img('train/abs_000.jpg')img" }, { "code": null, "e": 2886, "s": 2787, "text": "You can now use your data for anything you wish. In my case, it was training a CNN using free GPU." }, { "code": null, "e": 2894, "s": 2886, "text": "Summary" }, { "code": null, "e": 2976, "s": 2894, "text": "The process that I described above worked best for me! So please free to copy it." }, { "code": null, "e": 3255, "s": 2976, "text": "On the other hand, it would be much better to unzip the files in Google Drive, so they just stay there. This however was ‘mission impossible’ for me for thee days in a row. Every time I have unzipped the files and saved them in Google Drive there were missing photos in the end." }, { "code": null, "e": 3503, "s": 3255, "text": "I have tried to do it programmatically with Colab as well as using Zip Extractor connected to Google Drive. Both methods resulted in missing files with no warning about it. I have also tried two different Google accounts and the problem persisted." }, { "code": null, "e": 3641, "s": 3503, "text": "After losing 3 days of trial and error. I came with the process described above and it works smoothly for me every time I rerun the code." }, { "code": null, "e": 3887, "s": 3641, "text": "I hope it helps others that try to load large data sets to Google Drive in order to process them in Colab. If you are one that has found a better method or was able to unzip large files in Google Drive, I would be curious how this has been done." }, { "code": null, "e": 3901, "s": 3887, "text": "Happy coding!" }, { "code": null, "e": 4052, "s": 3901, "text": "Originally published at aboutdatablog.com: How to successfully add large data sets to Google Drive and use them in Google Colab, on December 19, 2020." }, { "code": null, "e": 4333, "s": 4052, "text": "PS: I am writing articles that explain basic Data Science concepts in a simple and comprehensible manner on Medium and aboutdatablog.com. You can subscribe to my email list to get notified every time I write a new article. And if you are not a Medium member yet you can join here." } ]
Correlating Branch Prediction - GeeksforGeeks
04 Jun, 2020 Conditional Branches present in the programs significantly affect the performance of the system. So we need to come up with efficient branch prediction mechanism so as to get the branch target address with high accuracy and thus minimizing the stalls associated with control hazards. In case if failure in correctly predicting target address, penalty will occur in terms of flushing the pipeline and bringing back the processors to a state that was there earlier when it was executing branch instruction. Types of Branch Prediction Technique –Branch prediction technique can be of two types: Static Branch Prediction TechniqueDynamic Branch Prediction Technique Static Branch Prediction Technique Dynamic Branch Prediction Technique These are explained as following below. 1. Static Branch Prediction Technique :In case of Static branch prediction technique underlying hardware assumes that either the branch is not taken always or the branch is taken always.Let us understand branch prediction with an example code: //Code int a=0; while(a<5) { //branch instruction, condition either true or false if(a%2==0) {.....} a++; } Output –Let us assume that underlying hardware has assumed that branch is not taken always. The output predicted by underlying hardware and actual output is shown in fig: 2. Dynamic Branch Prediction Technique :In Dynamic branch prediction technique prediction by underlying hardware is not fixed, rather it changes dynamically.This technique has high accuracy than static technique. Some dynamic branch prediction techniques are: 1-bit branch prediction technique2-bit branch prediction techniqueCorrelating branch prediction technique 1-bit branch prediction technique 2-bit branch prediction technique Correlating branch prediction technique These are explained as following below. 1-bit Branch Prediction Technique –In this technique hardware changes its assumption just after one false assumption.For example if hardware assumes branch to be taken but actually branch is not taken, then in next step hardware assumes branch to be not taken and vice-versa.1-bit branch prediction machine is shown in the fig below:Explanation –At the beginning, lets say hardware assume branch to be take and so at a=0, branch is taken. At a=1, hardware assumes branch to be taken but branch is not taken.So now at a=2 hardware assumes branch not to be taken but branch is taken. At a=3 hardware assumes branch to be taken but branch is not taken. At a=4 hardware assumes branch not to be taken but branch is taken.The output predicted by underlying hardware and actual output is shown in fig: 1-bit branch prediction machine is shown in the fig below: Explanation –At the beginning, lets say hardware assume branch to be take and so at a=0, branch is taken. At a=1, hardware assumes branch to be taken but branch is not taken.So now at a=2 hardware assumes branch not to be taken but branch is taken. At a=3 hardware assumes branch to be taken but branch is not taken. At a=4 hardware assumes branch not to be taken but branch is taken. The output predicted by underlying hardware and actual output is shown in fig: 2-bit Branch Predictor –In this technique the underlying hardware does not changes itss assumption just after one incorrect assumption, rather it changes its assumption after two consecutive wrong assumption and vice-versa.2-bit branch prediction machine is shown in the figure:Explanation –Lets say when a=0 everything is reset(00) and so hardware assume branch not to be taken and branch is taken. So current state is (01)When a=1, hardware assumes branch not to be taken and branch is not taken. So current state is (00)When a=2, hardware assumes branch not to be taken and branch is taken.So current State is (01)When a=3, hardware assumes branch not to be taken and branch is not taken. So current State is (10)When a=4, hardware assumes branch not to be taken and branch is taken.So current State is(00)The output predicted by underlying hardware and actual output is shown in fig: 2-bit branch prediction machine is shown in the figure: Explanation – Lets say when a=0 everything is reset(00) and so hardware assume branch not to be taken and branch is taken. So current state is (01)When a=1, hardware assumes branch not to be taken and branch is not taken. So current state is (00)When a=2, hardware assumes branch not to be taken and branch is taken.So current State is (01)When a=3, hardware assumes branch not to be taken and branch is not taken. So current State is (10)When a=4, hardware assumes branch not to be taken and branch is taken.So current State is(00) Lets say when a=0 everything is reset(00) and so hardware assume branch not to be taken and branch is taken. So current state is (01) When a=1, hardware assumes branch not to be taken and branch is not taken. So current state is (00) When a=2, hardware assumes branch not to be taken and branch is taken.So current State is (01) When a=3, hardware assumes branch not to be taken and branch is not taken. So current State is (10) When a=4, hardware assumes branch not to be taken and branch is taken.So current State is(00) The output predicted by underlying hardware and actual output is shown in fig: Correlating Branch Prediction –We cannot get significant accuracy from 2-bit branch predictor also due to interference with other branches.So correlating branch prediction comes into picture which is also known as two-level branch predictor in which prediction accuracy is improved as it takes into consideration the recent behavior of other branches also.Information Source –It uses k least significant bits of Branch Target Address which is fetched before.It also uses Local History Table(LHH) which is table of shift registers where shift register refers to the last outcome of m branches having same k least significant bits.It also uses Local Prediction Table to predict the outcome depending on the state in which it is present.Example –Lets illustrate and understand this prediction technique with the same example.Explanation Step By Step –1. Least k(here k=3) significant bit is 100 i.e, 4 so this point to location 4 in Local History Table. At location 4, it contains 000 i.e, 0, so it points to location 0 in Local Prediction Table. It contains state 00 i.e branch not taken, but actually branch (0%2) is taken. So now both table gets updated.Complete Process is shown in figure:2. At location 4, now it contains 100 in local history table, so it points to location 4 in Local Prediction Table. It contains state 00 i.e branch not taken, and actually branch is not taken. So accordingly table gets updated.Complete Process is shown in figure:3. t location 4 now it contains 010 in local history table, so it points to location 2 in Local Prediction Table. It contains state 00 i.e, branch not taken, and actually branch is taken. So accordingly table gets updated.Complete Process is shown in figure:4. At location 4, now it contains 101 in Local history table, so it points to location 5 in Local prediction table. It contains state 00 i.e, branch not taken, and actually branch is not taken. So accordingly table gets updatedComplete Process is shown in figure:5. At location 4 now it contains 010 in Local history table, so it points to location 2 in Local Prediction table. It contains state 01 i.e, branch not taken, and actually branch is taken. So accordingly table gets updatedComplete Process is shown in figure:The output predicted by underlying hardware and actual output is shown in fig:So if there are more than one branches and process continues like this Correlating Branch Predictions gives highest accuracy above all technique. Information Source – It uses k least significant bits of Branch Target Address which is fetched before. It also uses Local History Table(LHH) which is table of shift registers where shift register refers to the last outcome of m branches having same k least significant bits. It also uses Local Prediction Table to predict the outcome depending on the state in which it is present. Example –Lets illustrate and understand this prediction technique with the same example. Explanation Step By Step –1. Least k(here k=3) significant bit is 100 i.e, 4 so this point to location 4 in Local History Table. At location 4, it contains 000 i.e, 0, so it points to location 0 in Local Prediction Table. It contains state 00 i.e branch not taken, but actually branch (0%2) is taken. So now both table gets updated.Complete Process is shown in figure: 2. At location 4, now it contains 100 in local history table, so it points to location 4 in Local Prediction Table. It contains state 00 i.e branch not taken, and actually branch is not taken. So accordingly table gets updated.Complete Process is shown in figure: 3. t location 4 now it contains 010 in local history table, so it points to location 2 in Local Prediction Table. It contains state 00 i.e, branch not taken, and actually branch is taken. So accordingly table gets updated.Complete Process is shown in figure: 4. At location 4, now it contains 101 in Local history table, so it points to location 5 in Local prediction table. It contains state 00 i.e, branch not taken, and actually branch is not taken. So accordingly table gets updatedComplete Process is shown in figure: 5. At location 4 now it contains 010 in Local history table, so it points to location 2 in Local Prediction table. It contains state 01 i.e, branch not taken, and actually branch is taken. So accordingly table gets updatedComplete Process is shown in figure: The output predicted by underlying hardware and actual output is shown in fig: So if there are more than one branches and process continues like this Correlating Branch Predictions gives highest accuracy above all technique. Computer Organization & Architecture Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Architecture of 8085 microprocessor Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard) Direct Access Media (DMA) Controller in Computer Architecture Pin diagram of 8086 microprocessor General purpose registers in 8086 microprocessor 8085 program to add two 16 bit numbers I2C Communication Protocol Difference between SRAM and DRAM Difference between RISC and CISC processor | Set 2 Computer Organization | Different Instruction Cycles
[ { "code": null, "e": 24389, "s": 24361, "text": "\n04 Jun, 2020" }, { "code": null, "e": 24673, "s": 24389, "text": "Conditional Branches present in the programs significantly affect the performance of the system. So we need to come up with efficient branch prediction mechanism so as to get the branch target address with high accuracy and thus minimizing the stalls associated with control hazards." }, { "code": null, "e": 24894, "s": 24673, "text": "In case if failure in correctly predicting target address, penalty will occur in terms of flushing the pipeline and bringing back the processors to a state that was there earlier when it was executing branch instruction." }, { "code": null, "e": 24981, "s": 24894, "text": "Types of Branch Prediction Technique –Branch prediction technique can be of two types:" }, { "code": null, "e": 25051, "s": 24981, "text": "Static Branch Prediction TechniqueDynamic Branch Prediction Technique" }, { "code": null, "e": 25086, "s": 25051, "text": "Static Branch Prediction Technique" }, { "code": null, "e": 25122, "s": 25086, "text": "Dynamic Branch Prediction Technique" }, { "code": null, "e": 25162, "s": 25122, "text": "These are explained as following below." }, { "code": null, "e": 25406, "s": 25162, "text": "1. Static Branch Prediction Technique :In case of Static branch prediction technique underlying hardware assumes that either the branch is not taken always or the branch is taken always.Let us understand branch prediction with an example code:" }, { "code": null, "e": 25537, "s": 25406, "text": "//Code\nint a=0;\nwhile(a<5)\n {\n //branch instruction, condition either true or false\n if(a%2==0) \n {.....}\n a++;\n }" }, { "code": null, "e": 25708, "s": 25537, "text": "Output –Let us assume that underlying hardware has assumed that branch is not taken always. The output predicted by underlying hardware and actual output is shown in fig:" }, { "code": null, "e": 25921, "s": 25708, "text": "2. Dynamic Branch Prediction Technique :In Dynamic branch prediction technique prediction by underlying hardware is not fixed, rather it changes dynamically.This technique has high accuracy than static technique." }, { "code": null, "e": 25968, "s": 25921, "text": "Some dynamic branch prediction techniques are:" }, { "code": null, "e": 26074, "s": 25968, "text": "1-bit branch prediction technique2-bit branch prediction techniqueCorrelating branch prediction technique" }, { "code": null, "e": 26108, "s": 26074, "text": "1-bit branch prediction technique" }, { "code": null, "e": 26142, "s": 26108, "text": "2-bit branch prediction technique" }, { "code": null, "e": 26182, "s": 26142, "text": "Correlating branch prediction technique" }, { "code": null, "e": 26222, "s": 26182, "text": "These are explained as following below." }, { "code": null, "e": 27018, "s": 26222, "text": "1-bit Branch Prediction Technique –In this technique hardware changes its assumption just after one false assumption.For example if hardware assumes branch to be taken but actually branch is not taken, then in next step hardware assumes branch to be not taken and vice-versa.1-bit branch prediction machine is shown in the fig below:Explanation –At the beginning, lets say hardware assume branch to be take and so at a=0, branch is taken. At a=1, hardware assumes branch to be taken but branch is not taken.So now at a=2 hardware assumes branch not to be taken but branch is taken. At a=3 hardware assumes branch to be taken but branch is not taken. At a=4 hardware assumes branch not to be taken but branch is taken.The output predicted by underlying hardware and actual output is shown in fig:" }, { "code": null, "e": 27077, "s": 27018, "text": "1-bit branch prediction machine is shown in the fig below:" }, { "code": null, "e": 27462, "s": 27077, "text": "Explanation –At the beginning, lets say hardware assume branch to be take and so at a=0, branch is taken. At a=1, hardware assumes branch to be taken but branch is not taken.So now at a=2 hardware assumes branch not to be taken but branch is taken. At a=3 hardware assumes branch to be taken but branch is not taken. At a=4 hardware assumes branch not to be taken but branch is taken." }, { "code": null, "e": 27541, "s": 27462, "text": "The output predicted by underlying hardware and actual output is shown in fig:" }, { "code": null, "e": 28429, "s": 27541, "text": "2-bit Branch Predictor –In this technique the underlying hardware does not changes itss assumption just after one incorrect assumption, rather it changes its assumption after two consecutive wrong assumption and vice-versa.2-bit branch prediction machine is shown in the figure:Explanation –Lets say when a=0 everything is reset(00) and so hardware assume branch not to be taken and branch is taken. So current state is (01)When a=1, hardware assumes branch not to be taken and branch is not taken. So current state is (00)When a=2, hardware assumes branch not to be taken and branch is taken.So current State is (01)When a=3, hardware assumes branch not to be taken and branch is not taken. So current State is (10)When a=4, hardware assumes branch not to be taken and branch is taken.So current State is(00)The output predicted by underlying hardware and actual output is shown in fig:" }, { "code": null, "e": 28485, "s": 28429, "text": "2-bit branch prediction machine is shown in the figure:" }, { "code": null, "e": 28499, "s": 28485, "text": "Explanation –" }, { "code": null, "e": 29018, "s": 28499, "text": "Lets say when a=0 everything is reset(00) and so hardware assume branch not to be taken and branch is taken. So current state is (01)When a=1, hardware assumes branch not to be taken and branch is not taken. So current state is (00)When a=2, hardware assumes branch not to be taken and branch is taken.So current State is (01)When a=3, hardware assumes branch not to be taken and branch is not taken. So current State is (10)When a=4, hardware assumes branch not to be taken and branch is taken.So current State is(00)" }, { "code": null, "e": 29152, "s": 29018, "text": "Lets say when a=0 everything is reset(00) and so hardware assume branch not to be taken and branch is taken. So current state is (01)" }, { "code": null, "e": 29252, "s": 29152, "text": "When a=1, hardware assumes branch not to be taken and branch is not taken. So current state is (00)" }, { "code": null, "e": 29347, "s": 29252, "text": "When a=2, hardware assumes branch not to be taken and branch is taken.So current State is (01)" }, { "code": null, "e": 29447, "s": 29347, "text": "When a=3, hardware assumes branch not to be taken and branch is not taken. So current State is (10)" }, { "code": null, "e": 29541, "s": 29447, "text": "When a=4, hardware assumes branch not to be taken and branch is taken.So current State is(00)" }, { "code": null, "e": 29620, "s": 29541, "text": "The output predicted by underlying hardware and actual output is shown in fig:" }, { "code": null, "e": 32076, "s": 29620, "text": "Correlating Branch Prediction –We cannot get significant accuracy from 2-bit branch predictor also due to interference with other branches.So correlating branch prediction comes into picture which is also known as two-level branch predictor in which prediction accuracy is improved as it takes into consideration the recent behavior of other branches also.Information Source –It uses k least significant bits of Branch Target Address which is fetched before.It also uses Local History Table(LHH) which is table of shift registers where shift register refers to the last outcome of m branches having same k least significant bits.It also uses Local Prediction Table to predict the outcome depending on the state in which it is present.Example –Lets illustrate and understand this prediction technique with the same example.Explanation Step By Step –1. Least k(here k=3) significant bit is 100 i.e, 4 so this point to location 4 in Local History Table. At location 4, it contains 000 i.e, 0, so it points to location 0 in Local Prediction Table. It contains state 00 i.e branch not taken, but actually branch (0%2) is taken. So now both table gets updated.Complete Process is shown in figure:2. At location 4, now it contains 100 in local history table, so it points to location 4 in Local Prediction Table. It contains state 00 i.e branch not taken, and actually branch is not taken. So accordingly table gets updated.Complete Process is shown in figure:3. t location 4 now it contains 010 in local history table, so it points to location 2 in Local Prediction Table. It contains state 00 i.e, branch not taken, and actually branch is taken. So accordingly table gets updated.Complete Process is shown in figure:4. At location 4, now it contains 101 in Local history table, so it points to location 5 in Local prediction table. It contains state 00 i.e, branch not taken, and actually branch is not taken. So accordingly table gets updatedComplete Process is shown in figure:5. At location 4 now it contains 010 in Local history table, so it points to location 2 in Local Prediction table. It contains state 01 i.e, branch not taken, and actually branch is taken. So accordingly table gets updatedComplete Process is shown in figure:The output predicted by underlying hardware and actual output is shown in fig:So if there are more than one branches and process continues like this Correlating Branch Predictions gives highest accuracy above all technique." }, { "code": null, "e": 32097, "s": 32076, "text": "Information Source –" }, { "code": null, "e": 32180, "s": 32097, "text": "It uses k least significant bits of Branch Target Address which is fetched before." }, { "code": null, "e": 32352, "s": 32180, "text": "It also uses Local History Table(LHH) which is table of shift registers where shift register refers to the last outcome of m branches having same k least significant bits." }, { "code": null, "e": 32458, "s": 32352, "text": "It also uses Local Prediction Table to predict the outcome depending on the state in which it is present." }, { "code": null, "e": 32547, "s": 32458, "text": "Example –Lets illustrate and understand this prediction technique with the same example." }, { "code": null, "e": 32916, "s": 32547, "text": "Explanation Step By Step –1. Least k(here k=3) significant bit is 100 i.e, 4 so this point to location 4 in Local History Table. At location 4, it contains 000 i.e, 0, so it points to location 0 in Local Prediction Table. It contains state 00 i.e branch not taken, but actually branch (0%2) is taken. So now both table gets updated.Complete Process is shown in figure:" }, { "code": null, "e": 33180, "s": 32916, "text": "2. At location 4, now it contains 100 in local history table, so it points to location 4 in Local Prediction Table. It contains state 00 i.e branch not taken, and actually branch is not taken. So accordingly table gets updated.Complete Process is shown in figure:" }, { "code": null, "e": 33439, "s": 33180, "text": "3. t location 4 now it contains 010 in local history table, so it points to location 2 in Local Prediction Table. It contains state 00 i.e, branch not taken, and actually branch is taken. So accordingly table gets updated.Complete Process is shown in figure:" }, { "code": null, "e": 33703, "s": 33439, "text": "4. At location 4, now it contains 101 in Local history table, so it points to location 5 in Local prediction table. It contains state 00 i.e, branch not taken, and actually branch is not taken. So accordingly table gets updatedComplete Process is shown in figure:" }, { "code": null, "e": 33962, "s": 33703, "text": "5. At location 4 now it contains 010 in Local history table, so it points to location 2 in Local Prediction table. It contains state 01 i.e, branch not taken, and actually branch is taken. So accordingly table gets updatedComplete Process is shown in figure:" }, { "code": null, "e": 34041, "s": 33962, "text": "The output predicted by underlying hardware and actual output is shown in fig:" }, { "code": null, "e": 34187, "s": 34041, "text": "So if there are more than one branches and process continues like this Correlating Branch Predictions gives highest accuracy above all technique." }, { "code": null, "e": 34224, "s": 34187, "text": "Computer Organization & Architecture" }, { "code": null, "e": 34322, "s": 34224, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34331, "s": 34322, "text": "Comments" }, { "code": null, "e": 34344, "s": 34331, "text": "Old Comments" }, { "code": null, "e": 34380, "s": 34344, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 34471, "s": 34380, "text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)" }, { "code": null, "e": 34533, "s": 34471, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 34568, "s": 34533, "text": "Pin diagram of 8086 microprocessor" }, { "code": null, "e": 34617, "s": 34568, "text": "General purpose registers in 8086 microprocessor" }, { "code": null, "e": 34656, "s": 34617, "text": "8085 program to add two 16 bit numbers" }, { "code": null, "e": 34683, "s": 34656, "text": "I2C Communication Protocol" }, { "code": null, "e": 34716, "s": 34683, "text": "Difference between SRAM and DRAM" }, { "code": null, "e": 34767, "s": 34716, "text": "Difference between RISC and CISC processor | Set 2" } ]
PHP | Merging two or more arrays using array_merge()
18 Apr, 2019 The array_merge() is a builtin function in PHP and is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array. The merging occurs in such a manner that the values of one array are appended at the end of the previous array. The function takes the list of arrays separated by commas as a parameter that are needed to be merged and returns a new array with merged values of arrays passed in parameter. Syntax: array array_merge($array1, $array2, ......, $arrayn) Parameters: The array_merge() function takes a list of arrays separated by commas as a parameter that are needed to be merged as shown in the syntax. There are n arrays (($array1, $array2, ......, $arrayn) separated by (‘,’) in the syntax. We can pass any number of arrays in parameter. Return Value: It returns a new array in which the elements of all arrays passed in parameters are merged such that the values of one array are appended at the end of the previous array. Below programs illustrates the working of array_merge() function in PHP: Merging Two Simple Arrays: When two more arrays are passed to the array_merge() function then the values of one array are appended at the end of the previous array. If two elements have the same string keys then the latter value will be overridden. The integer keys will be renumbered starting from zero. To merge two arrays, the array_merge() function can be executed in the following way:<?php $my_array1 = array("size" => "big", 2,3 );$my_array2 = array("a", "b", "size" => "medium", "shape" => "circle", 4);$res = array_merge($my_array1, $my_array2); print_r($res); ?>Output:Array ( [size] => medium [0] => 2 [1] => 3 [2] => a [3] => b [shape] => circle [4] => 4 ) Note: If the input arrays contain the same string keys, then the later value for that key will overwrite the previous one. <?php $my_array1 = array("size" => "big", 2,3 );$my_array2 = array("a", "b", "size" => "medium", "shape" => "circle", 4);$res = array_merge($my_array1, $my_array2); print_r($res); ?> Output: Array ( [size] => medium [0] => 2 [1] => 3 [2] => a [3] => b [shape] => circle [4] => 4 ) Note: If the input arrays contain the same string keys, then the later value for that key will overwrite the previous one. Passing parameter with integer keys: If parameters are passed to the array_merge() function and the keys of this array parameter are an integer then the keys in the output array will be renumbered starting from 0 and incrementing for next elements by 1.Below programs illustrates this:<?php $my_array = array(1 => "Geeks", 3=>"for", 2=>"Geeks"); $res = array_merge($my_array);print_r($res); ?>Output:Array ( [0] => Geeks [1] => for [2] => Geeks )<?php $my_array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');$my_array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');$res = array_merge($my_array1,$my_array2);print_r($res); ?>Output:Array ( [0] => zero_a [1] => two_a [2] => three_a [3] => one_b [4] => three_b [5] => four_b ) Below programs illustrates this: <?php $my_array = array(1 => "Geeks", 3=>"for", 2=>"Geeks"); $res = array_merge($my_array);print_r($res); ?> Output: Array ( [0] => Geeks [1] => for [2] => Geeks ) <?php $my_array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');$my_array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');$res = array_merge($my_array1,$my_array2);print_r($res); ?> Output: Array ( [0] => zero_a [1] => two_a [2] => three_a [3] => one_b [4] => three_b [5] => four_b ) Akanksha_Rai PHP-array PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? PHP in_array() Function How to delete an array element based on key in PHP? How to convert array to string in PHP ? 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": 52, "s": 24, "text": "\n18 Apr, 2019" }, { "code": null, "e": 554, "s": 52, "text": "The array_merge() is a builtin function in PHP and is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array. The merging occurs in such a manner that the values of one array are appended at the end of the previous array. The function takes the list of arrays separated by commas as a parameter that are needed to be merged and returns a new array with merged values of arrays passed in parameter." }, { "code": null, "e": 562, "s": 554, "text": "Syntax:" }, { "code": null, "e": 615, "s": 562, "text": "array array_merge($array1, $array2, ......, $arrayn)" }, { "code": null, "e": 902, "s": 615, "text": "Parameters: The array_merge() function takes a list of arrays separated by commas as a parameter that are needed to be merged as shown in the syntax. There are n arrays (($array1, $array2, ......, $arrayn) separated by (‘,’) in the syntax. We can pass any number of arrays in parameter." }, { "code": null, "e": 1088, "s": 902, "text": "Return Value: It returns a new array in which the elements of all arrays passed in parameters are merged such that the values of one array are appended at the end of the previous array." }, { "code": null, "e": 1161, "s": 1088, "text": "Below programs illustrates the working of array_merge() function in PHP:" }, { "code": null, "e": 2007, "s": 1161, "text": "Merging Two Simple Arrays: When two more arrays are passed to the array_merge() function then the values of one array are appended at the end of the previous array. If two elements have the same string keys then the latter value will be overridden. The integer keys will be renumbered starting from zero. To merge two arrays, the array_merge() function can be executed in the following way:<?php $my_array1 = array(\"size\" => \"big\", 2,3 );$my_array2 = array(\"a\", \"b\", \"size\" => \"medium\", \"shape\" => \"circle\", 4);$res = array_merge($my_array1, $my_array2); print_r($res); ?>Output:Array\n(\n [size] => medium\n [0] => 2\n [1] => 3\n [2] => a\n [3] => b\n [shape] => circle\n [4] => 4\n)\nNote: If the input arrays contain the same string keys, then the later value for that key will overwrite the previous one." }, { "code": "<?php $my_array1 = array(\"size\" => \"big\", 2,3 );$my_array2 = array(\"a\", \"b\", \"size\" => \"medium\", \"shape\" => \"circle\", 4);$res = array_merge($my_array1, $my_array2); print_r($res); ?>", "e": 2216, "s": 2007, "text": null }, { "code": null, "e": 2224, "s": 2216, "text": "Output:" }, { "code": null, "e": 2343, "s": 2224, "text": "Array\n(\n [size] => medium\n [0] => 2\n [1] => 3\n [2] => a\n [3] => b\n [shape] => circle\n [4] => 4\n)\n" }, { "code": null, "e": 2466, "s": 2343, "text": "Note: If the input arrays contain the same string keys, then the later value for that key will overwrite the previous one." }, { "code": null, "e": 3253, "s": 2466, "text": "Passing parameter with integer keys: If parameters are passed to the array_merge() function and the keys of this array parameter are an integer then the keys in the output array will be renumbered starting from 0 and incrementing for next elements by 1.Below programs illustrates this:<?php $my_array = array(1 => \"Geeks\", 3=>\"for\", 2=>\"Geeks\"); $res = array_merge($my_array);print_r($res); ?>Output:Array\n(\n [0] => Geeks\n [1] => for\n [2] => Geeks \n)<?php $my_array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');$my_array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');$res = array_merge($my_array1,$my_array2);print_r($res); ?>Output:Array\n(\n [0] => zero_a\n [1] => two_a\n [2] => three_a\n [3] => one_b\n [4] => three_b\n [5] => four_b\n)\n" }, { "code": null, "e": 3286, "s": 3253, "text": "Below programs illustrates this:" }, { "code": "<?php $my_array = array(1 => \"Geeks\", 3=>\"for\", 2=>\"Geeks\"); $res = array_merge($my_array);print_r($res); ?>", "e": 3398, "s": 3286, "text": null }, { "code": null, "e": 3406, "s": 3398, "text": "Output:" }, { "code": null, "e": 3470, "s": 3406, "text": "Array\n(\n [0] => Geeks\n [1] => for\n [2] => Geeks \n)" }, { "code": "<?php $my_array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');$my_array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');$res = array_merge($my_array1,$my_array2);print_r($res); ?>", "e": 3666, "s": 3470, "text": null }, { "code": null, "e": 3674, "s": 3666, "text": "Output:" }, { "code": null, "e": 3793, "s": 3674, "text": "Array\n(\n [0] => zero_a\n [1] => two_a\n [2] => three_a\n [3] => one_b\n [4] => three_b\n [5] => four_b\n)\n" }, { "code": null, "e": 3806, "s": 3793, "text": "Akanksha_Rai" }, { "code": null, "e": 3816, "s": 3806, "text": "PHP-array" }, { "code": null, "e": 3829, "s": 3816, "text": "PHP-function" }, { "code": null, "e": 3833, "s": 3829, "text": "PHP" }, { "code": null, "e": 3850, "s": 3833, "text": "Web Technologies" }, { "code": null, "e": 3854, "s": 3850, "text": "PHP" }, { "code": null, "e": 3952, "s": 3854, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3997, "s": 3952, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 4047, "s": 3997, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 4071, "s": 4047, "text": "PHP in_array() Function" }, { "code": null, "e": 4123, "s": 4071, "text": "How to delete an array element based on key in PHP?" }, { "code": null, "e": 4163, "s": 4123, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 4225, "s": 4163, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4258, "s": 4225, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4319, "s": 4258, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4369, "s": 4319, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to tag a commit in git?
The git commit is a 40-digit hexadecimal SHA1 hash. Quite often we need to bookmark a as the commit hash is difficult to memorize. This is where one can use tags. Tags can be used to name a commit. In other words, tags are labels that can be used to identify a specific commit. For e.g., “v1.0, RC1.0” are some ways to name a commit. Tags can be classified as − Lightweight Tags Lightweight Tags Annotated Tags Annotated Tags A Lightweight tag is also known as a simple tag. These tags use a name to refer to a specific commit. Lightweight tags are private to a repository. These are just pointers to a specific commit. In other words, they only store the hash of the commit they refer to and do not store any information. A lightweight tag is not stored as a separate object in Git. A tag can be created using the git tag command. The syntax for using this command is − $ git tag <tag_name> <commit_hash> The following example creates a tag “RC1.0” and associates it with a commit having the hash “c81c9ab” $ git tag RC1.0 c81c9ab Let us verify this by executing the following commands − $ git tag // lists all tags $ git log −−oneline // lists all commits, one commit per line The following output indicates that a tag by the name “RC1.0” exists in the repository and it points to the commit “c81c9ab”. 089ddf4 (HEAD −> master) new line c81c9ab (tag: RC1.0) This is a short description 8a3d6ed first commit When we create a lightweight tag, a file with the name of the tag will be created inside the “.git/refs/tags folder”. This can be verified by executing the following commands − $ ls .git/refs/tags The output will be − RC1.0 $ cat .git/refs/tags/RC1.0 The output shows that a tag “RC1.0” is created and that it points to a specific commit. c81c9abe7c4c8273a11ab7d20a3aac0be54bf00c An annotated tag stores extra metadata such as author name, release notes, tag-message and date. Unlike lightweight tags, annotated tags are stored as a separate object in Git. These tags allow you to store information that is related to this specific tag. An annotated tag has a tagging message just like a commit has a commit message. The syntax to create an annotated tag is − $ git tag −a <tag_name> −m <tag_message> The −a specifies that the tag being created is an annotated tag. The −m flag denotes a tag message which is similar to commit message. The following example creates an annotated tag v1.1 and adds a message to it. $ git tag −a v1.1 −m 'my version 1.1' Many Git commands work only on annotated tags, because they are considered permanent objects. Annotated tags are stored as tag−type objects, that point to a commit. We can verify this by executing the following commands − $ ls .git/refs/tags The following output shows that “.git/refs/tags folder” has our “v1.1” tag file. RC1.0 v1.1 When we display contents using the cat command it shows a hash value. $ cat .git/refs/tags/v1.1 //view content of the tag file The output is fa2c7b87859db191440e97ec87e47b212c44945d Let’s verify the type of this hash using the following commands. $ git cat−file −t fa2c // shows type of the object represented by this hash $ git cat−file −p fa2c // prints the contents of the SHA1 hash The output of the above commands will be − // output of git cat−file −t fa2c tag // output of git cat−file −p fa2c object 089ddf457ded2496a5ad5ac4384a93a109b9b7e2 type commit tag v1.1 tagger Kiran <kiran.p@gmail.com>1612112082 The output shows the “fa2c” object which is contained in the “v1.1” tag file is a tag object. When we display details of the “fa2c” blob object using the cat−file −p command it points to commit “089dd” which is the last commit. We can also see the tagger name and tag message details.
[ { "code": null, "e": 1521, "s": 1187, "text": "The git commit is a 40-digit hexadecimal SHA1 hash. Quite often we need to bookmark a as the commit hash is difficult to memorize. This is where one can use tags. Tags can be used to name a commit. In other words, tags are labels that can be used to identify a specific commit. For e.g., “v1.0, RC1.0” are some ways to name a commit." }, { "code": null, "e": 1549, "s": 1521, "text": "Tags can be classified as −" }, { "code": null, "e": 1566, "s": 1549, "text": "Lightweight Tags" }, { "code": null, "e": 1583, "s": 1566, "text": "Lightweight Tags" }, { "code": null, "e": 1598, "s": 1583, "text": "Annotated Tags" }, { "code": null, "e": 1613, "s": 1598, "text": "Annotated Tags" }, { "code": null, "e": 1971, "s": 1613, "text": "A Lightweight tag is also known as a simple tag. These tags use a name to refer to a specific commit. Lightweight tags are private to a repository. These are just pointers to a specific commit. In other words, they only store the hash of the commit they refer to and do not store any information. A lightweight tag is not stored as a separate object in Git." }, { "code": null, "e": 2058, "s": 1971, "text": "A tag can be created using the git tag command. The syntax for using this command is −" }, { "code": null, "e": 2093, "s": 2058, "text": "$ git tag <tag_name> <commit_hash>" }, { "code": null, "e": 2195, "s": 2093, "text": "The following example creates a tag “RC1.0” and associates it with a commit having the hash “c81c9ab”" }, { "code": null, "e": 2219, "s": 2195, "text": "$ git tag RC1.0 c81c9ab" }, { "code": null, "e": 2276, "s": 2219, "text": "Let us verify this by executing the following commands −" }, { "code": null, "e": 2380, "s": 2276, "text": "$ git tag // lists all tags\n$ git log −−oneline // lists all commits, one commit per line" }, { "code": null, "e": 2506, "s": 2380, "text": "The following output indicates that a tag by the name “RC1.0” exists in the repository and it points to the commit “c81c9ab”." }, { "code": null, "e": 2610, "s": 2506, "text": "089ddf4 (HEAD −> master) new line\nc81c9ab (tag: RC1.0) This is a short description\n8a3d6ed first commit" }, { "code": null, "e": 2787, "s": 2610, "text": "When we create a lightweight tag, a file with the name of the tag will be created inside the “.git/refs/tags folder”. This can be verified by executing the following commands −" }, { "code": null, "e": 2807, "s": 2787, "text": "$ ls .git/refs/tags" }, { "code": null, "e": 2828, "s": 2807, "text": "The output will be −" }, { "code": null, "e": 2861, "s": 2828, "text": "RC1.0\n$ cat .git/refs/tags/RC1.0" }, { "code": null, "e": 2949, "s": 2861, "text": "The output shows that a tag “RC1.0” is created and that it points to a specific commit." }, { "code": null, "e": 2990, "s": 2949, "text": "c81c9abe7c4c8273a11ab7d20a3aac0be54bf00c" }, { "code": null, "e": 3370, "s": 2990, "text": "An annotated tag stores extra metadata such as author name, release notes, tag-message and date. Unlike lightweight tags, annotated tags are stored as a separate object in Git. These tags allow you to store information that is related to this specific tag. An annotated tag has a tagging message just like a commit has a commit message. The syntax to create an annotated tag is −" }, { "code": null, "e": 3411, "s": 3370, "text": "$ git tag −a <tag_name> −m <tag_message>" }, { "code": null, "e": 3546, "s": 3411, "text": "The −a specifies that the tag being created is an annotated tag. The −m flag denotes a tag message which is similar to commit message." }, { "code": null, "e": 3624, "s": 3546, "text": "The following example creates an annotated tag v1.1 and adds a message to it." }, { "code": null, "e": 3663, "s": 3624, "text": "$ git tag −a v1.1 −m 'my version 1.1'\n" }, { "code": null, "e": 3885, "s": 3663, "text": "Many Git commands work only on annotated tags, because they are considered permanent objects. Annotated tags are stored as tag−type objects, that point to a commit. We can verify this by executing the following commands −" }, { "code": null, "e": 3905, "s": 3885, "text": "$ ls .git/refs/tags" }, { "code": null, "e": 3986, "s": 3905, "text": "The following output shows that “.git/refs/tags folder” has our “v1.1” tag file." }, { "code": null, "e": 3997, "s": 3986, "text": "RC1.0 v1.1" }, { "code": null, "e": 4067, "s": 3997, "text": "When we display contents using the cat command it shows a hash value." }, { "code": null, "e": 4124, "s": 4067, "text": "$ cat .git/refs/tags/v1.1 //view content of the tag file" }, { "code": null, "e": 4138, "s": 4124, "text": "The output is" }, { "code": null, "e": 4180, "s": 4138, "text": "fa2c7b87859db191440e97ec87e47b212c44945d\n" }, { "code": null, "e": 4245, "s": 4180, "text": "Let’s verify the type of this hash using the following commands." }, { "code": null, "e": 4388, "s": 4245, "text": "$ git cat−file −t fa2c // shows type of the object represented by this hash\n$ git cat−file −p fa2c // prints the contents of the SHA1 hash" }, { "code": null, "e": 4431, "s": 4388, "text": "The output of the above commands will be −" }, { "code": null, "e": 4615, "s": 4431, "text": "// output of git cat−file −t fa2c\ntag\n// output of git cat−file −p fa2c\nobject 089ddf457ded2496a5ad5ac4384a93a109b9b7e2\ntype commit\ntag v1.1\ntagger Kiran <kiran.p@gmail.com>1612112082" }, { "code": null, "e": 4900, "s": 4615, "text": "The output shows the “fa2c” object which is contained in the “v1.1” tag file is a tag object. When we display details of the “fa2c” blob object using the cat−file −p command it points to commit “089dd” which is the last commit. We can also see the tagger name and tag message details." } ]
How to Update Data in API using Volley in Android?
26 Feb, 2021 Prerequisite: JSON Parsing in Android using Volley Library How to Post Data to API using Volley in Android? We have seen reading data from API as well as posting data to our database with the help of the API. In this article, we will take a look at updating our data in our API. We will be using the Volley library for updating our data in our API. We will be building a simple application in which we will be displaying a simple form and with that form, we will be updating our data and passing it to our API to update that data. We will be using PUT request along with volley library to update our data to API. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Add the below dependency in your build.gradle file Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. // below line is used for volley library implementation ‘com.android.volley:volley:1.1.1’ After adding this dependency sync your project and now move towards the AndroidManifest.xml part. Step 3: Adding permissions to the internet in the AndroidManifest.xml file Navigate to the app > AndroidManifest.xml and add the below code to it. XML <uses-permission android:name="android.permission.INTERNET"/> Step 4: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><!--in this we are displaying a nested scroll view--><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--edit text for our user name--> <EditText android:id="@+id/idEdtUserName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="30dp" android:layout_marginEnd="10dp" android:hint="User Name" /> <!--edit text for our job--> <EditText android:id="@+id/idEdtJob" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Job" /> <!--button to update our data--> <Button android:id="@+id/idBtnUpdate" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:text="Update Data" android:textAllCaps="false" /> <!--progress bar for the purpose of loading--> <ProgressBar android:id="@+id/idPBLoading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:visibility="gone" /> <!--text view to display our response after updating data--> <TextView android:id="@+id/idTVResponse" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:gravity="center_horizontal" android:text="Response" android:textAlignment="center" android:textColor="@color/black" android:textSize="15sp" /> </LinearLayout> Step 5: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.StringRequest;import com.android.volley.toolbox.Volley; import org.json.JSONException;import org.json.JSONObject; import java.util.HashMap;import java.util.Map; public class MainActivity extends AppCompatActivity { // creating our variables for our views such as // text view, button and progress bar // and response text view. private EditText userNameEdt, jobEdt; private Button updateBtn; private ProgressBar loadingPB; private TextView responseTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our views with their ids. userNameEdt = findViewById(R.id.idEdtUserName); jobEdt = findViewById(R.id.idEdtJob); updateBtn = findViewById(R.id.idBtnUpdate); loadingPB = findViewById(R.id.idPBLoading); responseTV = findViewById(R.id.idTVResponse); // adding on click listener for our button. updateBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // checking if the edit text is empty or not. if (TextUtils.isEmpty(userNameEdt.getText().toString()) && TextUtils.isEmpty(jobEdt.getText().toString())) { // displaying a toast message if the edit text is empty. Toast.makeText(MainActivity.this, "Please enter your data..", Toast.LENGTH_SHORT).show(); return; } // calling a method to update data in our API. callPUTDataMethod(userNameEdt.getText().toString(), jobEdt.getText().toString()); } }); } private void callPUTDataMethod(String name, String job) { // making our progress bar visible. loadingPB.setVisibility(View.VISIBLE); // url for updating our data // in below url 2 is the identity at which // we will be updating our data. String url = "https://reqres.in/api/users/2"; // creating a new variable for our request queue RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // making a string request to update our data and // passing method as PUT. to update our data. StringRequest request = new StringRequest(Request.Method.PUT, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // hiding our progress bar. loadingPB.setVisibility(View.GONE); // inside on response method we are // setting our edit text to empty. jobEdt.setText(""); userNameEdt.setText(""); // on below line we are displaying a toast message as data updated. Toast.makeText(MainActivity.this, "Data Updated..", Toast.LENGTH_SHORT).show(); try { // on below line we are extracting data from our json object // and passing our response to our json object. JSONObject jsonObject = new JSONObject(response); // creating a string for our output. String output = jsonObject.getString("name") + "\n" + jsonObject.getString("job") + "\n" + jsonObject.getString("updatedAt"); // on below line we are setting // our string to our text view. responseTV.setText(output); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // displaying toast message on response failure. Toast.makeText(MainActivity.this, "Fail to update data..", Toast.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() { // below line we are creating a map for storing // our values in key and value pair. Map<String, String> params = new HashMap<String, String>(); // on below line we are passing our key // and value pair to our parameters. params.put("name", name); params.put("job", job); // at last we are // returning our params. return params; } }; // below line is to make // a json object request. queue.add(request); }} Now run your app and see the output of the app. Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android Arrays in Java Arrays.sort() in Java with examples Split() String method in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Feb, 2021" }, { "code": null, "e": 42, "s": 28, "text": "Prerequisite:" }, { "code": null, "e": 87, "s": 42, "text": "JSON Parsing in Android using Volley Library" }, { "code": null, "e": 136, "s": 87, "text": "How to Post Data to API using Volley in Android?" }, { "code": null, "e": 378, "s": 136, "text": "We have seen reading data from API as well as posting data to our database with the help of the API. In this article, we will take a look at updating our data in our API. We will be using the Volley library for updating our data in our API. " }, { "code": null, "e": 809, "s": 378, "text": "We will be building a simple application in which we will be displaying a simple form and with that form, we will be updating our data and passing it to our API to update that data. We will be using PUT request along with volley library to update our data to API. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 838, "s": 809, "text": "Step 1: Create a New Project" }, { "code": null, "e": 1000, "s": 838, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 1059, "s": 1000, "text": "Step 2: Add the below dependency in your build.gradle file" }, { "code": null, "e": 1286, "s": 1059, "text": "Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. " }, { "code": null, "e": 1327, "s": 1286, "text": "// below line is used for volley library" }, { "code": null, "e": 1376, "s": 1327, "text": "implementation ‘com.android.volley:volley:1.1.1’" }, { "code": null, "e": 1476, "s": 1376, "text": "After adding this dependency sync your project and now move towards the AndroidManifest.xml part. " }, { "code": null, "e": 1551, "s": 1476, "text": "Step 3: Adding permissions to the internet in the AndroidManifest.xml file" }, { "code": null, "e": 1624, "s": 1551, "text": "Navigate to the app > AndroidManifest.xml and add the below code to it. " }, { "code": null, "e": 1628, "s": 1624, "text": "XML" }, { "code": "<uses-permission android:name=\"android.permission.INTERNET\"/>", "e": 1690, "s": 1628, "text": null }, { "code": null, "e": 1738, "s": 1690, "text": "Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 1881, "s": 1738, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 1885, "s": 1881, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--in this we are displaying a nested scroll view--><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--edit text for our user name--> <EditText android:id=\"@+id/idEdtUserName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"30dp\" android:layout_marginEnd=\"10dp\" android:hint=\"User Name\" /> <!--edit text for our job--> <EditText android:id=\"@+id/idEdtJob\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:hint=\"Job\" /> <!--button to update our data--> <Button android:id=\"@+id/idBtnUpdate\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:text=\"Update Data\" android:textAllCaps=\"false\" /> <!--progress bar for the purpose of loading--> <ProgressBar android:id=\"@+id/idPBLoading\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:visibility=\"gone\" /> <!--text view to display our response after updating data--> <TextView android:id=\"@+id/idTVResponse\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:gravity=\"center_horizontal\" android:text=\"Response\" android:textAlignment=\"center\" android:textColor=\"@color/black\" android:textSize=\"15sp\" /> </LinearLayout>", "e": 3823, "s": 1885, "text": null }, { "code": null, "e": 3871, "s": 3823, "text": "Step 5: Working with the MainActivity.java file" }, { "code": null, "e": 4061, "s": 3871, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 4066, "s": 4061, "text": "Java" }, { "code": "import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.StringRequest;import com.android.volley.toolbox.Volley; import org.json.JSONException;import org.json.JSONObject; import java.util.HashMap;import java.util.Map; public class MainActivity extends AppCompatActivity { // creating our variables for our views such as // text view, button and progress bar // and response text view. private EditText userNameEdt, jobEdt; private Button updateBtn; private ProgressBar loadingPB; private TextView responseTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our views with their ids. userNameEdt = findViewById(R.id.idEdtUserName); jobEdt = findViewById(R.id.idEdtJob); updateBtn = findViewById(R.id.idBtnUpdate); loadingPB = findViewById(R.id.idPBLoading); responseTV = findViewById(R.id.idTVResponse); // adding on click listener for our button. updateBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // checking if the edit text is empty or not. if (TextUtils.isEmpty(userNameEdt.getText().toString()) && TextUtils.isEmpty(jobEdt.getText().toString())) { // displaying a toast message if the edit text is empty. Toast.makeText(MainActivity.this, \"Please enter your data..\", Toast.LENGTH_SHORT).show(); return; } // calling a method to update data in our API. callPUTDataMethod(userNameEdt.getText().toString(), jobEdt.getText().toString()); } }); } private void callPUTDataMethod(String name, String job) { // making our progress bar visible. loadingPB.setVisibility(View.VISIBLE); // url for updating our data // in below url 2 is the identity at which // we will be updating our data. String url = \"https://reqres.in/api/users/2\"; // creating a new variable for our request queue RequestQueue queue = Volley.newRequestQueue(MainActivity.this); // making a string request to update our data and // passing method as PUT. to update our data. StringRequest request = new StringRequest(Request.Method.PUT, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // hiding our progress bar. loadingPB.setVisibility(View.GONE); // inside on response method we are // setting our edit text to empty. jobEdt.setText(\"\"); userNameEdt.setText(\"\"); // on below line we are displaying a toast message as data updated. Toast.makeText(MainActivity.this, \"Data Updated..\", Toast.LENGTH_SHORT).show(); try { // on below line we are extracting data from our json object // and passing our response to our json object. JSONObject jsonObject = new JSONObject(response); // creating a string for our output. String output = jsonObject.getString(\"name\") + \"\\n\" + jsonObject.getString(\"job\") + \"\\n\" + jsonObject.getString(\"updatedAt\"); // on below line we are setting // our string to our text view. responseTV.setText(output); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // displaying toast message on response failure. Toast.makeText(MainActivity.this, \"Fail to update data..\", Toast.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() { // below line we are creating a map for storing // our values in key and value pair. Map<String, String> params = new HashMap<String, String>(); // on below line we are passing our key // and value pair to our parameters. params.put(\"name\", name); params.put(\"job\", job); // at last we are // returning our params. return params; } }; // below line is to make // a json object request. queue.add(request); }}", "e": 9358, "s": 4066, "text": null }, { "code": null, "e": 9406, "s": 9358, "text": "Now run your app and see the output of the app." }, { "code": null, "e": 9430, "s": 9406, "text": "Technical Scripter 2020" }, { "code": null, "e": 9438, "s": 9430, "text": "Android" }, { "code": null, "e": 9443, "s": 9438, "text": "Java" }, { "code": null, "e": 9462, "s": 9443, "text": "Technical Scripter" }, { "code": null, "e": 9467, "s": 9462, "text": "Java" }, { "code": null, "e": 9475, "s": 9467, "text": "Android" }, { "code": null, "e": 9573, "s": 9475, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9642, "s": 9573, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 9674, "s": 9642, "text": "Android SDK and it's Components" }, { "code": null, "e": 9713, "s": 9674, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 9762, "s": 9713, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 9804, "s": 9762, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 9819, "s": 9804, "text": "Arrays in Java" }, { "code": null, "e": 9855, "s": 9819, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 9899, "s": 9855, "text": "Split() String method in Java with examples" }, { "code": null, "e": 9924, "s": 9899, "text": "Reverse a string in Java" } ]
Teradata - Logical and Conditional Operators
Teradata supports the following logical and conditional operators. These operators are used to perform comparison and combine multiple conditions. BETWEEN command is used to check if a value is within a range of values. Consider the following employee table. The following example fetches records with employee numbers in the range between 101,102 and 103. SELECT EmployeeNo, FirstName FROM Employee WHERE EmployeeNo BETWEEN 101 AND 103; When the above query is executed, it returns the employee records with employee no between 101 and 103. *** Query completed. 3 rows found. 2 columns returned. *** Total elapsed time was 1 second. EmployeeNo FirstName ----------- ------------------------------ 101 Mike 102 Robert 103 Peter IN command is used to check the value against a given list of values. The following example fetches records with employee numbers in 101, 102 and 103. SELECT EmployeeNo, FirstName FROM Employee WHERE EmployeeNo in (101,102,103); The above query returns the following records. *** Query completed. 3 rows found. 2 columns returned. *** Total elapsed time was 1 second. EmployeeNo FirstName ----------- ------------------------------ 101 Mike 102 Robert 103 Peter NOT IN command reverses the result of IN command. It fetches records with values that don’t match with the given list. The following example fetches records with employee numbers not in 101, 102 and 103. SELECT * FROM Employee WHERE EmployeeNo not in (101,102,103); The above query returns the following records. *** Query completed. 2 rows found. 6 columns returned. *** Total elapsed time was 1 second. EmployeeNo FirstName LastName ----------- ------------------------------ ----------------------------- 104 Alex Stuart 105 Robert James
[ { "code": null, "e": 2911, "s": 2764, "text": "Teradata supports the following logical and conditional operators. These operators are used to perform comparison and combine multiple conditions." }, { "code": null, "e": 2984, "s": 2911, "text": "BETWEEN command is used to check if a value is within a range of values." }, { "code": null, "e": 3023, "s": 2984, "text": "Consider the following employee table." }, { "code": null, "e": 3121, "s": 3023, "text": "The following example fetches records with employee numbers in the range between 101,102 and 103." }, { "code": null, "e": 3205, "s": 3121, "text": "SELECT EmployeeNo, FirstName FROM \nEmployee \nWHERE EmployeeNo BETWEEN 101 AND 103;" }, { "code": null, "e": 3309, "s": 3205, "text": "When the above query is executed, it returns the employee records with employee no between 101 and 103." }, { "code": null, "e": 3578, "s": 3309, "text": "*** Query completed. 3 rows found. 2 columns returned. \n*** Total elapsed time was 1 second. \n EmployeeNo FirstName \n----------- ------------------------------ \n 101 Mike \n 102 Robert \n 103 Peter\n" }, { "code": null, "e": 3648, "s": 3578, "text": "IN command is used to check the value against a given list of values." }, { "code": null, "e": 3729, "s": 3648, "text": "The following example fetches records with employee numbers in 101, 102 and 103." }, { "code": null, "e": 3810, "s": 3729, "text": "SELECT EmployeeNo, FirstName FROM \nEmployee \nWHERE EmployeeNo in (101,102,103);" }, { "code": null, "e": 3857, "s": 3810, "text": "The above query returns the following records." }, { "code": null, "e": 4127, "s": 3857, "text": "*** Query completed. 3 rows found. 2 columns returned. \n*** Total elapsed time was 1 second. \n EmployeeNo FirstName \n----------- ------------------------------ \n 101 Mike \n 102 Robert \n 103 Peter\n" }, { "code": null, "e": 4246, "s": 4127, "text": "NOT IN command reverses the result of IN command. It fetches records with values that don’t match with the given list." }, { "code": null, "e": 4331, "s": 4246, "text": "The following example fetches records with employee numbers not in 101, 102 and 103." }, { "code": null, "e": 4396, "s": 4331, "text": "SELECT * FROM \nEmployee \nWHERE EmployeeNo not in (101,102,103);" }, { "code": null, "e": 4443, "s": 4396, "text": "The above query returns the following records." } ]
Multi-Messenger : A python project, messaging via Terminal
30 May, 2018 The aim of this program is to let users mail/message on FB/SMS anyone using Terminal. The full project can be found here. So, first of all, why Multi-Messenger ? This is the first question which anyone will think about. The answer is simple, Terminal! Many of our work, now a days, lies in Terminal, talking about Programmers here in specific. So who wouldn’t like to message or mail or SMS someone quickly through Terminal? Requirements : For Linux Users: In order to compile the program successfully, installation of the following modules is necessaryTwilio Client: Run this code from Terminalpip install twilio pip install twilio fbchat Module: Run this code from Terminalpip install fbchat pip install fbchat Preferred Method using pip [See installation manual for installing pip in Linux] Code:The project is open sourced, and the code can be found in Github. Twilio Client can be used to SMS someone, fbchat is used to send a message to your Facebook friend and gmtp library has been used to send mail using Python. Python AutoGUI has also been used here, to give the user an option of a dialog based option. It will help the user if he’s not in love with Terminal.These screenshots show how it looks like: Message Received: This article is contributed by Kushashwa Ravi Shrimali and Krutika Bapat. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Project Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 10 Best Web Development Projects For Your Resume E-commerce Website using Django Banking Transaction System using Java Voting System Project Using Django Framework Browser Automation Using Selenium Student record management system using linked list Handling Ajax request in Django Setup Sending Email in Django Project How to Build Portfolio Website And Host It on GitHub Pages? College Management System using Django - Python Project
[ { "code": null, "e": 54, "s": 26, "text": "\n30 May, 2018" }, { "code": null, "e": 176, "s": 54, "text": "The aim of this program is to let users mail/message on FB/SMS anyone using Terminal. The full project can be found here." }, { "code": null, "e": 216, "s": 176, "text": "So, first of all, why Multi-Messenger ?" }, { "code": null, "e": 479, "s": 216, "text": "This is the first question which anyone will think about. The answer is simple, Terminal! Many of our work, now a days, lies in Terminal, talking about Programmers here in specific. So who wouldn’t like to message or mail or SMS someone quickly through Terminal?" }, { "code": null, "e": 494, "s": 479, "text": "Requirements :" }, { "code": null, "e": 511, "s": 494, "text": "For Linux Users:" }, { "code": null, "e": 668, "s": 511, "text": "In order to compile the program successfully, installation of the following modules is necessaryTwilio Client: Run this code from Terminalpip install twilio" }, { "code": null, "e": 687, "s": 668, "text": "pip install twilio" }, { "code": null, "e": 748, "s": 687, "text": "fbchat Module: Run this code from Terminalpip install fbchat" }, { "code": null, "e": 767, "s": 748, "text": "pip install fbchat" }, { "code": null, "e": 848, "s": 767, "text": "Preferred Method using pip [See installation manual for installing pip in Linux]" }, { "code": null, "e": 1267, "s": 848, "text": "Code:The project is open sourced, and the code can be found in Github. Twilio Client can be used to SMS someone, fbchat is used to send a message to your Facebook friend and gmtp library has been used to send mail using Python. Python AutoGUI has also been used here, to give the user an option of a dialog based option. It will help the user if he’s not in love with Terminal.These screenshots show how it looks like:" }, { "code": null, "e": 1285, "s": 1267, "text": "Message Received:" }, { "code": null, "e": 1616, "s": 1287, "text": "This article is contributed by Kushashwa Ravi Shrimali and Krutika Bapat. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 1741, "s": 1616, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 1749, "s": 1741, "text": "Project" }, { "code": null, "e": 1847, "s": 1749, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1896, "s": 1847, "text": "10 Best Web Development Projects For Your Resume" }, { "code": null, "e": 1928, "s": 1896, "text": "E-commerce Website using Django" }, { "code": null, "e": 1966, "s": 1928, "text": "Banking Transaction System using Java" }, { "code": null, "e": 2011, "s": 1966, "text": "Voting System Project Using Django Framework" }, { "code": null, "e": 2045, "s": 2011, "text": "Browser Automation Using Selenium" }, { "code": null, "e": 2096, "s": 2045, "text": "Student record management system using linked list" }, { "code": null, "e": 2128, "s": 2096, "text": "Handling Ajax request in Django" }, { "code": null, "e": 2166, "s": 2128, "text": "Setup Sending Email in Django Project" }, { "code": null, "e": 2226, "s": 2166, "text": "How to Build Portfolio Website And Host It on GitHub Pages?" } ]
Working of ISO-OSI Model
04 Jul, 2022 The ISO-OSI (International organization of Standardization – Open System Interconnection) says to group together the functions which are related to each other. The Functions in OSI Model that are needed for proper communication can be divided into 2 types :- 1. Mandatory Functions: Here the implementation of the functions is not optional, i.e., it means these functions must be implemented for proper communication. (i) Error Control (ii) Flow Control (iii) Access Control (iv) Multiplexing and De-Multiplexing (v) Addressing, etc. 2. Optional Functions: Here the implementation of the functions is optional, i.e., it means the implementation of these functions is not must. (i) Encryption/ Decryption (ii) Check Pointing. (iii) Routing, etc. Routing is optional we can sustain in Computer networks even by using Flooding. 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. Now the reasons ISO-OSI model says to group together similar functions, here we will be explaining why exactly we need different layer for efficient routing. Every layer can implement similar functions and every layer can perform some specific tasks.It would even help in grouping all the variables together used in those similar functions, thus this would protect the variables in a layer and are not scattered all over the layers (so it’s kind of Encapsulation).Now as every layer is performing their some specific task so we are cornered about our layer only and not in how the under-lying layer is implemented (so its kind of Abstraction). In simple words, we can say we are concerned only about what function we get from a layer and not how we get that.It helps in Testing, it means each layer can be tested separately thus it would be easy to find errors if present any. Every layer can implement similar functions and every layer can perform some specific tasks. It would even help in grouping all the variables together used in those similar functions, thus this would protect the variables in a layer and are not scattered all over the layers (so it’s kind of Encapsulation). Now as every layer is performing their some specific task so we are cornered about our layer only and not in how the under-lying layer is implemented (so its kind of Abstraction). In simple words, we can say we are concerned only about what function we get from a layer and not how we get that. It helps in Testing, it means each layer can be tested separately thus it would be easy to find errors if present any. Now the layers in ISO-OSI model :- 1. Application Layer 2. Presentation Layer 3. Session Layer 4. Transport Layer 5. Network Layer 6. Data link Layer 7. Physical Layer The first 3 layers are usually for intended user-specific . 1. Physical Layer: It deals with how our data, which are in bit are going to be get converted into various kinds of signals and how these are to be transported among routers and hosts. It handles concepts like :- Transmission – It means it handles if channels are simplex, half-duplex, Full duplex. Topology – It decides what is the topology of the network. For example: Bus Topology, Star Topology, Ring Topology, etc. Encoding – It decides what kinds of encoding is to be used to convert 0’s and 1’s into waves and send them across the channels. 2. Data Link Layer: The major functions of data link layer are :- Flow Control – Basically Flow control means the rate at which the sender is sending should be somewhat sunk with the rate at which receiver can receive and process the data. If a sink is not maintained then the data packets would get lost. These Flow Control also helps in determining the algorithm in which we will repeat the process of sending the lost packets. It says which of the flow controls are to be used (S&W or GBN or SR). Error Control – Here the functions are implemented which help in error detection. The CRC (Cyclic Redundancy Check) algorithm is implemented here to detect the errors. Framing – The task of this is to put the packets (datagrams from Network layer) received from above layers into a frame and send it. These frames have a SFD(Starting Frame Delimiter) which alerts the routers that a new packet is coming. And these packets can even have a ED (End Delimiter) when we use variable length Frames saying that the packet is over. To mark this ED 2 strategies are used: Character Stuffing, and Bit Stuffing. The DLL (Data link Layer) is itself divided into 2 parts: LLC (Logical Link Control) – Dealing mainly with Flow control and Error Control.MAC (Medium Access control) – It deals with Framing, Access Control methods, Error Control (yes it also does), Physical Addressing. LLC (Logical Link Control) – Dealing mainly with Flow control and Error Control. MAC (Medium Access control) – It deals with Framing, Access Control methods, Error Control (yes it also does), Physical Addressing. 3. Network Layer: This layer deals with the host-to-host connectivity, i.e., this layer is concerned about how packets are to be transferred without error from one host(sender) to other host(receiver). This layer uses the Logical Addressing which is unique for a device in the entire internet. It also deals with the Switching of the packets to reach the desired host. The Switching of Packets is done by using the Routing Tables. This Layer also performs the task of Congestion control. Most important that this layer also performs is Fragmentation of packets. The Fragmentation, when the packets are to be transferred through a network which have less MTU (Maximum Transmission unit). Thus the datagrams are fragmented here so that they can be successfully transferred through that network. 4. Transport Layer: This Layer handles the End-to-end connectivity it means this layer is important for the data packet to reach the exact port of the host . The Network Layer will bring the packet and give to host but the Transport Layer is the layer that helps the data packets to reach the designated port. The other Functions of Transport layer are Flow Control (using SR protocol), Error Control, Segmentation, Multiplexing and demultiplexing, Congestion control. 5. Session Layer: Mainly Deals with :- Authentication and Authorisation Checkpointing Synchronization Logical grouping of operations (i.e., either all operations or no operations) 6. Presentation Layer: This layer Mainly Deals with :- Encryption and Decryption Compression Now after learning the functions of the important layers. Now let’s see how it exactly works. Consider the case that we want to use GfG(GeeksforGeeks). Then when we start to send some data then after passing from initial layers (Application) the data will reach in Transport Layer where the port numbers of source and destination are added to the data packet. Then the packet is given to Network Layer and now this Layer will add source and destination IP addresses so that there would be proper communication between the sender and receiver. After that the Packet is given to Data Link Layer where the MAC addresses of source and destination are added. Now an important thing to note is that initially by Logically ANDing the Subnet mask and Destination IP address we try to find to that if we have an entry for the destination network. If no entry is present in routing table then we use the mac address of the default gateway (router) as the destination mac address. Now to find the MAC address of the router the host sends ARP request so that it receive the MAC address. ARP (Address Resolution Protocol) request is like saying please send me your MAC address whose IP address is this (Logically). In the Data Link Layer, sometimes also the Fragmentation is performed so that packet can fit into the network’s MTU (as explained earlier). After all this data-packet is given to Physical Layer and is transported. Now when the packet reaches the router (whose mac address was written in the packet) the router accepts that packet then removes the headers and give to Network Layer of that Router and there it checks if the packet is for it or someone else by checking the destination ip in the router. Then again the above mentioned process of DLL is performed again by the router. This process is repeated until the packets reach the Destination Network. On Reaching the Destination Host DLL removes the headers and give the data packet to NL then the NL finds that the packet is for it. Thus, the data is given to the designated port of the Host. And thus finally after receiving the packet successfully the Transport Layer sends an acknowledgment to the Host that packet has been successfully delivered and this acknowledgment sent back will go through the exact steps mentioned above. The router’s Data link Layer also give acknowledgments after receiving the packet packets. akshayanand7 rithesharjun praharsh922 abhishekpal97854368 Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n04 Jul, 2022" }, { "code": null, "e": 214, "s": 53, "text": "The ISO-OSI (International organization of Standardization – Open System Interconnection) says to group together the functions which are related to each other. " }, { "code": null, "e": 314, "s": 214, "text": "The Functions in OSI Model that are needed for proper communication can be divided into 2 types :- " }, { "code": null, "e": 474, "s": 314, "text": "1. Mandatory Functions: Here the implementation of the functions is not optional, i.e., it means these functions must be implemented for proper communication. " }, { "code": null, "e": 591, "s": 474, "text": "(i) Error Control\n(ii) Flow Control\n(iii) Access Control\n(iv) Multiplexing and De-Multiplexing\n(v) Addressing, etc. " }, { "code": null, "e": 735, "s": 591, "text": "2. Optional Functions: Here the implementation of the functions is optional, i.e., it means the implementation of these functions is not must. " }, { "code": null, "e": 804, "s": 735, "text": "(i) Encryption/ Decryption\n(ii) Check Pointing.\n(iii) Routing, etc. " }, { "code": null, "e": 885, "s": 804, "text": "Routing is optional we can sustain in Computer networks even by using Flooding. " }, { "code": null, "e": 894, "s": 885, "text": "Chapters" }, { "code": null, "e": 921, "s": 894, "text": "descriptions off, selected" }, { "code": null, "e": 971, "s": 921, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 994, "s": 971, "text": "captions off, selected" }, { "code": null, "e": 1002, "s": 994, "text": "English" }, { "code": null, "e": 1026, "s": 1002, "text": "This is a modal window." }, { "code": null, "e": 1095, "s": 1026, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1117, "s": 1095, "text": "End of dialog window." }, { "code": null, "e": 1276, "s": 1117, "text": "Now the reasons ISO-OSI model says to group together similar functions, here we will be explaining why exactly we need different layer for efficient routing. " }, { "code": null, "e": 1997, "s": 1276, "text": "Every layer can implement similar functions and every layer can perform some specific tasks.It would even help in grouping all the variables together used in those similar functions, thus this would protect the variables in a layer and are not scattered all over the layers (so it’s kind of Encapsulation).Now as every layer is performing their some specific task so we are cornered about our layer only and not in how the under-lying layer is implemented (so its kind of Abstraction). In simple words, we can say we are concerned only about what function we get from a layer and not how we get that.It helps in Testing, it means each layer can be tested separately thus it would be easy to find errors if present any. " }, { "code": null, "e": 2090, "s": 1997, "text": "Every layer can implement similar functions and every layer can perform some specific tasks." }, { "code": null, "e": 2305, "s": 2090, "text": "It would even help in grouping all the variables together used in those similar functions, thus this would protect the variables in a layer and are not scattered all over the layers (so it’s kind of Encapsulation)." }, { "code": null, "e": 2600, "s": 2305, "text": "Now as every layer is performing their some specific task so we are cornered about our layer only and not in how the under-lying layer is implemented (so its kind of Abstraction). In simple words, we can say we are concerned only about what function we get from a layer and not how we get that." }, { "code": null, "e": 2721, "s": 2600, "text": "It helps in Testing, it means each layer can be tested separately thus it would be easy to find errors if present any. " }, { "code": null, "e": 2757, "s": 2721, "text": "Now the layers in ISO-OSI model :- " }, { "code": null, "e": 2891, "s": 2757, "text": "1. Application Layer\n2. Presentation Layer\n3. Session Layer\n4. Transport Layer\n5. Network Layer\n6. Data link Layer\n7. Physical Layer " }, { "code": null, "e": 2952, "s": 2891, "text": "The first 3 layers are usually for intended user-specific . " }, { "code": null, "e": 3138, "s": 2952, "text": "1. Physical Layer: It deals with how our data, which are in bit are going to be get converted into various kinds of signals and how these are to be transported among routers and hosts. " }, { "code": null, "e": 3167, "s": 3138, "text": "It handles concepts like :- " }, { "code": null, "e": 3253, "s": 3167, "text": "Transmission – It means it handles if channels are simplex, half-duplex, Full duplex." }, { "code": null, "e": 3374, "s": 3253, "text": "Topology – It decides what is the topology of the network. For example: Bus Topology, Star Topology, Ring Topology, etc." }, { "code": null, "e": 3504, "s": 3374, "text": "Encoding – It decides what kinds of encoding is to be used to convert 0’s and 1’s into waves and send them across the channels. " }, { "code": null, "e": 3571, "s": 3504, "text": "2. Data Link Layer: The major functions of data link layer are :- " }, { "code": null, "e": 4005, "s": 3571, "text": "Flow Control – Basically Flow control means the rate at which the sender is sending should be somewhat sunk with the rate at which receiver can receive and process the data. If a sink is not maintained then the data packets would get lost. These Flow Control also helps in determining the algorithm in which we will repeat the process of sending the lost packets. It says which of the flow controls are to be used (S&W or GBN or SR)." }, { "code": null, "e": 4173, "s": 4005, "text": "Error Control – Here the functions are implemented which help in error detection. The CRC (Cyclic Redundancy Check) algorithm is implemented here to detect the errors." }, { "code": null, "e": 4530, "s": 4173, "text": "Framing – The task of this is to put the packets (datagrams from Network layer) received from above layers into a frame and send it. These frames have a SFD(Starting Frame Delimiter) which alerts the routers that a new packet is coming. And these packets can even have a ED (End Delimiter) when we use variable length Frames saying that the packet is over." }, { "code": null, "e": 4608, "s": 4530, "text": "To mark this ED 2 strategies are used: Character Stuffing, and Bit Stuffing. " }, { "code": null, "e": 4667, "s": 4608, "text": "The DLL (Data link Layer) is itself divided into 2 parts: " }, { "code": null, "e": 4879, "s": 4667, "text": "LLC (Logical Link Control) – Dealing mainly with Flow control and Error Control.MAC (Medium Access control) – It deals with Framing, Access Control methods, Error Control (yes it also does), Physical Addressing." }, { "code": null, "e": 4960, "s": 4879, "text": "LLC (Logical Link Control) – Dealing mainly with Flow control and Error Control." }, { "code": null, "e": 5092, "s": 4960, "text": "MAC (Medium Access control) – It deals with Framing, Access Control methods, Error Control (yes it also does), Physical Addressing." }, { "code": null, "e": 5387, "s": 5092, "text": "3. Network Layer: This layer deals with the host-to-host connectivity, i.e., this layer is concerned about how packets are to be transferred without error from one host(sender) to other host(receiver). This layer uses the Logical Addressing which is unique for a device in the entire internet. " }, { "code": null, "e": 5526, "s": 5387, "text": "It also deals with the Switching of the packets to reach the desired host. The Switching of Packets is done by using the Routing Tables. " }, { "code": null, "e": 5584, "s": 5526, "text": "This Layer also performs the task of Congestion control. " }, { "code": null, "e": 5890, "s": 5584, "text": "Most important that this layer also performs is Fragmentation of packets. The Fragmentation, when the packets are to be transferred through a network which have less MTU (Maximum Transmission unit). Thus the datagrams are fragmented here so that they can be successfully transferred through that network. " }, { "code": null, "e": 6201, "s": 5890, "text": "4. Transport Layer: This Layer handles the End-to-end connectivity it means this layer is important for the data packet to reach the exact port of the host . The Network Layer will bring the packet and give to host but the Transport Layer is the layer that helps the data packets to reach the designated port. " }, { "code": null, "e": 6361, "s": 6201, "text": "The other Functions of Transport layer are Flow Control (using SR protocol), Error Control, Segmentation, Multiplexing and demultiplexing, Congestion control. " }, { "code": null, "e": 6401, "s": 6361, "text": "5. Session Layer: Mainly Deals with :- " }, { "code": null, "e": 6434, "s": 6401, "text": "Authentication and Authorisation" }, { "code": null, "e": 6448, "s": 6434, "text": "Checkpointing" }, { "code": null, "e": 6464, "s": 6448, "text": "Synchronization" }, { "code": null, "e": 6542, "s": 6464, "text": "Logical grouping of operations (i.e., either all operations or no operations)" }, { "code": null, "e": 6598, "s": 6542, "text": "6. Presentation Layer: This layer Mainly Deals with :- " }, { "code": null, "e": 6624, "s": 6598, "text": "Encryption and Decryption" }, { "code": null, "e": 6636, "s": 6624, "text": "Compression" }, { "code": null, "e": 7180, "s": 6636, "text": "Now after learning the functions of the important layers. Now let’s see how it exactly works. Consider the case that we want to use GfG(GeeksforGeeks). Then when we start to send some data then after passing from initial layers (Application) the data will reach in Transport Layer where the port numbers of source and destination are added to the data packet. Then the packet is given to Network Layer and now this Layer will add source and destination IP addresses so that there would be proper communication between the sender and receiver. " }, { "code": null, "e": 7292, "s": 7180, "text": "After that the Packet is given to Data Link Layer where the MAC addresses of source and destination are added. " }, { "code": null, "e": 7714, "s": 7292, "text": "Now an important thing to note is that initially by Logically ANDing the Subnet mask and Destination IP address we try to find to that if we have an entry for the destination network. If no entry is present in routing table then we use the mac address of the default gateway (router) as the destination mac address. Now to find the MAC address of the router the host sends ARP request so that it receive the MAC address. " }, { "code": null, "e": 7842, "s": 7714, "text": "ARP (Address Resolution Protocol) request is like saying please send me your MAC address whose IP address is this (Logically). " }, { "code": null, "e": 7984, "s": 7842, "text": "In the Data Link Layer, sometimes also the Fragmentation is performed so that packet can fit into the network’s MTU (as explained earlier). " }, { "code": null, "e": 8059, "s": 7984, "text": "After all this data-packet is given to Physical Layer and is transported. " }, { "code": null, "e": 8502, "s": 8059, "text": "Now when the packet reaches the router (whose mac address was written in the packet) the router accepts that packet then removes the headers and give to Network Layer of that Router and there it checks if the packet is for it or someone else by checking the destination ip in the router. Then again the above mentioned process of DLL is performed again by the router. This process is repeated until the packets reach the Destination Network. " }, { "code": null, "e": 8936, "s": 8502, "text": "On Reaching the Destination Host DLL removes the headers and give the data packet to NL then the NL finds that the packet is for it. Thus, the data is given to the designated port of the Host. And thus finally after receiving the packet successfully the Transport Layer sends an acknowledgment to the Host that packet has been successfully delivered and this acknowledgment sent back will go through the exact steps mentioned above. " }, { "code": null, "e": 9028, "s": 8936, "text": "The router’s Data link Layer also give acknowledgments after receiving the packet packets. " }, { "code": null, "e": 9041, "s": 9028, "text": "akshayanand7" }, { "code": null, "e": 9054, "s": 9041, "text": "rithesharjun" }, { "code": null, "e": 9066, "s": 9054, "text": "praharsh922" }, { "code": null, "e": 9086, "s": 9066, "text": "abhishekpal97854368" }, { "code": null, "e": 9104, "s": 9086, "text": "Computer Networks" }, { "code": null, "e": 9112, "s": 9104, "text": "GATE CS" }, { "code": null, "e": 9130, "s": 9112, "text": "Computer Networks" } ]
Python | Create an empty text file with current date as its name
02 Aug, 2019 In this article, we will learn how to create a text file names as the current date in it. For this, we can use now() method of datetime module. The datetime module supplies classes for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation. Let’s see a code example and try to understand it better. # Python script to create an empty file# with current date as name. # importing datetime moduleimport datetime # datetime.datetime.now() to get # current date as filename.filename = datetime.datetime.now() # create empty filedef create_file(): # Function creates an empty file # %d - date, %B - month, %Y - Year with open(filename.strftime("%d %B %Y")+".txt", "w") as file: file.write("") # Driver Codecreate_file() Output: 01 August 2019.txt Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Aug, 2019" }, { "code": null, "e": 172, "s": 28, "text": "In this article, we will learn how to create a text file names as the current date in it. For this, we can use now() method of datetime module." }, { "code": null, "e": 429, "s": 172, "text": "The datetime module supplies classes for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation." }, { "code": null, "e": 487, "s": 429, "text": "Let’s see a code example and try to understand it better." }, { "code": "# Python script to create an empty file# with current date as name. # importing datetime moduleimport datetime # datetime.datetime.now() to get # current date as filename.filename = datetime.datetime.now() # create empty filedef create_file(): # Function creates an empty file # %d - date, %B - month, %Y - Year with open(filename.strftime(\"%d %B %Y\")+\".txt\", \"w\") as file: file.write(\"\") # Driver Codecreate_file()", "e": 923, "s": 487, "text": null }, { "code": null, "e": 931, "s": 923, "text": "Output:" }, { "code": null, "e": 950, "s": 931, "text": "01 August 2019.txt" }, { "code": null, "e": 957, "s": 950, "text": "Python" }, { "code": null, "e": 973, "s": 957, "text": "Python Programs" }, { "code": null, "e": 1071, "s": 973, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1089, "s": 1071, "text": "Python Dictionary" }, { "code": null, "e": 1131, "s": 1089, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1153, "s": 1131, "text": "Enumerate() in Python" }, { "code": null, "e": 1179, "s": 1153, "text": "Python String | replace()" }, { "code": null, "e": 1211, "s": 1179, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1254, "s": 1211, "text": "Python program to convert a list to string" }, { "code": null, "e": 1276, "s": 1254, "text": "Defaultdict in Python" }, { "code": null, "e": 1315, "s": 1276, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1353, "s": 1315, "text": "Python | Convert a list to dictionary" } ]
Templates in C++ with Examples
13 May, 2022 A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter. C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The second keyword can always be replaced by keyword ‘class’. How do templates work? Templates are expanded at compiler time. This is like macros. The difference is, the compiler does type checking before template expansion. The idea is simple, source code contains only function/class, but compiled code may contain multiple copies of same function/class. Function Templates We write a generic function that can be used for different data types. Examples of function templates are sort(), max(), min(), printArray(). Know more on Generics in C++ CPP #include <iostream>using namespace std; // One function works for all data types. This would work// even for user defined types if operator '>' is overloadedtemplate <typename T> T myMax(T x, T y){ return (x > y) ? x : y;} int main(){ cout << myMax<int>(3, 7) << endl; // Call myMax for int cout << myMax<double>(3.0, 7.0) << endl; // call myMax for double cout << myMax<char>('g', 'e') << endl; // call myMax for char return 0;} 7 7 g Below is the program to implement Bubble Sort using templates in C++: CPP // CPP code for bubble sort// using template function#include <iostream>using namespace std; // A template function to implement bubble sort.// We can use this for any data type that supports// comparison operator < and swap works for it.template <class T> void bubbleSort(T a[], int n){ for (int i = 0; i < n - 1; i++) for (int j = n - 1; i < j; j--) if (a[j] < a[j - 1]) swap(a[j], a[j - 1]);} // Driver Codeint main(){ int a[5] = { 10, 50, 30, 40, 20 }; int n = sizeof(a) / sizeof(a[0]); // calls template function bubbleSort<int>(a, n); cout << " Sorted array : "; for (int i = 0; i < n; i++) cout << a[i] << " "; cout << endl; return 0;} Sorted array : 10 20 30 40 50 Class Templates Like function templates, class templates are useful when a class defines something that is independent of the data type. Can be useful for classes like LinkedList, BinaryTree, Stack, Queue, Array, etc. Following is a simple example of template Array class. CPP #include <iostream>using namespace std; template <typename T> class Array {private: T* ptr; int size; public: Array(T arr[], int s); void print();}; template <typename T> Array<T>::Array(T arr[], int s){ ptr = new T[s]; size = s; for (int i = 0; i < size; i++) ptr[i] = arr[i];} template <typename T> void Array<T>::print(){ for (int i = 0; i < size; i++) cout << " " << *(ptr + i); cout << endl;} int main(){ int arr[5] = { 1, 2, 3, 4, 5 }; Array<int> a(arr, 5); a.print(); return 0;} 1 2 3 4 5 Can there be more than one arguments to templates? Yes, like normal parameters, we can pass more than one data types as arguments to templates. The following example demonstrates the same. CPP #include <iostream>using namespace std; template <class T, class U> class A { T x; U y; public: A() { cout << "Constructor Called" << endl; }}; int main(){ A<char, char> a; A<int, double> b; return 0;} Constructor Called Constructor Called Can we specify default value for template arguments? Yes, like normal parameters, we can specify default arguments to templates. The following example demonstrates the same. CPP #include <iostream>using namespace std; template <class T, class U = char> class A {public: T x; U y; A() { cout << "Constructor Called" << endl; }}; int main(){ A<char> a; // This will call A<char, char> return 0;} Constructor Called What is the difference between function overloading and templates? Both function overloading and templates are examples of polymorphism feature of OOP. Function overloading is used when multiple functions do similar operations, templates are used when multiple functions do identical operations. What happens when there is a static member in a template class/function? Each instance of a template contains its own static variable. See Templates and Static variables for more details. What is template specialization? Template specialization allows us to have different code for a particular data type. See Template Specialization for more details. Can we pass nontype parameters to templates? We can pass non-type arguments to templates. Non-type parameters are mainly used for specifying max or min values or any other constant value for a particular instance of a template. The important thing to note about non-type parameters is, they must be const. The compiler must know the value of non-type parameters at compile time. Because the compiler needs to create functions/classes for a specified non-type value at compile time. In below program, if we replace 10000 or 25 with a variable, we get a compiler error. Please see this. Below is a C++ program. CPP // A C++ program to demonstrate working of non-type// parameters to templates in C++.#include <iostream>using namespace std; template <class T, int max> int arrMin(T arr[], int n){ int m = max; for (int i = 0; i < n; i++) if (arr[i] < m) m = arr[i]; return m;} int main(){ int arr1[] = { 10, 20, 15, 12 }; int n1 = sizeof(arr1) / sizeof(arr1[0]); char arr2[] = { 1, 2, 3 }; int n2 = sizeof(arr2) / sizeof(arr2[0]); // Second template parameter to arrMin must be a // constant cout << arrMin<int, 10000>(arr1, n1) << endl; cout << arrMin<char, 256>(arr2, n2); return 0;} 10 1 Here is an example of C++ program to show different data types using constructor and template. We will perform few actions passing character value by creating an objects in main() function. passing integer value by creating an objects in main() function. passing float value by creating an objects in main() function. C++ // #include <conio.h>#include <iostream>using namespace std; // defining a class templatetemplate <class T> class info {public: info(T A) // constructor of type template { cout << "\n" << "A = " << A << " size of data in bytes:" << sizeof(A); } // end of info()}; // end of class // Main Functionint main(){ // clrscr(); // passing character value by creating an objects info<char> p('x'); // passing integer value by creating an object info<int> q(22); // passing float value by creating an object info<float> r(2.25); return 0;} // end of Main Function A = x size of data in bytes:1 A = 22 size of data in bytes:4 A = 2.25 size of data in bytes:4 What is template metaprogramming? See Template Metaprogramming You may also like to take a quiz on templates.Java also supports these features. Java calls it generics . Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anu7699 stathpaul biplab_prasad hakukiro dey0btpch57lmvgz5mqhpaiqn337p09fd8yq1lw4 RishabhPrabhu cpp-template C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) std::sort() in C++ STL Bitwise Operators in C/C++ Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Inheritance in C++ Priority Queue in C++ Standard Template Library (STL)
[ { "code": null, "e": 54, "s": 26, "text": "\n13 May, 2022" }, { "code": null, "e": 561, "s": 54, "text": "A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter. C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The second keyword can always be replaced by keyword ‘class’." }, { "code": null, "e": 858, "s": 561, "text": "How do templates work? Templates are expanded at compiler time. This is like macros. The difference is, the compiler does type checking before template expansion. The idea is simple, source code contains only function/class, but compiled code may contain multiple copies of same function/class. " }, { "code": null, "e": 1051, "s": 858, "text": " Function Templates We write a generic function that can be used for different data types. Examples of function templates are sort(), max(), min(), printArray(). Know more on Generics in C++ " }, { "code": null, "e": 1055, "s": 1051, "text": "CPP" }, { "code": "#include <iostream>using namespace std; // One function works for all data types. This would work// even for user defined types if operator '>' is overloadedtemplate <typename T> T myMax(T x, T y){ return (x > y) ? x : y;} int main(){ cout << myMax<int>(3, 7) << endl; // Call myMax for int cout << myMax<double>(3.0, 7.0) << endl; // call myMax for double cout << myMax<char>('g', 'e') << endl; // call myMax for char return 0;}", "e": 1521, "s": 1055, "text": null }, { "code": null, "e": 1528, "s": 1521, "text": "7\n7\ng\n" }, { "code": null, "e": 1600, "s": 1528, "text": "Below is the program to implement Bubble Sort using templates in C++: " }, { "code": null, "e": 1604, "s": 1600, "text": "CPP" }, { "code": "// CPP code for bubble sort// using template function#include <iostream>using namespace std; // A template function to implement bubble sort.// We can use this for any data type that supports// comparison operator < and swap works for it.template <class T> void bubbleSort(T a[], int n){ for (int i = 0; i < n - 1; i++) for (int j = n - 1; i < j; j--) if (a[j] < a[j - 1]) swap(a[j], a[j - 1]);} // Driver Codeint main(){ int a[5] = { 10, 50, 30, 40, 20 }; int n = sizeof(a) / sizeof(a[0]); // calls template function bubbleSort<int>(a, n); cout << \" Sorted array : \"; for (int i = 0; i < n; i++) cout << a[i] << \" \"; cout << endl; return 0;}", "e": 2322, "s": 1604, "text": null }, { "code": null, "e": 2355, "s": 2322, "text": " Sorted array : 10 20 30 40 50 \n" }, { "code": null, "e": 2574, "s": 2355, "text": "Class Templates Like function templates, class templates are useful when a class defines something that is independent of the data type. Can be useful for classes like LinkedList, BinaryTree, Stack, Queue, Array, etc. " }, { "code": null, "e": 2630, "s": 2574, "text": "Following is a simple example of template Array class. " }, { "code": null, "e": 2634, "s": 2630, "text": "CPP" }, { "code": "#include <iostream>using namespace std; template <typename T> class Array {private: T* ptr; int size; public: Array(T arr[], int s); void print();}; template <typename T> Array<T>::Array(T arr[], int s){ ptr = new T[s]; size = s; for (int i = 0; i < size; i++) ptr[i] = arr[i];} template <typename T> void Array<T>::print(){ for (int i = 0; i < size; i++) cout << \" \" << *(ptr + i); cout << endl;} int main(){ int arr[5] = { 1, 2, 3, 4, 5 }; Array<int> a(arr, 5); a.print(); return 0;}", "e": 3178, "s": 2634, "text": null }, { "code": null, "e": 3190, "s": 3178, "text": " 1 2 3 4 5\n" }, { "code": null, "e": 3381, "s": 3190, "text": "Can there be more than one arguments to templates? Yes, like normal parameters, we can pass more than one data types as arguments to templates. The following example demonstrates the same. " }, { "code": null, "e": 3385, "s": 3381, "text": "CPP" }, { "code": "#include <iostream>using namespace std; template <class T, class U> class A { T x; U y; public: A() { cout << \"Constructor Called\" << endl; }}; int main(){ A<char, char> a; A<int, double> b; return 0;}", "e": 3608, "s": 3385, "text": null }, { "code": null, "e": 3647, "s": 3608, "text": "Constructor Called\nConstructor Called\n" }, { "code": null, "e": 3823, "s": 3647, "text": "Can we specify default value for template arguments? Yes, like normal parameters, we can specify default arguments to templates. The following example demonstrates the same. " }, { "code": null, "e": 3827, "s": 3823, "text": "CPP" }, { "code": "#include <iostream>using namespace std; template <class T, class U = char> class A {public: T x; U y; A() { cout << \"Constructor Called\" << endl; }}; int main(){ A<char> a; // This will call A<char, char> return 0;}", "e": 4060, "s": 3827, "text": null }, { "code": null, "e": 4080, "s": 4060, "text": "Constructor Called\n" }, { "code": null, "e": 4376, "s": 4080, "text": "What is the difference between function overloading and templates? Both function overloading and templates are examples of polymorphism feature of OOP. Function overloading is used when multiple functions do similar operations, templates are used when multiple functions do identical operations." }, { "code": null, "e": 4564, "s": 4376, "text": "What happens when there is a static member in a template class/function? Each instance of a template contains its own static variable. See Templates and Static variables for more details." }, { "code": null, "e": 4728, "s": 4564, "text": "What is template specialization? Template specialization allows us to have different code for a particular data type. See Template Specialization for more details." }, { "code": null, "e": 5313, "s": 4728, "text": "Can we pass nontype parameters to templates? We can pass non-type arguments to templates. Non-type parameters are mainly used for specifying max or min values or any other constant value for a particular instance of a template. The important thing to note about non-type parameters is, they must be const. The compiler must know the value of non-type parameters at compile time. Because the compiler needs to create functions/classes for a specified non-type value at compile time. In below program, if we replace 10000 or 25 with a variable, we get a compiler error. Please see this." }, { "code": null, "e": 5339, "s": 5313, "text": "Below is a C++ program. " }, { "code": null, "e": 5343, "s": 5339, "text": "CPP" }, { "code": "// A C++ program to demonstrate working of non-type// parameters to templates in C++.#include <iostream>using namespace std; template <class T, int max> int arrMin(T arr[], int n){ int m = max; for (int i = 0; i < n; i++) if (arr[i] < m) m = arr[i]; return m;} int main(){ int arr1[] = { 10, 20, 15, 12 }; int n1 = sizeof(arr1) / sizeof(arr1[0]); char arr2[] = { 1, 2, 3 }; int n2 = sizeof(arr2) / sizeof(arr2[0]); // Second template parameter to arrMin must be a // constant cout << arrMin<int, 10000>(arr1, n1) << endl; cout << arrMin<char, 256>(arr2, n2); return 0;}", "e": 5975, "s": 5343, "text": null }, { "code": null, "e": 5980, "s": 5975, "text": "10\n1" }, { "code": null, "e": 6104, "s": 5980, "text": "Here is an example of C++ program to show different data types using constructor and template. We will perform few actions " }, { "code": null, "e": 6171, "s": 6104, "text": "passing character value by creating an objects in main() function." }, { "code": null, "e": 6236, "s": 6171, "text": "passing integer value by creating an objects in main() function." }, { "code": null, "e": 6299, "s": 6236, "text": "passing float value by creating an objects in main() function." }, { "code": null, "e": 6303, "s": 6299, "text": "C++" }, { "code": "// #include <conio.h>#include <iostream>using namespace std; // defining a class templatetemplate <class T> class info {public: info(T A) // constructor of type template { cout << \"\\n\" << \"A = \" << A << \" size of data in bytes:\" << sizeof(A); } // end of info()}; // end of class // Main Functionint main(){ // clrscr(); // passing character value by creating an objects info<char> p('x'); // passing integer value by creating an object info<int> q(22); // passing float value by creating an object info<float> r(2.25); return 0;} // end of Main Function", "e": 6932, "s": 6303, "text": null }, { "code": null, "e": 7026, "s": 6932, "text": "A = x size of data in bytes:1\nA = 22 size of data in bytes:4\nA = 2.25 size of data in bytes:4" }, { "code": null, "e": 7089, "s": 7026, "text": "What is template metaprogramming? See Template Metaprogramming" }, { "code": null, "e": 7195, "s": 7089, "text": "You may also like to take a quiz on templates.Java also supports these features. Java calls it generics ." }, { "code": null, "e": 7320, "s": 7195, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 7328, "s": 7320, "text": "anu7699" }, { "code": null, "e": 7338, "s": 7328, "text": "stathpaul" }, { "code": null, "e": 7352, "s": 7338, "text": "biplab_prasad" }, { "code": null, "e": 7361, "s": 7352, "text": "hakukiro" }, { "code": null, "e": 7402, "s": 7361, "text": "dey0btpch57lmvgz5mqhpaiqn337p09fd8yq1lw4" }, { "code": null, "e": 7416, "s": 7402, "text": "RishabhPrabhu" }, { "code": null, "e": 7429, "s": 7416, "text": "cpp-template" }, { "code": null, "e": 7433, "s": 7429, "text": "C++" }, { "code": null, "e": 7437, "s": 7433, "text": "CPP" }, { "code": null, "e": 7535, "s": 7437, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7553, "s": 7535, "text": "Vector in C++ STL" }, { "code": null, "e": 7596, "s": 7553, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 7642, "s": 7596, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 7665, "s": 7642, "text": "std::sort() in C++ STL" }, { "code": null, "e": 7692, "s": 7665, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 7735, "s": 7692, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 7769, "s": 7735, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 7794, "s": 7769, "text": "unordered_map in C++ STL" }, { "code": null, "e": 7813, "s": 7794, "text": "Inheritance in C++" } ]
Extract specific column from a DataFrame using column name in R
15 Feb, 2022 In this article, we are going to see how to extract a specific column from a dataframe using the column name in R Programming Language. In the data.frame() we have to pass dataframe_name followed by $ symbol followed by column name. The reason to pass dataframe_name$ column name to data.frame() is, after extracting the data from column we have to show the data in the rows and column format. So we pass dataframe_name $ column name to the data.frame(). Syntax of $ operator data.frame ( dataframe_name $ column_name ) Example 1: In this example, we just created a data frame using data.frame() function and passed 3 vectors which holds some values. In the second step, we used $ operator along with the data frame name inside the data.frame(). The reason behind passing dataframe_name $ column name into data.frame() is to show the extracted column in data frame format. R # creating a data frame with number ,# string and binary as column names .df1=data.frame(number = c(1:3), string = c("One" , "Two" , "Three") , Binary = c(001,010,011)) # passing column name of df1 using # $ symbol to data.frame() function.data.frame(df1$number) Output: Example 2: In this example, we have created 2 vectors named ranking and name with some data inside. Passed the 2 vectors into the data.frame() function as parameters and assigned it to a variable called df1, finally using $ operator we are extracting the name column and passing it to data.frame() function for showing in dataframe format. R # creating a vector with some valuesranking = c(1 : 3) # creating another vector with some # valuesname = c("Mani sharma" , "Devi sri prasad" , "Thaman SS") # passing the vectors to data.frame() # as parameters .df1 = data.frame(ranking,name) # Extracting name column from df1 using # $ symboldata.frame(df1$name) Output: Example 3: In this example, we have created 2 vectors named ranking and name with some data inside. Passing the 2 vectors into the data.frame() function as parameters. Assigned the data.frame() function into a variable named df1. Using $ operator along with dataframe_name to extract column name and passed it into data.frame() function to show the extracted column name in data frame format. R # creating a vector with some valuesranking = c(1 : 3) # creating another vector with some dataname = c("Trivikram" , "RajaMouli SS" , "Puri Jagannadh") # passing the vectors to the data.frame()# functiondf1 = data.frame(ranking,name) # Extracting name column from df1# using $ symbol and passing it to data.frame()# as parameter .data.frame(df1$name) Output: Multiple column extraction can be done through indexing. Syntax : variable_name = dataframe_name [ row(s) , column(s) ] Example 1: a=df[ c(1,2) , c(1,2) ] Explanation : if we want to extract multiple rows and columns we can use c() with row names and column names as parameters. Here in the above example we have extracted 1,2 rows and 1,2 columns data from a data frame and stored into a variable. Example 2 : b=df [ c(1,2) , c(“id”,”name”) ] Explanation : If we want to specify column names we can give column names as parameters in c() function . In the above example we have extracted 1,2 rows of ID and name columns. Example 1: First, we are creating a data frame with some data. Using indexing we are extracting multiple columns. In the above example, we have extracted all rows and 2 columns named number and string from df1 and storing into another variable. Finally, printing the df2. R # creating a data frame with number# string and binary as column names .df1=data.frame(number=c(1:3), string=c("One" , "Two" , "Three") , Binary=c(001,010,011)) # extracting 1 to 3 rows of string # and binary columns from df1df2 = df1[c(1:3),c("string","Binary")] # And storing the extracted data into df2print(df2) # printing the df2 Output: Example 2: First, we are creating a data frame with some data. Using indexing we are extracting multiple columns. In the above example, we have extracted 1,2 rows and 2 columns named ranking and name from df1 and storing them into another variable. Finally, printing the df2. R # creating a vector with some valuesranking = c(1 : 3) # creating another vector with# some dataname = c("Trivikram" , "RajaMouli SS" , "Puri Jagannadh") no_of_movies = c(15, 10, 12) # passing the vectors to the data.frame()# functiondf1 = data.frame(ranking,name,no_of_movies) # extracting 1,2 rows of ranking and name# columns from df1df2 = df1[1:2 , c("ranking","name")] # And storing the data into a variable df2print(df2) Output: Example 3: First we are creating a data frame with some data. Using indexing we are extracting multiple columns. In the above example, we have extracted all rows and 2 columns named name and no_of_movies from df1 and storing into another variable. Finally, printing the df2. R # creating a vector with some valuesranking = c(1 : 3) # creating another vector with some valuesname = c("Mani sharma" , "Devi sri prasad" , "Thaman SS") no_of_movies=c(20, 30, 40) # passing the vectors to data.frame()# as parameters .df1 = data.frame(ranking,name,no_of_movies) # Extracting all rows of name and # no_of_movies columns from df1df2 = df1[, c("name", "no_of_movies")] # And storing into a variable called df2print(df2) Output: surinderdawra388 Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Feb, 2022" }, { "code": null, "e": 164, "s": 28, "text": "In this article, we are going to see how to extract a specific column from a dataframe using the column name in R Programming Language." }, { "code": null, "e": 483, "s": 164, "text": "In the data.frame() we have to pass dataframe_name followed by $ symbol followed by column name. The reason to pass dataframe_name$ column name to data.frame() is, after extracting the data from column we have to show the data in the rows and column format. So we pass dataframe_name $ column name to the data.frame()." }, { "code": null, "e": 504, "s": 483, "text": "Syntax of $ operator" }, { "code": null, "e": 548, "s": 504, "text": "data.frame ( dataframe_name $ column_name )" }, { "code": null, "e": 901, "s": 548, "text": "Example 1: In this example, we just created a data frame using data.frame() function and passed 3 vectors which holds some values. In the second step, we used $ operator along with the data frame name inside the data.frame(). The reason behind passing dataframe_name $ column name into data.frame() is to show the extracted column in data frame format." }, { "code": null, "e": 903, "s": 901, "text": "R" }, { "code": "# creating a data frame with number ,# string and binary as column names .df1=data.frame(number = c(1:3), string = c(\"One\" , \"Two\" , \"Three\") , Binary = c(001,010,011)) # passing column name of df1 using # $ symbol to data.frame() function.data.frame(df1$number) ", "e": 1197, "s": 903, "text": null }, { "code": null, "e": 1205, "s": 1197, "text": "Output:" }, { "code": null, "e": 1545, "s": 1205, "text": "Example 2: In this example, we have created 2 vectors named ranking and name with some data inside. Passed the 2 vectors into the data.frame() function as parameters and assigned it to a variable called df1, finally using $ operator we are extracting the name column and passing it to data.frame() function for showing in dataframe format." }, { "code": null, "e": 1547, "s": 1545, "text": "R" }, { "code": "# creating a vector with some valuesranking = c(1 : 3) # creating another vector with some # valuesname = c(\"Mani sharma\" , \"Devi sri prasad\" , \"Thaman SS\") # passing the vectors to data.frame() # as parameters .df1 = data.frame(ranking,name) # Extracting name column from df1 using # $ symboldata.frame(df1$name) ", "e": 1884, "s": 1547, "text": null }, { "code": null, "e": 1892, "s": 1884, "text": "Output:" }, { "code": null, "e": 2285, "s": 1892, "text": "Example 3: In this example, we have created 2 vectors named ranking and name with some data inside. Passing the 2 vectors into the data.frame() function as parameters. Assigned the data.frame() function into a variable named df1. Using $ operator along with dataframe_name to extract column name and passed it into data.frame() function to show the extracted column name in data frame format." }, { "code": null, "e": 2287, "s": 2285, "text": "R" }, { "code": "# creating a vector with some valuesranking = c(1 : 3) # creating another vector with some dataname = c(\"Trivikram\" , \"RajaMouli SS\" , \"Puri Jagannadh\") # passing the vectors to the data.frame()# functiondf1 = data.frame(ranking,name) # Extracting name column from df1# using $ symbol and passing it to data.frame()# as parameter .data.frame(df1$name) ", "e": 2646, "s": 2287, "text": null }, { "code": null, "e": 2654, "s": 2646, "text": "Output:" }, { "code": null, "e": 2711, "s": 2654, "text": "Multiple column extraction can be done through indexing." }, { "code": null, "e": 2775, "s": 2711, "text": " Syntax : variable_name = dataframe_name [ row(s) , column(s) ]" }, { "code": null, "e": 2810, "s": 2775, "text": "Example 1: a=df[ c(1,2) , c(1,2) ]" }, { "code": null, "e": 3054, "s": 2810, "text": "Explanation : if we want to extract multiple rows and columns we can use c() with row names and column names as parameters. Here in the above example we have extracted 1,2 rows and 1,2 columns data from a data frame and stored into a variable." }, { "code": null, "e": 3100, "s": 3054, "text": "Example 2 : b=df [ c(1,2) , c(“id”,”name”) ] " }, { "code": null, "e": 3278, "s": 3100, "text": "Explanation : If we want to specify column names we can give column names as parameters in c() function . In the above example we have extracted 1,2 rows of ID and name columns." }, { "code": null, "e": 3550, "s": 3278, "text": "Example 1: First, we are creating a data frame with some data. Using indexing we are extracting multiple columns. In the above example, we have extracted all rows and 2 columns named number and string from df1 and storing into another variable. Finally, printing the df2." }, { "code": null, "e": 3552, "s": 3550, "text": "R" }, { "code": "# creating a data frame with number# string and binary as column names .df1=data.frame(number=c(1:3), string=c(\"One\" , \"Two\" , \"Three\") , Binary=c(001,010,011)) # extracting 1 to 3 rows of string # and binary columns from df1df2 = df1[c(1:3),c(\"string\",\"Binary\")] # And storing the extracted data into df2print(df2) # printing the df2", "e": 3917, "s": 3552, "text": null }, { "code": null, "e": 3925, "s": 3917, "text": "Output:" }, { "code": null, "e": 4201, "s": 3925, "text": "Example 2: First, we are creating a data frame with some data. Using indexing we are extracting multiple columns. In the above example, we have extracted 1,2 rows and 2 columns named ranking and name from df1 and storing them into another variable. Finally, printing the df2." }, { "code": null, "e": 4203, "s": 4201, "text": "R" }, { "code": "# creating a vector with some valuesranking = c(1 : 3) # creating another vector with# some dataname = c(\"Trivikram\" , \"RajaMouli SS\" , \"Puri Jagannadh\") no_of_movies = c(15, 10, 12) # passing the vectors to the data.frame()# functiondf1 = data.frame(ranking,name,no_of_movies) # extracting 1,2 rows of ranking and name# columns from df1df2 = df1[1:2 , c(\"ranking\",\"name\")] # And storing the data into a variable df2print(df2)", "e": 4637, "s": 4203, "text": null }, { "code": null, "e": 4645, "s": 4637, "text": "Output:" }, { "code": null, "e": 4920, "s": 4645, "text": "Example 3: First we are creating a data frame with some data. Using indexing we are extracting multiple columns. In the above example, we have extracted all rows and 2 columns named name and no_of_movies from df1 and storing into another variable. Finally, printing the df2." }, { "code": null, "e": 4922, "s": 4920, "text": "R" }, { "code": "# creating a vector with some valuesranking = c(1 : 3) # creating another vector with some valuesname = c(\"Mani sharma\" , \"Devi sri prasad\" , \"Thaman SS\") no_of_movies=c(20, 30, 40) # passing the vectors to data.frame()# as parameters .df1 = data.frame(ranking,name,no_of_movies) # Extracting all rows of name and # no_of_movies columns from df1df2 = df1[, c(\"name\", \"no_of_movies\")] # And storing into a variable called df2print(df2) ", "e": 5363, "s": 4922, "text": null }, { "code": null, "e": 5371, "s": 5363, "text": "Output:" }, { "code": null, "e": 5388, "s": 5371, "text": "surinderdawra388" }, { "code": null, "e": 5395, "s": 5388, "text": "Picked" }, { "code": null, "e": 5416, "s": 5395, "text": "R DataFrame-Programs" }, { "code": null, "e": 5428, "s": 5416, "text": "R-DataFrame" }, { "code": null, "e": 5439, "s": 5428, "text": "R Language" }, { "code": null, "e": 5450, "s": 5439, "text": "R Programs" } ]
Shuffle a given array using Fisher–Yates shuffle Algorithm
27 Jun, 2022 Given an array, write a program to generate a random permutation of array elements. This question is also asked as “shuffle a deck of cards” or “randomize a given array”. Here shuffle means that every permutation of array element should be equally likely. Let the given array be arr[]. A simple solution is to create an auxiliary array temp[] which is initially a copy of arr[]. Randomly select an element from temp[], copy the randomly selected element to arr[0], and remove the selected element from temp[]. Repeat the same process n times and keep copying elements to arr[1], arr[2], ... . The time complexity of this solution will be O(n^2). Fisher–Yates shuffle Algorithm works in O(n) time complexity. The assumption here is, we are given a function rand() that generates a random number in O(1) time. The idea is to start from the last element and swap it with a randomly selected element from the whole array (including the last). Now consider the array from 0 to n-2 (size reduced by 1), and repeat the process till we hit the first element. Following is the detailed algorithm that is as follows: To shuffle an array a of n elements (indices 0..n-1): for i from n - 1 downto 1 do j = random integer with 0 <= j <= i exchange a[j] and a[i] Flowchart: flowchart Following is an implementation of this algorithm. C++ C Java Python3 C# PHP Javascript // C++ Program to shuffle a given array#include<bits/stdc++.h>#include <stdlib.h>#include <time.h>using namespace std; // A utility function to swap to integersvoid swap (int *a, int *b){ int temp = *a; *a = *b; *b = temp;} // A utility function to print an arrayvoid printArray (int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << "\n";} // A function to generate a random// permutation of arr[]void randomize (int arr[], int n){ // Use a different seed value so that // we don't get same result each time // we run this program srand (time(NULL)); // Start from the last element and swap // one by one. We don't need to run for // the first element that's why i > 0 for (int i = n - 1; i > 0; i--) { // Pick a random index from 0 to i int j = rand() % (i + 1); // Swap arr[i] with the element // at random index swap(&arr[i], &arr[j]); }} // Driver Codeint main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; int n = sizeof(arr) / sizeof(arr[0]); randomize (arr, n); printArray(arr, n); return 0;} // This code is contributed by// rathbhupendra // C Program to shuffle a given array #include <stdio.h>#include <stdlib.h>#include <time.h> // A utility function to swap to integersvoid swap (int *a, int *b){ int temp = *a; *a = *b; *b = temp;} // A utility function to print an arrayvoid printArray (int arr[], int n){ for (int i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n");} // A function to generate a random permutation of arr[]void randomize ( int arr[], int n ){ // Use a different seed value so that we don't get same // result each time we run this program srand ( time(NULL) ); // Start from the last element and swap one by one. We don't // need to run for the first element that's why i > 0 for (int i = n-1; i > 0; i--) { // Pick a random index from 0 to i int j = rand() % (i+1); // Swap arr[i] with the element at random index swap(&arr[i], &arr[j]); }} // Driver program to test above function.int main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; int n = sizeof(arr)/ sizeof(arr[0]); randomize (arr, n); printArray(arr, n); return 0;} // Java Program to shuffle a given arrayimport java.util.Random;import java.util.Arrays;public class ShuffleRand{ // A Function to generate a random permutation of arr[] static void randomize( int arr[], int n) { // Creating a object for Random class Random r = new Random(); // Start from the last element and swap one by one. We don't // need to run for the first element that's why i > 0 for (int i = n-1; i > 0; i--) { // Pick a random index from 0 to i int j = r.nextInt(i+1); // Swap arr[i] with the element at random index int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Prints the random array System.out.println(Arrays.toString(arr)); } // Driver Program to test above function public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6, 7, 8}; int n = arr.length; randomize (arr, n); }}// This code is contributed by Sumit Ghosh # Python Program to shuffle a given arrayfrom random import randint # A function to generate a random permutation of arr[]def randomize (arr, n): # Start from the last element and swap one by one. We don't # need to run for the first element that's why i > 0 for i in range(n-1,0,-1): # Pick a random index from 0 to i j = randint(0,i+1) # Swap arr[i] with the element at random index arr[i],arr[j] = arr[j],arr[i] return arr # Driver program to test above function.arr = [1, 2, 3, 4, 5, 6, 7, 8]n = len(arr)print(randomize(arr, n)) # This code is contributed by Pratik Chhajer // C# Code for Number of digits// in the product of two numbersusing System; class GFG{// A Function to generate a// random permutation of arr[] static void randomize(int []arr, int n) { // Creating a object // for Random class Random r = new Random(); // Start from the last element and // swap one by one. We don't need to // run for the first element // that's why i > 0 for (int i = n - 1; i > 0; i--) { // Pick a random index // from 0 to i int j = r.Next(0, i+1); // Swap arr[i] with the // element at random index int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Prints the random array for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); } // Driver Codestatic void Main(){ int[] arr = {1, 2, 3, 4, 5, 6, 7, 8}; int n = arr.Length; randomize (arr, n);}} // This code is contributed by Sam007 <?php// PHP Program to shuffle// a given array // A function to generate// a random permutation of arr[]function randomize ($arr, $n){ // Start from the last element // and swap one by one. We // don't need to run for the // first element that's why i > 0 for($i = $n - 1; $i >= 0; $i--) { // Pick a random index // from 0 to i $j = rand(0, $i+1); // Swap arr[i] with the // element at random index $tmp = $arr[$i]; $arr[$i] = $arr[$j]; $arr[$j] = $tmp; } for($i = 0; $i < $n; $i++) echo $arr[$i]." ";} // Driver Code$arr = array(1, 2, 3, 4, 5, 6, 7, 8);$n = count($arr);randomize($arr, $n); // This code is contributed by mits?> <script>// JavaScript Program to shuffle a given array // A function to print an arraylet printArray = (arr, n)=>{ ans = ''; for (let i = 0; i < n; i++) { ans += arr[i] + " "; } console.log(ans);} // A function to generate a random// permutation of arrlet randomize = (arr, n) =>{ // Start from the last element and swap // one by one. We don't need to run for // the first element that's why i > 0 for (let i = n - 1; i > 0; i--) { // Pick a random index from 0 to i inclusive let j = Math.floor(Math.random() * (i + 1)); // Swap arr[i] with the element // at random index [arr[i], arr[j]] = [arr[j], arr[i]]; }} // Driver Codelet arr = [1, 2, 3, 4, 5, 6, 7, 8];let n = arr.length;randomize (arr, n);printArray(arr, n); // This code is contributed by rohitsingh07052.</script> Output : 7 8 4 6 3 1 2 5 The above function assumes that rand() generates a random number. Time Complexity: O(n), assuming that the function rand() takes O(1) time., Auxiliary Space: O(1) How does this work? The probability that ith element (including the last one) goes to the last position is 1/n, because we randomly pick an element in the first iteration.The probability that ith element goes to the second last position can be proved to be 1/n by dividing it into two cases. Case 1: i = n-1 (index of last element): The probability of last element going to second last position is = (probability that last element doesn’t stay at its original position) x (probability that the index picked in previous step is picked again so that the last element is swapped) So the probability = ((n-1)/n) x (1/(n-1)) = 1/n Case 2: 0 < i < n-1 (index of non-last): The probability of ith element going to second position = (probability that ith element is not picked in previous iteration) x (probability that ith element is picked in this iteration) So the probability = ((n-1)/n) x (1/(n-1)) = 1/nWe can easily generalize above proof for any other position. Shuffle a given array | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersShuffle a given array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:55•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=LP7YQdT5eps" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> https://www.youtube.com/playlist?list=PLqM7alHXFySEQDk2MDfbwEdjd2svVJH9p Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. Sam007 Mithun Kumar _Uchiha_Itachi rathbhupendra rohitsingh07052 deadchicken subhammahato348 amartyaghoshgfg jivendrasah guptavivek0503 Mathematical Randomized Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Jun, 2022" }, { "code": null, "e": 311, "s": 54, "text": "Given an array, write a program to generate a random permutation of array elements. This question is also asked as “shuffle a deck of cards” or “randomize a given array”. Here shuffle means that every permutation of array element should be equally likely. " }, { "code": null, "e": 701, "s": 311, "text": "Let the given array be arr[]. A simple solution is to create an auxiliary array temp[] which is initially a copy of arr[]. Randomly select an element from temp[], copy the randomly selected element to arr[0], and remove the selected element from temp[]. Repeat the same process n times and keep copying elements to arr[1], arr[2], ... . The time complexity of this solution will be O(n^2)." }, { "code": null, "e": 1107, "s": 701, "text": "Fisher–Yates shuffle Algorithm works in O(n) time complexity. The assumption here is, we are given a function rand() that generates a random number in O(1) time. The idea is to start from the last element and swap it with a randomly selected element from the whole array (including the last). Now consider the array from 0 to n-2 (size reduced by 1), and repeat the process till we hit the first element. " }, { "code": null, "e": 1165, "s": 1107, "text": "Following is the detailed algorithm that is as follows: " }, { "code": null, "e": 1323, "s": 1165, "text": "To shuffle an array a of n elements (indices 0..n-1):\n for i from n - 1 downto 1 do\n j = random integer with 0 <= j <= i\n exchange a[j] and a[i]" }, { "code": null, "e": 1334, "s": 1323, "text": "Flowchart:" }, { "code": null, "e": 1344, "s": 1334, "text": "flowchart" }, { "code": null, "e": 1394, "s": 1344, "text": "Following is an implementation of this algorithm." }, { "code": null, "e": 1398, "s": 1394, "text": "C++" }, { "code": null, "e": 1400, "s": 1398, "text": "C" }, { "code": null, "e": 1405, "s": 1400, "text": "Java" }, { "code": null, "e": 1413, "s": 1405, "text": "Python3" }, { "code": null, "e": 1416, "s": 1413, "text": "C#" }, { "code": null, "e": 1420, "s": 1416, "text": "PHP" }, { "code": null, "e": 1431, "s": 1420, "text": "Javascript" }, { "code": "// C++ Program to shuffle a given array#include<bits/stdc++.h>#include <stdlib.h>#include <time.h>using namespace std; // A utility function to swap to integersvoid swap (int *a, int *b){ int temp = *a; *a = *b; *b = temp;} // A utility function to print an arrayvoid printArray (int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \"; cout << \"\\n\";} // A function to generate a random// permutation of arr[]void randomize (int arr[], int n){ // Use a different seed value so that // we don't get same result each time // we run this program srand (time(NULL)); // Start from the last element and swap // one by one. We don't need to run for // the first element that's why i > 0 for (int i = n - 1; i > 0; i--) { // Pick a random index from 0 to i int j = rand() % (i + 1); // Swap arr[i] with the element // at random index swap(&arr[i], &arr[j]); }} // Driver Codeint main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; int n = sizeof(arr) / sizeof(arr[0]); randomize (arr, n); printArray(arr, n); return 0;} // This code is contributed by// rathbhupendra", "e": 2603, "s": 1431, "text": null }, { "code": "// C Program to shuffle a given array #include <stdio.h>#include <stdlib.h>#include <time.h> // A utility function to swap to integersvoid swap (int *a, int *b){ int temp = *a; *a = *b; *b = temp;} // A utility function to print an arrayvoid printArray (int arr[], int n){ for (int i = 0; i < n; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} // A function to generate a random permutation of arr[]void randomize ( int arr[], int n ){ // Use a different seed value so that we don't get same // result each time we run this program srand ( time(NULL) ); // Start from the last element and swap one by one. We don't // need to run for the first element that's why i > 0 for (int i = n-1; i > 0; i--) { // Pick a random index from 0 to i int j = rand() % (i+1); // Swap arr[i] with the element at random index swap(&arr[i], &arr[j]); }} // Driver program to test above function.int main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; int n = sizeof(arr)/ sizeof(arr[0]); randomize (arr, n); printArray(arr, n); return 0;}", "e": 3704, "s": 2603, "text": null }, { "code": "// Java Program to shuffle a given arrayimport java.util.Random;import java.util.Arrays;public class ShuffleRand{ // A Function to generate a random permutation of arr[] static void randomize( int arr[], int n) { // Creating a object for Random class Random r = new Random(); // Start from the last element and swap one by one. We don't // need to run for the first element that's why i > 0 for (int i = n-1; i > 0; i--) { // Pick a random index from 0 to i int j = r.nextInt(i+1); // Swap arr[i] with the element at random index int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Prints the random array System.out.println(Arrays.toString(arr)); } // Driver Program to test above function public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6, 7, 8}; int n = arr.length; randomize (arr, n); }}// This code is contributed by Sumit Ghosh", "e": 4782, "s": 3704, "text": null }, { "code": "# Python Program to shuffle a given arrayfrom random import randint # A function to generate a random permutation of arr[]def randomize (arr, n): # Start from the last element and swap one by one. We don't # need to run for the first element that's why i > 0 for i in range(n-1,0,-1): # Pick a random index from 0 to i j = randint(0,i+1) # Swap arr[i] with the element at random index arr[i],arr[j] = arr[j],arr[i] return arr # Driver program to test above function.arr = [1, 2, 3, 4, 5, 6, 7, 8]n = len(arr)print(randomize(arr, n)) # This code is contributed by Pratik Chhajer", "e": 5402, "s": 4782, "text": null }, { "code": "// C# Code for Number of digits// in the product of two numbersusing System; class GFG{// A Function to generate a// random permutation of arr[] static void randomize(int []arr, int n) { // Creating a object // for Random class Random r = new Random(); // Start from the last element and // swap one by one. We don't need to // run for the first element // that's why i > 0 for (int i = n - 1; i > 0; i--) { // Pick a random index // from 0 to i int j = r.Next(0, i+1); // Swap arr[i] with the // element at random index int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Prints the random array for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); } // Driver Codestatic void Main(){ int[] arr = {1, 2, 3, 4, 5, 6, 7, 8}; int n = arr.Length; randomize (arr, n);}} // This code is contributed by Sam007", "e": 6471, "s": 5402, "text": null }, { "code": "<?php// PHP Program to shuffle// a given array // A function to generate// a random permutation of arr[]function randomize ($arr, $n){ // Start from the last element // and swap one by one. We // don't need to run for the // first element that's why i > 0 for($i = $n - 1; $i >= 0; $i--) { // Pick a random index // from 0 to i $j = rand(0, $i+1); // Swap arr[i] with the // element at random index $tmp = $arr[$i]; $arr[$i] = $arr[$j]; $arr[$j] = $tmp; } for($i = 0; $i < $n; $i++) echo $arr[$i].\" \";} // Driver Code$arr = array(1, 2, 3, 4, 5, 6, 7, 8);$n = count($arr);randomize($arr, $n); // This code is contributed by mits?>", "e": 7197, "s": 6471, "text": null }, { "code": "<script>// JavaScript Program to shuffle a given array // A function to print an arraylet printArray = (arr, n)=>{ ans = ''; for (let i = 0; i < n; i++) { ans += arr[i] + \" \"; } console.log(ans);} // A function to generate a random// permutation of arrlet randomize = (arr, n) =>{ // Start from the last element and swap // one by one. We don't need to run for // the first element that's why i > 0 for (let i = n - 1; i > 0; i--) { // Pick a random index from 0 to i inclusive let j = Math.floor(Math.random() * (i + 1)); // Swap arr[i] with the element // at random index [arr[i], arr[j]] = [arr[j], arr[i]]; }} // Driver Codelet arr = [1, 2, 3, 4, 5, 6, 7, 8];let n = arr.length;randomize (arr, n);printArray(arr, n); // This code is contributed by rohitsingh07052.</script>", "e": 8057, "s": 7197, "text": null }, { "code": null, "e": 8068, "s": 8057, "text": "Output : " }, { "code": null, "e": 8084, "s": 8068, "text": "7 8 4 6 3 1 2 5" }, { "code": null, "e": 8151, "s": 8084, "text": "The above function assumes that rand() generates a random number. " }, { "code": null, "e": 8248, "s": 8151, "text": "Time Complexity: O(n), assuming that the function rand() takes O(1) time., Auxiliary Space: O(1)" }, { "code": null, "e": 8269, "s": 8248, "text": "How does this work? " }, { "code": null, "e": 9211, "s": 8269, "text": "The probability that ith element (including the last one) goes to the last position is 1/n, because we randomly pick an element in the first iteration.The probability that ith element goes to the second last position can be proved to be 1/n by dividing it into two cases. Case 1: i = n-1 (index of last element): The probability of last element going to second last position is = (probability that last element doesn’t stay at its original position) x (probability that the index picked in previous step is picked again so that the last element is swapped) So the probability = ((n-1)/n) x (1/(n-1)) = 1/n Case 2: 0 < i < n-1 (index of non-last): The probability of ith element going to second position = (probability that ith element is not picked in previous iteration) x (probability that ith element is picked in this iteration) So the probability = ((n-1)/n) x (1/(n-1)) = 1/nWe can easily generalize above proof for any other position." }, { "code": null, "e": 10071, "s": 9211, "text": "Shuffle a given array | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersShuffle a given array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:55•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=LP7YQdT5eps\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 10144, "s": 10071, "text": "https://www.youtube.com/playlist?list=PLqM7alHXFySEQDk2MDfbwEdjd2svVJH9p" }, { "code": null, "e": 10272, "s": 10144, "text": "Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above." }, { "code": null, "e": 10279, "s": 10272, "text": "Sam007" }, { "code": null, "e": 10292, "s": 10279, "text": "Mithun Kumar" }, { "code": null, "e": 10307, "s": 10292, "text": "_Uchiha_Itachi" }, { "code": null, "e": 10321, "s": 10307, "text": "rathbhupendra" }, { "code": null, "e": 10337, "s": 10321, "text": "rohitsingh07052" }, { "code": null, "e": 10349, "s": 10337, "text": "deadchicken" }, { "code": null, "e": 10365, "s": 10349, "text": "subhammahato348" }, { "code": null, "e": 10381, "s": 10365, "text": "amartyaghoshgfg" }, { "code": null, "e": 10393, "s": 10381, "text": "jivendrasah" }, { "code": null, "e": 10408, "s": 10393, "text": "guptavivek0503" }, { "code": null, "e": 10421, "s": 10408, "text": "Mathematical" }, { "code": null, "e": 10432, "s": 10421, "text": "Randomized" }, { "code": null, "e": 10445, "s": 10432, "text": "Mathematical" } ]
VB.Net - While... End While Loop
It executes a series of statements as long as a given condition is True. The syntax for this loop construct is − While condition [ statements ] [ Continue While ] [ statements ] [ Exit While ] [ statements ] End While Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is logical true. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop. Here, key point of the While loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. Module loops Sub Main() Dim a As Integer = 10 ' while loop execution ' While a < 20 Console.WriteLine("value of a: {0}", a) a = a + 1 End While Console.ReadLine() End Sub End Module When the above code is compiled and executed, it produces the following result − value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19
[ { "code": null, "e": 2507, "s": 2434, "text": "It executes a series of statements as long as a given condition is True." }, { "code": null, "e": 2547, "s": 2507, "text": "The syntax for this loop construct is −" }, { "code": null, "e": 2668, "s": 2547, "text": "While condition\n [ statements ]\n [ Continue While ]\n [ statements ]\n [ Exit While ]\n [ statements ]\nEnd While\n" }, { "code": null, "e": 2849, "s": 2668, "text": "Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is logical true. The loop iterates while the condition is true." }, { "code": null, "e": 2950, "s": 2849, "text": "When the condition becomes false, program control passes to the line immediately following the loop." }, { "code": null, "e": 3168, "s": 2950, "text": "Here, key point of the While loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed." }, { "code": null, "e": 3411, "s": 3168, "text": "Module loops\n Sub Main()\n Dim a As Integer = 10\n ' while loop execution '\n \n While a < 20\n Console.WriteLine(\"value of a: {0}\", a)\n a = a + 1\n End While\n Console.ReadLine()\n End Sub\nEnd Module" }, { "code": null, "e": 3492, "s": 3411, "text": "When the above code is compiled and executed, it produces the following result −" } ]
Spring Boot | How to publish JSON messages on Apache Kafka
21 Jun, 2020 Apache Kafka is a publish-subscribe messaging system. A messaging queue lets you send messages between processes, applications, and servers. In this article, we will see how to send JSON messages to Apache Kafka in a spring boot application. In order to learn how to create a spring boot project, refer to this article. The full-form of JSON is JavaScript Object Notation. JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. Though it is derived from a subset of JavaScript, yet it is Language independent. It is a complete language-independent text format. The following steps can be followed in order to publish JSON messages to Apache Kafka: Go to spring initializr and create a starter project with following dependencies:Spring WebSpring for Apache KafkaOpen the project in an IDE and sync the dependencies. In this article, we would be creating a student model where we would be posting the student details. Therefore, create a model class Student. Add data members and create constructor and create getters and setters. The following is the implementation of the student class:// Java program to implement a// student class // Creating a student classpublic class Student { // Data members of the // student class int id; String firstName; String lastName; // Constructor of the student // class public Student(int id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } // Implementing the getters // and setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; }}Now, create a new class Controller with the annotation @RestController. Create a GET API and initialize KafkaTemplate with parameter as string and model class object. The following is the implementation of the controller:// Java program to implement a// controller @RestController@RequestMapping("gfg")public class UserResource { @Autowired private KafkaTemplate<String, Student> kafkaTemplate; private static final String TOPIC = "StudentExample"; @GetMapping("/publish/{id}/" + "{firstName}/{lastName}") public String post( @PathVariable("id") final int id, @PathVariable("firstName") final String firstName, @PathVariable("lastName") final String lastName) { kafkaTemplate.send( TOPIC, new Student( id, firstName, lastName)); return "Published successfully"; }}Create a class StudentConfig with the annotation @Configuration. In this class we will serialize the object of the model class.// Java program to serialize the// object of the model class @Configurationpublic class StudentConfig { @Bean public ProducerFactory<String, Student> producerFactory() { // Create a map of a string // and object Map<String, Object> config = new HashMap<>(); config.put( ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092"); config.put( ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); config.put( ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); return new DefaultKafkaProducerFactory<>(config); } @Bean public KafkaTemplate<String, Student> kafkaTemplate() { return new KafkaTemplate<>( producerFactory()); }}Now, start zookeeper and Kafka server. We need to create a new topic with the name StudentExample. To do so, open a new command prompt window and change directory to the Kafka folder.Now, create a new topic using the command given below:For Mac and Linux: bin/kafka-topics.sh –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic topic_nameFor Windows: .\bin\windows\kafka-topics.bat –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic topic_nameNow to see the messages on the Kafka server in the real-time, use the command below:For Mac and Linux: bin/kafka-console-consumer.sh –bootstrap-server localhost:9092 –topic topic_name –from-beginningFor Windows: .\bin\windows\kafka-console-consumer.bat –bootstrap-server localhost:9092 –topic topic_name –from-beginningRun the application and call the API as:localhost:8080/gfg/publish/{id}/{first name}/{last name}Note: If a different port has been used, then replace the port with 8080. Go to spring initializr and create a starter project with following dependencies:Spring WebSpring for Apache Kafka Spring Web Spring for Apache Kafka Open the project in an IDE and sync the dependencies. In this article, we would be creating a student model where we would be posting the student details. Therefore, create a model class Student. Add data members and create constructor and create getters and setters. The following is the implementation of the student class:// Java program to implement a// student class // Creating a student classpublic class Student { // Data members of the // student class int id; String firstName; String lastName; // Constructor of the student // class public Student(int id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } // Implementing the getters // and setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; }} // Java program to implement a// student class // Creating a student classpublic class Student { // Data members of the // student class int id; String firstName; String lastName; // Constructor of the student // class public Student(int id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } // Implementing the getters // and setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; }} Now, create a new class Controller with the annotation @RestController. Create a GET API and initialize KafkaTemplate with parameter as string and model class object. The following is the implementation of the controller:// Java program to implement a// controller @RestController@RequestMapping("gfg")public class UserResource { @Autowired private KafkaTemplate<String, Student> kafkaTemplate; private static final String TOPIC = "StudentExample"; @GetMapping("/publish/{id}/" + "{firstName}/{lastName}") public String post( @PathVariable("id") final int id, @PathVariable("firstName") final String firstName, @PathVariable("lastName") final String lastName) { kafkaTemplate.send( TOPIC, new Student( id, firstName, lastName)); return "Published successfully"; }} // Java program to implement a// controller @RestController@RequestMapping("gfg")public class UserResource { @Autowired private KafkaTemplate<String, Student> kafkaTemplate; private static final String TOPIC = "StudentExample"; @GetMapping("/publish/{id}/" + "{firstName}/{lastName}") public String post( @PathVariable("id") final int id, @PathVariable("firstName") final String firstName, @PathVariable("lastName") final String lastName) { kafkaTemplate.send( TOPIC, new Student( id, firstName, lastName)); return "Published successfully"; }} Create a class StudentConfig with the annotation @Configuration. In this class we will serialize the object of the model class.// Java program to serialize the// object of the model class @Configurationpublic class StudentConfig { @Bean public ProducerFactory<String, Student> producerFactory() { // Create a map of a string // and object Map<String, Object> config = new HashMap<>(); config.put( ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092"); config.put( ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); config.put( ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); return new DefaultKafkaProducerFactory<>(config); } @Bean public KafkaTemplate<String, Student> kafkaTemplate() { return new KafkaTemplate<>( producerFactory()); }} // Java program to serialize the// object of the model class @Configurationpublic class StudentConfig { @Bean public ProducerFactory<String, Student> producerFactory() { // Create a map of a string // and object Map<String, Object> config = new HashMap<>(); config.put( ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092"); config.put( ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); config.put( ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); return new DefaultKafkaProducerFactory<>(config); } @Bean public KafkaTemplate<String, Student> kafkaTemplate() { return new KafkaTemplate<>( producerFactory()); }} Now, start zookeeper and Kafka server. We need to create a new topic with the name StudentExample. To do so, open a new command prompt window and change directory to the Kafka folder. Now, create a new topic using the command given below:For Mac and Linux: bin/kafka-topics.sh –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic topic_nameFor Windows: .\bin\windows\kafka-topics.bat –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic topic_name For Mac and Linux: bin/kafka-topics.sh –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic topic_name For Windows: .\bin\windows\kafka-topics.bat –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic topic_name Now to see the messages on the Kafka server in the real-time, use the command below:For Mac and Linux: bin/kafka-console-consumer.sh –bootstrap-server localhost:9092 –topic topic_name –from-beginningFor Windows: .\bin\windows\kafka-console-consumer.bat –bootstrap-server localhost:9092 –topic topic_name –from-beginning For Mac and Linux: bin/kafka-console-consumer.sh –bootstrap-server localhost:9092 –topic topic_name –from-beginning For Windows: .\bin\windows\kafka-console-consumer.bat –bootstrap-server localhost:9092 –topic topic_name –from-beginning Run the application and call the API as:localhost:8080/gfg/publish/{id}/{first name}/{last name}Note: If a different port has been used, then replace the port with 8080. localhost:8080/gfg/publish/{id}/{first name}/{last name} Note: If a different port has been used, then replace the port with 8080. Output: Calling the API: Checking the message in real time: Apache java-advanced Java-Spring JSON How To Java Programs 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": "\n21 Jun, 2020" }, { "code": null, "e": 270, "s": 28, "text": "Apache Kafka is a publish-subscribe messaging system. A messaging queue lets you send messages between processes, applications, and servers. In this article, we will see how to send JSON messages to Apache Kafka in a spring boot application." }, { "code": null, "e": 348, "s": 270, "text": "In order to learn how to create a spring boot project, refer to this article." }, { "code": null, "e": 765, "s": 348, "text": "The full-form of JSON is JavaScript Object Notation. JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. Though it is derived from a subset of JavaScript, yet it is Language independent. It is a complete language-independent text format. The following steps can be followed in order to publish JSON messages to Apache Kafka:" }, { "code": null, "e": 4997, "s": 765, "text": "Go to spring initializr and create a starter project with following dependencies:Spring WebSpring for Apache KafkaOpen the project in an IDE and sync the dependencies. In this article, we would be creating a student model where we would be posting the student details. Therefore, create a model class Student. Add data members and create constructor and create getters and setters. The following is the implementation of the student class:// Java program to implement a// student class // Creating a student classpublic class Student { // Data members of the // student class int id; String firstName; String lastName; // Constructor of the student // class public Student(int id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } // Implementing the getters // and setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; }}Now, create a new class Controller with the annotation @RestController. Create a GET API and initialize KafkaTemplate with parameter as string and model class object. The following is the implementation of the controller:// Java program to implement a// controller @RestController@RequestMapping(\"gfg\")public class UserResource { @Autowired private KafkaTemplate<String, Student> kafkaTemplate; private static final String TOPIC = \"StudentExample\"; @GetMapping(\"/publish/{id}/\" + \"{firstName}/{lastName}\") public String post( @PathVariable(\"id\") final int id, @PathVariable(\"firstName\") final String firstName, @PathVariable(\"lastName\") final String lastName) { kafkaTemplate.send( TOPIC, new Student( id, firstName, lastName)); return \"Published successfully\"; }}Create a class StudentConfig with the annotation @Configuration. In this class we will serialize the object of the model class.// Java program to serialize the// object of the model class @Configurationpublic class StudentConfig { @Bean public ProducerFactory<String, Student> producerFactory() { // Create a map of a string // and object Map<String, Object> config = new HashMap<>(); config.put( ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, \"127.0.0.1:9092\"); config.put( ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); config.put( ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); return new DefaultKafkaProducerFactory<>(config); } @Bean public KafkaTemplate<String, Student> kafkaTemplate() { return new KafkaTemplate<>( producerFactory()); }}Now, start zookeeper and Kafka server. We need to create a new topic with the name StudentExample. To do so, open a new command prompt window and change directory to the Kafka folder.Now, create a new topic using the command given below:For Mac and Linux: bin/kafka-topics.sh –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic topic_nameFor Windows: .\\bin\\windows\\kafka-topics.bat –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic topic_nameNow to see the messages on the Kafka server in the real-time, use the command below:For Mac and Linux: bin/kafka-console-consumer.sh –bootstrap-server localhost:9092 –topic topic_name –from-beginningFor Windows: .\\bin\\windows\\kafka-console-consumer.bat –bootstrap-server localhost:9092 –topic topic_name –from-beginningRun the application and call the API as:localhost:8080/gfg/publish/{id}/{first name}/{last name}Note: If a different port has been used, then replace the port with 8080." }, { "code": null, "e": 5112, "s": 4997, "text": "Go to spring initializr and create a starter project with following dependencies:Spring WebSpring for Apache Kafka" }, { "code": null, "e": 5123, "s": 5112, "text": "Spring Web" }, { "code": null, "e": 5147, "s": 5123, "text": "Spring for Apache Kafka" }, { "code": null, "e": 6377, "s": 5147, "text": "Open the project in an IDE and sync the dependencies. In this article, we would be creating a student model where we would be posting the student details. Therefore, create a model class Student. Add data members and create constructor and create getters and setters. The following is the implementation of the student class:// Java program to implement a// student class // Creating a student classpublic class Student { // Data members of the // student class int id; String firstName; String lastName; // Constructor of the student // class public Student(int id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } // Implementing the getters // and setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; }}" }, { "code": "// Java program to implement a// student class // Creating a student classpublic class Student { // Data members of the // student class int id; String firstName; String lastName; // Constructor of the student // class public Student(int id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } // Implementing the getters // and setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; }}", "e": 7282, "s": 6377, "text": null }, { "code": null, "e": 8219, "s": 7282, "text": "Now, create a new class Controller with the annotation @RestController. Create a GET API and initialize KafkaTemplate with parameter as string and model class object. The following is the implementation of the controller:// Java program to implement a// controller @RestController@RequestMapping(\"gfg\")public class UserResource { @Autowired private KafkaTemplate<String, Student> kafkaTemplate; private static final String TOPIC = \"StudentExample\"; @GetMapping(\"/publish/{id}/\" + \"{firstName}/{lastName}\") public String post( @PathVariable(\"id\") final int id, @PathVariable(\"firstName\") final String firstName, @PathVariable(\"lastName\") final String lastName) { kafkaTemplate.send( TOPIC, new Student( id, firstName, lastName)); return \"Published successfully\"; }}" }, { "code": "// Java program to implement a// controller @RestController@RequestMapping(\"gfg\")public class UserResource { @Autowired private KafkaTemplate<String, Student> kafkaTemplate; private static final String TOPIC = \"StudentExample\"; @GetMapping(\"/publish/{id}/\" + \"{firstName}/{lastName}\") public String post( @PathVariable(\"id\") final int id, @PathVariable(\"firstName\") final String firstName, @PathVariable(\"lastName\") final String lastName) { kafkaTemplate.send( TOPIC, new Student( id, firstName, lastName)); return \"Published successfully\"; }}", "e": 8935, "s": 8219, "text": null }, { "code": null, "e": 9906, "s": 8935, "text": "Create a class StudentConfig with the annotation @Configuration. In this class we will serialize the object of the model class.// Java program to serialize the// object of the model class @Configurationpublic class StudentConfig { @Bean public ProducerFactory<String, Student> producerFactory() { // Create a map of a string // and object Map<String, Object> config = new HashMap<>(); config.put( ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, \"127.0.0.1:9092\"); config.put( ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); config.put( ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); return new DefaultKafkaProducerFactory<>(config); } @Bean public KafkaTemplate<String, Student> kafkaTemplate() { return new KafkaTemplate<>( producerFactory()); }}" }, { "code": "// Java program to serialize the// object of the model class @Configurationpublic class StudentConfig { @Bean public ProducerFactory<String, Student> producerFactory() { // Create a map of a string // and object Map<String, Object> config = new HashMap<>(); config.put( ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, \"127.0.0.1:9092\"); config.put( ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); config.put( ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); return new DefaultKafkaProducerFactory<>(config); } @Bean public KafkaTemplate<String, Student> kafkaTemplate() { return new KafkaTemplate<>( producerFactory()); }}", "e": 10750, "s": 9906, "text": null }, { "code": null, "e": 10934, "s": 10750, "text": "Now, start zookeeper and Kafka server. We need to create a new topic with the name StudentExample. To do so, open a new command prompt window and change directory to the Kafka folder." }, { "code": null, "e": 11246, "s": 10934, "text": "Now, create a new topic using the command given below:For Mac and Linux: bin/kafka-topics.sh –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic topic_nameFor Windows: .\\bin\\windows\\kafka-topics.bat –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic topic_name" }, { "code": null, "e": 11373, "s": 11246, "text": "For Mac and Linux: bin/kafka-topics.sh –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic topic_name" }, { "code": null, "e": 11505, "s": 11373, "text": "For Windows: .\\bin\\windows\\kafka-topics.bat –create –zookeeper localhost:2181 –replication-factor 1 –partitions 1 –topic topic_name" }, { "code": null, "e": 11825, "s": 11505, "text": "Now to see the messages on the Kafka server in the real-time, use the command below:For Mac and Linux: bin/kafka-console-consumer.sh –bootstrap-server localhost:9092 –topic topic_name –from-beginningFor Windows: .\\bin\\windows\\kafka-console-consumer.bat –bootstrap-server localhost:9092 –topic topic_name –from-beginning" }, { "code": null, "e": 11941, "s": 11825, "text": "For Mac and Linux: bin/kafka-console-consumer.sh –bootstrap-server localhost:9092 –topic topic_name –from-beginning" }, { "code": null, "e": 12062, "s": 11941, "text": "For Windows: .\\bin\\windows\\kafka-console-consumer.bat –bootstrap-server localhost:9092 –topic topic_name –from-beginning" }, { "code": null, "e": 12232, "s": 12062, "text": "Run the application and call the API as:localhost:8080/gfg/publish/{id}/{first name}/{last name}Note: If a different port has been used, then replace the port with 8080." }, { "code": null, "e": 12289, "s": 12232, "text": "localhost:8080/gfg/publish/{id}/{first name}/{last name}" }, { "code": null, "e": 12363, "s": 12289, "text": "Note: If a different port has been used, then replace the port with 8080." }, { "code": null, "e": 12371, "s": 12363, "text": "Output:" }, { "code": null, "e": 12388, "s": 12371, "text": "Calling the API:" }, { "code": null, "e": 12423, "s": 12388, "text": "Checking the message in real time:" }, { "code": null, "e": 12430, "s": 12423, "text": "Apache" }, { "code": null, "e": 12444, "s": 12430, "text": "java-advanced" }, { "code": null, "e": 12456, "s": 12444, "text": "Java-Spring" }, { "code": null, "e": 12461, "s": 12456, "text": "JSON" }, { "code": null, "e": 12468, "s": 12461, "text": "How To" }, { "code": null, "e": 12482, "s": 12468, "text": "Java Programs" }, { "code": null, "e": 12499, "s": 12482, "text": "Web Technologies" } ]
Classes in TypeScript
14 Nov, 2019 Class in term of OOPs is a blueprint for creating objects. TypeScript supports object-oriented programming features like classes, Interfaces, Polymorphism, data-binding etc. Object means this a real world entity. JavaScript ES5 or earlier didn’t support classes. Typescript inherits this feature from ES6. In class group of objects which have common properties. Class contains fields, methods, constructors, Blocks, Nestedclass and interface. Syntax to declare a class: class class_Name{ field; method; } Here, in place of class_Name, name will be there, and inside field and method or function.If we compile this, It will generate JavaScript code. // Generated by typescript 1.8.10 var Person = (function () { function Person() { } return Person; }()); We will see a simple example: class Person {perCode: number;perName: string; constructor(code: number, name: string) {this.perName = name;this.perCode = code;} getGrade() : string {return “A+” ;}} The example declare a Student class which has two fields that is perCode and perName and a constructor which is special type of function which is responsible for variable or object initialization. Here is parameterized constructor. And this keyword which refers to the current instance of the class.getGrade() is a simple function.The TypeScript compiler will convert the above class in JavaScript code:ObjectsAn object is an instance of class which contains set of key value pairs. It’s value may be scalar values or functions or even array of other objects.The syntax is given below ? var object_name = { // scalar value key1: “value”, // functions key2: function() { }, // collection key3:[“content1”, “content2”] }; An objects can contain scalar value, functions and structures like arrays and tuples.We can represent object in literal notation: var person = {fName:”Marry”,lName:”Jerry”}; // Access the object valuesconsole.log(person.fName)console.log(person.lName) Marry Jerry Let’s see with simple example: var person = {fName:”Vivek”,lName:”Hanks”, // Type templateHello:function() { }} person.Hello = function() {console.log(“hello “+person.fName)} person.Hello() Output: hello Vivek Objects as function parameters var person = {fname:”Vivek”,lname:”Ranjan”};var hello = function(obj: { fname:string, lname:string }) {console.log(“first name :”+obj.fname)console.log(“last name :”+obj.lname)}hello(person) Output: first name :Vivek last name :Ranjan For creating Instance Objects.To create an instance of the class, use with the new keyword followed by the class name. To allocates memory for objects with the help new during runtime. Memory allocation for all objects in heap memory area. given below: var object_name = new class_name([ arguments ]) see with simple example declaration: // Creating an object or instance let obj = new Student(); Accessing Attributes and Functions:A class’s attributes and functions can be accessed by the object. With the help of ‘ . ’ dot notation we access the data members of a class. // Accessing an attribute obj.field_name // Accessing a function obj.function_name() We will see with the example: class Car { // Fieldengine:string; // Constructorconstructor(engine:string) {this.engine = engine} // Functiondisplay():void {console.log(“Function displays Engine is :”+ this.engine)}} // Create an objectvar o1 = new Car(“geeks”) // Access the fieldconsole.log(“Reading attribute value Engine as: ”+ o1.engine) // Access the functiono1.disp() After compilation this will convert into JavaScript code look like://Generated by typescript 1.8.10 var Car = (function () {// Here is constructorfunction Car(engine) {this.engine = engine;} // Function workingCar.prototype.display = function () {console.log(“Function displays Engine is: ”+ this.engine);};return Car;}()); // Create an objectvar o1 = new Car(“geks”); // Access the field valueconsole.log(“Attribute value Engine as: ”+ o1.engine); // Access the display functiono1.display(); Output: Attribute value Engine as : geeks Function displays Engine is : geeks shubham_singh TypeScript JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array JavaScript String includes() Method Implementation of LinkedList in Javascript DOM (Document Object Model) Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to create footer to stay at the bottom of a Web page? How to set the default value for an HTML <select> element ?
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Nov, 2019" }, { "code": null, "e": 334, "s": 28, "text": "Class in term of OOPs is a blueprint for creating objects. TypeScript supports object-oriented programming features like classes, Interfaces, Polymorphism, data-binding etc. Object means this a real world entity. JavaScript ES5 or earlier didn’t support classes. Typescript inherits this feature from ES6." }, { "code": null, "e": 471, "s": 334, "text": "In class group of objects which have common properties. Class contains fields, methods, constructors, Blocks, Nestedclass and interface." }, { "code": null, "e": 498, "s": 471, "text": "Syntax to declare a class:" }, { "code": null, "e": 556, "s": 498, "text": "class class_Name{ \n field; \n method; \n} \n" }, { "code": null, "e": 700, "s": 556, "text": "Here, in place of class_Name, name will be there, and inside field and method or function.If we compile this, It will generate JavaScript code." }, { "code": null, "e": 815, "s": 700, "text": "// Generated by typescript 1.8.10\nvar Person = (function () {\n function Person() {\n }\n return Person;\n}());\n" }, { "code": null, "e": 845, "s": 815, "text": "We will see a simple example:" }, { "code": null, "e": 892, "s": 845, "text": "class Person {perCode: number;perName: string;" }, { "code": null, "e": 975, "s": 892, "text": "constructor(code: number, name: string) {this.perName = name;this.perCode = code;}" }, { "code": null, "e": 1012, "s": 975, "text": "getGrade() : string {return “A+” ;}}" }, { "code": null, "e": 1599, "s": 1012, "text": "The example declare a Student class which has two fields that is perCode and perName and a constructor which is special type of function which is responsible for variable or object initialization. Here is parameterized constructor. And this keyword which refers to the current instance of the class.getGrade() is a simple function.The TypeScript compiler will convert the above class in JavaScript code:ObjectsAn object is an instance of class which contains set of key value pairs. It’s value may be scalar values or functions or even array of other objects.The syntax is given below ?" }, { "code": null, "e": 1763, "s": 1599, "text": "var object_name = {\n // scalar value \n key1: “value”, \n\n // functions\n key2: function() { \n }, \n\n // collection \n key3:[“content1”, “content2”] \n};\n" }, { "code": null, "e": 1893, "s": 1763, "text": "An objects can contain scalar value, functions and structures like arrays and tuples.We can represent object in literal notation:" }, { "code": null, "e": 1937, "s": 1893, "text": "var person = {fName:”Marry”,lName:”Jerry”};" }, { "code": null, "e": 2015, "s": 1937, "text": "// Access the object valuesconsole.log(person.fName)console.log(person.lName)" }, { "code": null, "e": 2028, "s": 2015, "text": "Marry\nJerry\n" }, { "code": null, "e": 2059, "s": 2028, "text": "Let’s see with simple example:" }, { "code": null, "e": 2102, "s": 2059, "text": "var person = {fName:”Vivek”,lName:”Hanks”," }, { "code": null, "e": 2140, "s": 2102, "text": "// Type templateHello:function() { }}" }, { "code": null, "e": 2203, "s": 2140, "text": "person.Hello = function() {console.log(“hello “+person.fName)}" }, { "code": null, "e": 2218, "s": 2203, "text": "person.Hello()" }, { "code": null, "e": 2226, "s": 2218, "text": "Output:" }, { "code": null, "e": 2239, "s": 2226, "text": "hello Vivek\n" }, { "code": null, "e": 2270, "s": 2239, "text": "Objects as function parameters" }, { "code": null, "e": 2461, "s": 2270, "text": "var person = {fname:”Vivek”,lname:”Ranjan”};var hello = function(obj: { fname:string, lname:string }) {console.log(“first name :”+obj.fname)console.log(“last name :”+obj.lname)}hello(person)" }, { "code": null, "e": 2469, "s": 2461, "text": "Output:" }, { "code": null, "e": 2506, "s": 2469, "text": "first name :Vivek\nlast name :Ranjan\n" }, { "code": null, "e": 2759, "s": 2506, "text": "For creating Instance Objects.To create an instance of the class, use with the new keyword followed by the class name. To allocates memory for objects with the help new during runtime. Memory allocation for all objects in heap memory area. given below:" }, { "code": null, "e": 2808, "s": 2759, "text": "var object_name = new class_name([ arguments ])\n" }, { "code": null, "e": 2845, "s": 2808, "text": "see with simple example declaration:" }, { "code": null, "e": 2912, "s": 2845, "text": "// Creating an object or instance \nlet obj = new Student(); \n" }, { "code": null, "e": 3088, "s": 2912, "text": "Accessing Attributes and Functions:A class’s attributes and functions can be accessed by the object. With the help of ‘ . ’ dot notation we access the data members of a class." }, { "code": null, "e": 3178, "s": 3088, "text": "// Accessing an attribute \nobj.field_name \n\n// Accessing a function \nobj.function_name()\n" }, { "code": null, "e": 3208, "s": 3178, "text": "We will see with the example:" }, { "code": null, "e": 3220, "s": 3208, "text": "class Car {" }, { "code": null, "e": 3243, "s": 3220, "text": "// Fieldengine:string;" }, { "code": null, "e": 3307, "s": 3243, "text": "// Constructorconstructor(engine:string) {this.engine = engine}" }, { "code": null, "e": 3394, "s": 3307, "text": "// Functiondisplay():void {console.log(“Function displays Engine is :”+ this.engine)}}" }, { "code": null, "e": 3439, "s": 3394, "text": "// Create an objectvar o1 = new Car(“geeks”)" }, { "code": null, "e": 3520, "s": 3439, "text": "// Access the fieldconsole.log(“Reading attribute value Engine as: ”+ o1.engine)" }, { "code": null, "e": 3552, "s": 3520, "text": "// Access the functiono1.disp()" }, { "code": null, "e": 3652, "s": 3552, "text": "After compilation this will convert into JavaScript code look like://Generated by typescript 1.8.10" }, { "code": null, "e": 3743, "s": 3652, "text": "var Car = (function () {// Here is constructorfunction Car(engine) {this.engine = engine;}" }, { "code": null, "e": 3876, "s": 3743, "text": "// Function workingCar.prototype.display = function () {console.log(“Function displays Engine is: ”+ this.engine);};return Car;}());" }, { "code": null, "e": 3921, "s": 3876, "text": "// Create an objectvar o1 = new Car(“geks”);" }, { "code": null, "e": 4001, "s": 3921, "text": "// Access the field valueconsole.log(“Attribute value Engine as: ”+ o1.engine);" }, { "code": null, "e": 4045, "s": 4001, "text": "// Access the display functiono1.display();" }, { "code": null, "e": 4053, "s": 4045, "text": "Output:" }, { "code": null, "e": 4125, "s": 4053, "text": "Attribute value Engine as : geeks\nFunction displays Engine is : geeks\n" }, { "code": null, "e": 4139, "s": 4125, "text": "shubham_singh" }, { "code": null, "e": 4150, "s": 4139, "text": "TypeScript" }, { "code": null, "e": 4161, "s": 4150, "text": "JavaScript" }, { "code": null, "e": 4178, "s": 4161, "text": "Web Technologies" }, { "code": null, "e": 4276, "s": 4178, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4337, "s": 4276, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4377, "s": 4337, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4413, "s": 4377, "text": "JavaScript String includes() Method" }, { "code": null, "e": 4456, "s": 4413, "text": "Implementation of LinkedList in Javascript" }, { "code": null, "e": 4484, "s": 4456, "text": "DOM (Document Object Model)" }, { "code": null, "e": 4517, "s": 4484, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4567, "s": 4517, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4629, "s": 4567, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4687, "s": 4629, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Solving Cryptarithmetic Puzzles | Backtracking-8
10 May, 2019 Newspapers and magazines often have crypt-arithmetic puzzles of the form: SEND + MORE -------- MONEY -------- The goal here is to assign each letter a digit from 0 to 9 so that the arithmetic works out correctly. The rules are that all occurrences of a letter must be assigned the same digit, and no digit can be assigned to more than one letter. First, create a list of all the characters that need assigning to pass to Solve If all characters are assigned, return true if puzzle is solved, false otherwise Otherwise, consider the first unassigned character for (every possible choice among the digits not in use) make that choice and then recursively try to assign the rest of the charactersif recursion successful, return trueif !successful, unmake assignment and try another digit If all digits have been tried and nothing worked, return false to trigger backtracking /* ExhaustiveSolve* ---------------* This is the "not-very-smart" version of cryptarithmetic solver. It takes* the puzzle itself (with the 3 strings for the two addends and sum) and a* string of letters as yet unassigned. If no more letters to assign* then we've hit a base-case, if the current letter-to-digit mapping solves* the puzzle, we're done, otherwise we return false to trigger backtracking* If we have letters to assign, we take the first letter from that list, and* try assigning it the digits from 0 to 9 and then recursively working* through solving puzzle from here. If we manage to make a good assignment* that works, we've succeeded, else we need to unassign that choice and try* another digit. This version is easy to write, since it uses a simple* approach (quite similar to permutations if you think about it) but it is* not so smart because it doesn't take into account the structure of the* puzzle constraints (for example, once the two digits for the addends have* been assigned, there is no reason to try anything other than the correct* digit for the sum) yet it tries a lot of useless combos regardless*/bool ExhaustiveSolve(puzzleT puzzle, string lettersToAssign){ if (lettersToAssign.empty()) // no more choices to make return PuzzleSolved(puzzle); // checks arithmetic to see if works for (int digit = 0; digit <= 9; digit++) // try all digits { if (AssignLetterToDigit(lettersToAssign[0], digit)) { if (ExhaustiveSolve(puzzle, lettersToAssign.substr(1))) return true; UnassignLetterFromDigit(lettersToAssign[0], digit); } } return false; // nothing worked, need to backtrack} The algorithm above actually has a lot in common with the permutations algorithm, it pretty much just creates all arrangements of the mapping from characters to digits and tries each until one works or all have been successfully tried. For a large puzzle, this could take a while.A smarter algorithm could take into account the structure of the puzzle and avoid going down dead-end paths. For example, if we assign the characters starting from the one’s place and moving to the left, at each stage, we can verify the correctness of what we have so far before we continue onwards. This definitely complicates the code but leads to a tremendous improvement in efficiency, making it much more feasible to solve large puzzles. Below pseudocode, in this case, has more special cases, but the same general design Start by examining the rightmost digit of the topmost row, with a carry of 0 If we are beyond the leftmost digit of the puzzle, return true if no carry, false otherwise If we are currently trying to assign a char in one of the addendsIf char already assigned, just recur on the row beneath this one, adding value into the sumIf not assigned, thenfor (every possible choice among the digits not in use)make that choice and then on row beneath this one, if successful, return trueif !successful, unmake assignment and try another digitreturn false if no assignment worked to trigger backtracking for (every possible choice among the digits not in use)make that choice and then on row beneath this one, if successful, return trueif !successful, unmake assignment and try another digit return false if no assignment worked to trigger backtracking Else if trying to assign a char in the sum If char assigned & matches correct,recur on next column to the left with carry, if success return true, If char assigned & doesn’t match, return false If char unassigned & correct digit already used, return false If char unassigned & correct digit unused,assign it and recur on next column to left with carry, if success return true return false to trigger backtracking Source:http://see.stanford.edu/materials/icspacs106b/H19-RecBacktrackExamples.pdf ManasChhabra2 Backtracking Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Print all paths from a given source to a destination Generate all the binary strings of N bits Print all permutations of a string in Java Find if there is a path of more than k length from a source Recursive program to generate power set Find Maximum number possible by doing at-most K swaps Remove Invalid Parentheses Difference between Backtracking and Branch-N-Bound technique Find all distinct subsets of a given set using BitMasking Approach
[ { "code": null, "e": 52, "s": 24, "text": "\n10 May, 2019" }, { "code": null, "e": 126, "s": 52, "text": "Newspapers and magazines often have crypt-arithmetic puzzles of the form:" }, { "code": null, "e": 166, "s": 126, "text": " SEND\n+ MORE\n--------\n MONEY\n-------- " }, { "code": null, "e": 403, "s": 166, "text": "The goal here is to assign each letter a digit from 0 to 9 so that the arithmetic works out correctly. The rules are that all occurrences of a letter must be assigned the same digit, and no digit can be assigned to more than one letter." }, { "code": null, "e": 483, "s": 403, "text": "First, create a list of all the characters that need assigning to pass to Solve" }, { "code": null, "e": 564, "s": 483, "text": "If all characters are assigned, return true if puzzle is solved, false otherwise" }, { "code": null, "e": 615, "s": 564, "text": "Otherwise, consider the first unassigned character" }, { "code": null, "e": 671, "s": 615, "text": "for (every possible choice among the digits not in use)" }, { "code": null, "e": 841, "s": 671, "text": "make that choice and then recursively try to assign the rest of the charactersif recursion successful, return trueif !successful, unmake assignment and try another digit" }, { "code": null, "e": 928, "s": 841, "text": "If all digits have been tried and nothing worked, return false to trigger backtracking" }, { "code": "/* ExhaustiveSolve* ---------------* This is the \"not-very-smart\" version of cryptarithmetic solver. It takes* the puzzle itself (with the 3 strings for the two addends and sum) and a* string of letters as yet unassigned. If no more letters to assign* then we've hit a base-case, if the current letter-to-digit mapping solves* the puzzle, we're done, otherwise we return false to trigger backtracking* If we have letters to assign, we take the first letter from that list, and* try assigning it the digits from 0 to 9 and then recursively working* through solving puzzle from here. If we manage to make a good assignment* that works, we've succeeded, else we need to unassign that choice and try* another digit. This version is easy to write, since it uses a simple* approach (quite similar to permutations if you think about it) but it is* not so smart because it doesn't take into account the structure of the* puzzle constraints (for example, once the two digits for the addends have* been assigned, there is no reason to try anything other than the correct* digit for the sum) yet it tries a lot of useless combos regardless*/bool ExhaustiveSolve(puzzleT puzzle, string lettersToAssign){ if (lettersToAssign.empty()) // no more choices to make return PuzzleSolved(puzzle); // checks arithmetic to see if works for (int digit = 0; digit <= 9; digit++) // try all digits { if (AssignLetterToDigit(lettersToAssign[0], digit)) { if (ExhaustiveSolve(puzzle, lettersToAssign.substr(1))) return true; UnassignLetterFromDigit(lettersToAssign[0], digit); } } return false; // nothing worked, need to backtrack}", "e": 2617, "s": 928, "text": null }, { "code": null, "e": 3340, "s": 2617, "text": "The algorithm above actually has a lot in common with the permutations algorithm, it pretty much just creates all arrangements of the mapping from characters to digits and tries each until one works or all have been successfully tried. For a large puzzle, this could take a while.A smarter algorithm could take into account the structure of the puzzle and avoid going down dead-end paths. For example, if we assign the characters starting from the one’s place and moving to the left, at each stage, we can verify the correctness of what we have so far before we continue onwards. This definitely complicates the code but leads to a tremendous improvement in efficiency, making it much more feasible to solve large puzzles." }, { "code": null, "e": 3424, "s": 3340, "text": "Below pseudocode, in this case, has more special cases, but the same general design" }, { "code": null, "e": 3501, "s": 3424, "text": "Start by examining the rightmost digit of the topmost row, with a carry of 0" }, { "code": null, "e": 3593, "s": 3501, "text": "If we are beyond the leftmost digit of the puzzle, return true if no carry, false otherwise" }, { "code": null, "e": 4018, "s": 3593, "text": "If we are currently trying to assign a char in one of the addendsIf char already assigned, just recur on the row beneath this one, adding value into the sumIf not assigned, thenfor (every possible choice among the digits not in use)make that choice and then on row beneath this one, if successful, return trueif !successful, unmake assignment and try another digitreturn false if no assignment worked to trigger backtracking" }, { "code": null, "e": 4206, "s": 4018, "text": "for (every possible choice among the digits not in use)make that choice and then on row beneath this one, if successful, return trueif !successful, unmake assignment and try another digit" }, { "code": null, "e": 4267, "s": 4206, "text": "return false if no assignment worked to trigger backtracking" }, { "code": null, "e": 4310, "s": 4267, "text": "Else if trying to assign a char in the sum" }, { "code": null, "e": 4414, "s": 4310, "text": "If char assigned & matches correct,recur on next column to the left with carry, if success return true," }, { "code": null, "e": 4461, "s": 4414, "text": "If char assigned & doesn’t match, return false" }, { "code": null, "e": 4523, "s": 4461, "text": "If char unassigned & correct digit already used, return false" }, { "code": null, "e": 4643, "s": 4523, "text": "If char unassigned & correct digit unused,assign it and recur on next column to left with carry, if success return true" }, { "code": null, "e": 4680, "s": 4643, "text": "return false to trigger backtracking" }, { "code": null, "e": 4762, "s": 4680, "text": "Source:http://see.stanford.edu/materials/icspacs106b/H19-RecBacktrackExamples.pdf" }, { "code": null, "e": 4776, "s": 4762, "text": "ManasChhabra2" }, { "code": null, "e": 4789, "s": 4776, "text": "Backtracking" }, { "code": null, "e": 4802, "s": 4789, "text": "Backtracking" }, { "code": null, "e": 4900, "s": 4802, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4985, "s": 4900, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 5038, "s": 4985, "text": "Print all paths from a given source to a destination" }, { "code": null, "e": 5080, "s": 5038, "text": "Generate all the binary strings of N bits" }, { "code": null, "e": 5123, "s": 5080, "text": "Print all permutations of a string in Java" }, { "code": null, "e": 5183, "s": 5123, "text": "Find if there is a path of more than k length from a source" }, { "code": null, "e": 5223, "s": 5183, "text": "Recursive program to generate power set" }, { "code": null, "e": 5277, "s": 5223, "text": "Find Maximum number possible by doing at-most K swaps" }, { "code": null, "e": 5304, "s": 5277, "text": "Remove Invalid Parentheses" }, { "code": null, "e": 5365, "s": 5304, "text": "Difference between Backtracking and Branch-N-Bound technique" } ]
Heighway’s Dragon Curve using Python
26 Apr, 2022 Introduction | Dragon Curve A Dragon curve is a recursive non-intersecting curve also known as the Harter–Heighway dragon or the Jurassic Park dragon curve. It is a mathematical curve which can be approximated by recursive methods such as Lindenmayer systems. Lindenmayer systems: A Lindenmayer system, also known as an L-system, is a string rewriting system that can be used to generate fractals. Two principal areas include generation of fractals and realistic modeling of plants. Lindenmayer system begins with a string of symbols called the axiom and applies to the axiom a set of production rules which are used to rewrite the axiom. Recursive L-System are more interesting as it replaces a symbol with a copy of itself plus something extra.L-system follow some rules: An L-system is a formal grammar consisting of 4 parts: 1. A set of variables: symbols that can be replaced by production rules. 2. A set of constants: symbols that do not get replaced.e.g: !, [, ], +, -. 3. A single axiom: a string & is the initial state of the system. 4. A set of production rules: defining the way/rule variables can be replaced. Let’s take the example of the following L-system: L-System Rules gen 1 takes help of gen 0 (axiom) generation 1 -> apply rule in generation 0 generation 0 = skk replace s with "ksk" in gen 0 to get gen 1 gen 1 = (s)kk = (ksk)kk = kskskk replace s with "ksk" in gen 1 to get gen 2 Iterate the same rule for all generations Recursive L-systems, often produce intricately complex patterns that are self-similar across multiple scales.These complex patterns can be visualized with the help of a graphical interpretation applied to L-Systems based on turtle graphics.When L-systems are used with turtle graphics, a state of the turtle is defined as a quadruple (x, y, a, c). The Cartesian coordinates (x, y) represent the turtle’s position. The angle a, called the heading is interpreted as the direction in which the turtle is facing. The color c is interpreted as the color pen that the turtle currently has pressed to the floor so that any movement of the turtle will create a line of that color. Given the step size d and the angle increment b, the turtle can respond to symbols in an L-system string according to the following instructions: Move forward (in the dir of the current heading) a distance d while drawing a line of color c. The state of the turtle changes to (x', y', a, c), where x' = x + d cos(a) and y' = y + d sin(a) Dragon Curve L-system The finite approximation of Dragon curve can be created with an L-System.The Dragon curve L-system can be represented as : 2 rules / \ replace f with f-h replace h with f+h + & - are constants build up generations by following rules on axiom gen 1 forms gen 2; gen 2 forms gen 3 and so on... The generation 2 string is: 'f-h - f+h' In the above L-system, assuming that the initial heading of the turtle is upward on the screen, then the first ‘f’ will draw a line straight up. The ‘-‘ causes the turtle to change its heading by 90 degrees to be pointed directly to the left. The ‘h’ draws a line directly to the left of the screen. The second ‘-‘ symbol again turns the turtle 90 degrees to its left which is directly down on the screen. The f symbol draws a unit length line in the down direction. The last turn symbol in the string is a ‘+’ which turns the turtle to its right by 90 degrees. However, since current heading of the turtle is pointed downward, its right is the screen’s left, so again the turtle’s heading is to the left of the screen. Finally, the h symbol draws a unit length line to the screen’s left.Hence we get the colorful resulting image. If we keep on forming more generations, we get beautiful curves called the dragon curves.As we can see below, the curve gets more intricate and complex as we grow in generations. Iteration 3: Iteration 9: Dragon Curve using paper These dragon curves can also be formed by Paper folding: The concept is so simple but the potential is amazing. Take a long strip of paper and fold it in half. You get a strip of paper with a fold in it! Refold the paper then fold it in half again. When you look inside you have two folds going in one direction and one fold going the other way. Refold and fold in half again and, when you unfold, you get even more folds, some going one way, some the other. Unfold the strip and make a firm crease along each of the fold lines, taking care to maintain the correct direction for the fold. Stand the strip on its edge, with each fold forming a 90 degree angle, and look down on it. You will see an intricate pattern of squares, and twists and turns. The strips get the name of Dragon Curves because, after a few folds, they start to take on the appearance of a dragon with large head, legs and tail. Numberphile explains Dragon Curve’s formation well in their video.You can also watch the Dragon curve transitions Here : https://www.youtube.com/watch?v=3WBvS_n2oTY Programming the Dragon Curve PSEUDOCODE → IMPORT TURTLE → TURN TURTLE - RIGHT SIDE('r') #OLD PATTERN = 'r' → NEW PATTERN = OLD PATTERN → USER INPUT [ Number of Iterations(n), Segment size, Pen color & Background color ] → CYCLE = 1 → WHILE CYCLE < ITERATION : → FORM DRAGON CURVE L-SYSTEM → STORE THE PATTERN OF 'l'/'r' in NEW PATTERN → NEW PATTERN += OLD PATTERN → OLD PATTERN = NEW PATTERN → INCREMENT CYCLE → USER INPUT [Whether to display 'r'/'l' Dragon curve L-system in console] → INITIATE THE TURTLE TO DRAW [pencolor, bgcolor, draw right = segment size] → ITERATE OVER FULL L SYSTEM FOR n ITERATIONS: → IF CHAR == 'r' → DRAW RIGHT(90) → DRAW FORWARD(Segment Size) → ELSE IF CHAR == 'l' → DRAW LEFT(90) → DRAW FORWARD(Segment Size) → END Python # import the turtle module to use turtle graphicsimport turtle # make variables for the right and left containing 'r' and 'l'r = 'r'l = 'l' # assign our first iteration a right so we can build off of itold = rnew = old # for inputsiteration = int(input('Enter iteration:'))length = int(input('Enter length of each segment:'))pencolor = input('Enter pen color:')bgcolor = input('Enter background color:') # set the number of times we have been creating# the next iteration as the firstcycle = 1 # keep on generating the next iteration until desired iteration is reachedwhile cycle<iteration: # add a right to the end of the old iteration and save it to the new new = (old) + (r) # flip the old iteration around(as in the first character becomes last) old = old[::-1] # cycling through each character in the flipped old iteration: for char in range(0, len(old)): # if the character is a right: if old[char] == r: # change it to a left old = (old[:char])+ (l) + (old[char + 1:]) # otherwise, if it's a left: elif old[char] == l: #change it to a right old = (old[:char]) + (r) + (old[char + 1:]) # add the modified old to the new iteration new = (new) + (old) # save the new iteration to old as well for use next cycle old = new # advance cycle variable to keep track of the number of times it's been done cycle = cycle + 1 printans = input('Display r/l form?(y/n):')if printans =='y': print(new) # for not show the turtle icon when drawingturtle.ht()turtle.speed(0)turtle.color(pencolor)turtle.bgcolor(bgcolor)turtle.forward(length) # cycling through all the characters in the iterationfor char in range(0, len(new)): # if the character is a right: if new[char] == (r): turtle.right(90) turtle.forward(length) # otherwise, if the character is a left: elif new[char] == (l): turtle.left(90) turtle.forward(length) Output : Dragon Fractals - YouTubeAmartya R Saikia277 subscribersDragon FractalsWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 0:37•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=7C1OxeoyCGE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Get the codes of Dragon curve for different languages from rosettacode. It will give you great pleasure to check the fractals yourself. Also check, Project Euler : Problem 220 : Heighway Dragon. References: Mathematics of Fractals formation math.psu.edu [pdf] ecademy.agnesscott.edu woollythoughts.com This article is contributed by Amartya Ranjan Saikia. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Akanksha_Rai simmytarika5 Fractal GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Apr, 2022" }, { "code": null, "e": 56, "s": 28, "text": "Introduction | Dragon Curve" }, { "code": null, "e": 802, "s": 56, "text": "A Dragon curve is a recursive non-intersecting curve also known as the Harter–Heighway dragon or the Jurassic Park dragon curve. It is a mathematical curve which can be approximated by recursive methods such as Lindenmayer systems. Lindenmayer systems: A Lindenmayer system, also known as an L-system, is a string rewriting system that can be used to generate fractals. Two principal areas include generation of fractals and realistic modeling of plants. Lindenmayer system begins with a string of symbols called the axiom and applies to the axiom a set of production rules which are used to rewrite the axiom. Recursive L-System are more interesting as it replaces a symbol with a copy of itself plus something extra.L-system follow some rules:" }, { "code": null, "e": 1151, "s": 802, "text": "An L-system is a formal grammar consisting of 4 parts:\n1. A set of variables: symbols that can be replaced by production rules.\n2. A set of constants: symbols that do not get replaced.e.g: !, [, ], +, -.\n3. A single axiom: a string & is the initial state of the system.\n4. A set of production rules: defining the way/rule variables can be replaced." }, { "code": null, "e": 1216, "s": 1151, "text": "Let’s take the example of the following L-system: L-System Rules" }, { "code": null, "e": 1473, "s": 1216, "text": "gen 1 takes help of gen 0 (axiom)\ngeneration 1 -> apply rule in generation 0\ngeneration 0 = skk\nreplace s with \"ksk\" in gen 0 to get gen 1\ngen 1 = (s)kk = (ksk)kk = kskskk\nreplace s with \"ksk\" in gen 1 to get gen 2\nIterate the same rule for all generations" }, { "code": null, "e": 2292, "s": 1473, "text": "Recursive L-systems, often produce intricately complex patterns that are self-similar across multiple scales.These complex patterns can be visualized with the help of a graphical interpretation applied to L-Systems based on turtle graphics.When L-systems are used with turtle graphics, a state of the turtle is defined as a quadruple (x, y, a, c). The Cartesian coordinates (x, y) represent the turtle’s position. The angle a, called the heading is interpreted as the direction in which the turtle is facing. The color c is interpreted as the color pen that the turtle currently has pressed to the floor so that any movement of the turtle will create a line of that color. Given the step size d and the angle increment b, the turtle can respond to symbols in an L-system string according to the following instructions:" }, { "code": null, "e": 2485, "s": 2292, "text": "Move forward (in the dir of the current heading) a distance d while drawing a line of color c.\nThe state of the turtle changes to (x', y', a, c), where \nx' = x + d cos(a) and y' = y + d sin(a)" }, { "code": null, "e": 2507, "s": 2485, "text": "Dragon Curve L-system" }, { "code": null, "e": 2630, "s": 2507, "text": "The finite approximation of Dragon curve can be created with an L-System.The Dragon curve L-system can be represented as :" }, { "code": null, "e": 2884, "s": 2630, "text": " 2 rules\n / \\ \nreplace f with f-h replace h with f+h\n\n+ & - are constants\n\nbuild up generations by following rules on axiom\ngen 1 forms gen 2; gen 2 forms gen 3 and so on...\n\nThe generation 2 string is: 'f-h - f+h'" }, { "code": null, "e": 3923, "s": 2884, "text": " In the above L-system, assuming that the initial heading of the turtle is upward on the screen, then the first ‘f’ will draw a line straight up. The ‘-‘ causes the turtle to change its heading by 90 degrees to be pointed directly to the left. The ‘h’ draws a line directly to the left of the screen. The second ‘-‘ symbol again turns the turtle 90 degrees to its left which is directly down on the screen. The f symbol draws a unit length line in the down direction. The last turn symbol in the string is a ‘+’ which turns the turtle to its right by 90 degrees. However, since current heading of the turtle is pointed downward, its right is the screen’s left, so again the turtle’s heading is to the left of the screen. Finally, the h symbol draws a unit length line to the screen’s left.Hence we get the colorful resulting image. If we keep on forming more generations, we get beautiful curves called the dragon curves.As we can see below, the curve gets more intricate and complex as we grow in generations. Iteration 3: Iteration 9: " }, { "code": null, "e": 3948, "s": 3923, "text": "Dragon Curve using paper" }, { "code": null, "e": 4968, "s": 3948, "text": "These dragon curves can also be formed by Paper folding: The concept is so simple but the potential is amazing. Take a long strip of paper and fold it in half. You get a strip of paper with a fold in it! Refold the paper then fold it in half again. When you look inside you have two folds going in one direction and one fold going the other way. Refold and fold in half again and, when you unfold, you get even more folds, some going one way, some the other. Unfold the strip and make a firm crease along each of the fold lines, taking care to maintain the correct direction for the fold. Stand the strip on its edge, with each fold forming a 90 degree angle, and look down on it. You will see an intricate pattern of squares, and twists and turns. The strips get the name of Dragon Curves because, after a few folds, they start to take on the appearance of a dragon with large head, legs and tail. Numberphile explains Dragon Curve’s formation well in their video.You can also watch the Dragon curve transitions Here :" }, { "code": null, "e": 5012, "s": 4968, "text": "https://www.youtube.com/watch?v=3WBvS_n2oTY" }, { "code": null, "e": 5041, "s": 5012, "text": "Programming the Dragon Curve" }, { "code": null, "e": 5861, "s": 5041, "text": "PSEUDOCODE\n→ IMPORT TURTLE\n→ TURN TURTLE - RIGHT SIDE('r') #OLD PATTERN = 'r'\n→ NEW PATTERN = OLD PATTERN\n→ USER INPUT [ Number of Iterations(n), Segment size, Pen color & Background color ]\n→ CYCLE = 1\n→ WHILE CYCLE < ITERATION :\n→ FORM DRAGON CURVE L-SYSTEM\n→ STORE THE PATTERN OF 'l'/'r' in NEW PATTERN\n→ NEW PATTERN += OLD PATTERN\n→ OLD PATTERN = NEW PATTERN\n→ INCREMENT CYCLE\n→ USER INPUT [Whether to display 'r'/'l' Dragon curve L-system in console]\n→ INITIATE THE TURTLE TO DRAW [pencolor, bgcolor, draw right = segment size]\n→ ITERATE OVER FULL L SYSTEM FOR n ITERATIONS:\n→ IF CHAR == 'r'\n→ DRAW RIGHT(90)\n→ DRAW FORWARD(Segment Size)\n→ ELSE IF CHAR == 'l'\n→ DRAW LEFT(90)\n→ DRAW FORWARD(Segment Size)\n→ END" }, { "code": null, "e": 5868, "s": 5861, "text": "Python" }, { "code": "# import the turtle module to use turtle graphicsimport turtle # make variables for the right and left containing 'r' and 'l'r = 'r'l = 'l' # assign our first iteration a right so we can build off of itold = rnew = old # for inputsiteration = int(input('Enter iteration:'))length = int(input('Enter length of each segment:'))pencolor = input('Enter pen color:')bgcolor = input('Enter background color:') # set the number of times we have been creating# the next iteration as the firstcycle = 1 # keep on generating the next iteration until desired iteration is reachedwhile cycle<iteration: # add a right to the end of the old iteration and save it to the new new = (old) + (r) # flip the old iteration around(as in the first character becomes last) old = old[::-1] # cycling through each character in the flipped old iteration: for char in range(0, len(old)): # if the character is a right: if old[char] == r: # change it to a left old = (old[:char])+ (l) + (old[char + 1:]) # otherwise, if it's a left: elif old[char] == l: #change it to a right old = (old[:char]) + (r) + (old[char + 1:]) # add the modified old to the new iteration new = (new) + (old) # save the new iteration to old as well for use next cycle old = new # advance cycle variable to keep track of the number of times it's been done cycle = cycle + 1 printans = input('Display r/l form?(y/n):')if printans =='y': print(new) # for not show the turtle icon when drawingturtle.ht()turtle.speed(0)turtle.color(pencolor)turtle.bgcolor(bgcolor)turtle.forward(length) # cycling through all the characters in the iterationfor char in range(0, len(new)): # if the character is a right: if new[char] == (r): turtle.right(90) turtle.forward(length) # otherwise, if the character is a left: elif new[char] == (l): turtle.left(90) turtle.forward(length)", "e": 7840, "s": 5868, "text": null }, { "code": null, "e": 7849, "s": 7840, "text": "Output :" }, { "code": null, "e": 8667, "s": 7849, "text": "Dragon Fractals - YouTubeAmartya R Saikia277 subscribersDragon FractalsWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 0:37•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=7C1OxeoyCGE\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 8874, "s": 8667, "text": "Get the codes of Dragon curve for different languages from rosettacode. It will give you great pleasure to check the fractals yourself. Also check, Project Euler : Problem 220 : Heighway Dragon. References:" }, { "code": null, "e": 8908, "s": 8874, "text": "Mathematics of Fractals formation" }, { "code": null, "e": 8927, "s": 8908, "text": "math.psu.edu [pdf]" }, { "code": null, "e": 8950, "s": 8927, "text": "ecademy.agnesscott.edu" }, { "code": null, "e": 8969, "s": 8950, "text": "woollythoughts.com" }, { "code": null, "e": 9399, "s": 8969, "text": "This article is contributed by Amartya Ranjan Saikia. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 9412, "s": 9399, "text": "Akanksha_Rai" }, { "code": null, "e": 9425, "s": 9412, "text": "simmytarika5" }, { "code": null, "e": 9433, "s": 9425, "text": "Fractal" }, { "code": null, "e": 9439, "s": 9433, "text": "GBlog" } ]
How to Remove HTML element from DOM using AngularJS ?
15 Oct, 2020 Here the task is to remove a particular element from the DOM with the help of AngularJS. Approach: Here first we select the element that we want to remove. Then we use remove() method to remove that particular element. Example 1: Here the element of class(‘p’) has been removed. <!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.removeEl = function () { var el = angular.element( document.querySelector('.p')); el.remove(); }; }); </script> <style> .p { border: 1px solid black; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> Remove a HTML element from DOM </p> <div ng-app="app"> <div ng-controller="controller"> <p class="p">This is paragraph</p> <input type="button" value="Click here" ng-click="removeEl()"> </div> </div></body> </html> Output: Example 2: Here the element of Id(‘p’) has been removed by remove() method. <!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.removeEl = function () { var el = angular.element( document.querySelector('#div')); el.remove(); }; }); </script> <style> #div { height: 50px; width: 100px; margin: 0 auto; background: green; color: white; } </style></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> Remove a HTML element from DOM </p> <div ng-app="app"> <div ng-controller="controller"> <div id="div">Element</div> <br> <input type="button" value="Click here" ng-click="removeEl()"> </div> </div></body> </html> Output: AngularJS-Misc CSS-Misc HTML-Misc AngularJS CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Auth Guards in Angular 9/10/11 Routing in Angular 9/10 What is AOT and JIT Compiler in Angular ? Angular PrimeNG Dropdown Component How to set focus on input field automatically on page load in AngularJS ? 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
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Oct, 2020" }, { "code": null, "e": 117, "s": 28, "text": "Here the task is to remove a particular element from the DOM with the help of AngularJS." }, { "code": null, "e": 247, "s": 117, "text": "Approach: Here first we select the element that we want to remove. Then we use remove() method to remove that particular element." }, { "code": null, "e": 307, "s": 247, "text": "Example 1: Here the element of class(‘p’) has been removed." }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.removeEl = function () { var el = angular.element( document.querySelector('.p')); el.remove(); }; }); </script> <style> .p { border: 1px solid black; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> Remove a HTML element from DOM </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> <p class=\"p\">This is paragraph</p> <input type=\"button\" value=\"Click here\" ng-click=\"removeEl()\"> </div> </div></body> </html> ", "e": 1242, "s": 307, "text": null }, { "code": null, "e": 1250, "s": 1242, "text": "Output:" }, { "code": null, "e": 1326, "s": 1250, "text": "Example 2: Here the element of Id(‘p’) has been removed by remove() method." }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.removeEl = function () { var el = angular.element( document.querySelector('#div')); el.remove(); }; }); </script> <style> #div { height: 50px; width: 100px; margin: 0 auto; background: green; color: white; } </style></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> Remove a HTML element from DOM </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> <div id=\"div\">Element</div> <br> <input type=\"button\" value=\"Click here\" ng-click=\"removeEl()\"> </div> </div></body> </html> ", "e": 2369, "s": 1326, "text": null }, { "code": null, "e": 2377, "s": 2369, "text": "Output:" }, { "code": null, "e": 2392, "s": 2377, "text": "AngularJS-Misc" }, { "code": null, "e": 2401, "s": 2392, "text": "CSS-Misc" }, { "code": null, "e": 2411, "s": 2401, "text": "HTML-Misc" }, { "code": null, "e": 2421, "s": 2411, "text": "AngularJS" }, { "code": null, "e": 2425, "s": 2421, "text": "CSS" }, { "code": null, "e": 2430, "s": 2425, "text": "HTML" }, { "code": null, "e": 2447, "s": 2430, "text": "Web Technologies" }, { "code": null, "e": 2474, "s": 2447, "text": "Web technologies Questions" }, { "code": null, "e": 2479, "s": 2474, "text": "HTML" }, { "code": null, "e": 2577, "s": 2479, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2608, "s": 2577, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 2632, "s": 2608, "text": "Routing in Angular 9/10" }, { "code": null, "e": 2674, "s": 2632, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 2709, "s": 2674, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 2783, "s": 2709, "text": "How to set focus on input field automatically on page load in AngularJS ?" }, { "code": null, "e": 2831, "s": 2783, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2893, "s": 2831, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2943, "s": 2893, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3001, "s": 2943, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Python Tricks for Competitive Coding
03 Jun, 2022 Python is one such programming language that makes everything easier and straight forward. Anyone who has dabbled in python for Competitive Coding gets somewhat addicted to its many features. Here is a list of some of its cool features that I’ve found most useful in a competitive coding environment. The most_common function of the Counter Package. This is probably the most useful function I’ve ever used and its always at the back of my mind while writing any python code. This function analyses a list/string and helps to return the top n entities in the list/string according to their number of occurrences in descending order where n is a number that is specified by the programmer. The individual entities are returned along with their number of occurrences in a tuple which can easily be referred/printed as and when required. Python # Code to find top 3 elements and their counts# using most_commonfrom collections import Counter arr = [1, 3, 4, 1, 2, 1, 1, 3, 4, 3, 5, 1, 2, 5, 3, 4, 5]counter = Counter(arr)top_three = counter.most_common(3)print(top_three) Output: [(1, 5), (3, 4), (4, 3)] The output tuple clearly states that 1 has occurred 5 times, 3 has occurred 4 times, and 4 has occurred 3 times. The n-largest/n-smallest function of the heapq Package. This function helps to return the top n smallest/largest elements in any lists and here again n is a number specified by the programmer. Python # Python code to find 3 largest and 4 smallest# elements of a list.import heapq grades = [110, 25, 38, 49, 20, 95, 33, 87, 80, 90]print(heapq.nlargest(3, grades))print(heapq.nsmallest(4, grades)) Output: [110, 95, 90] [20, 25, 33, 38] The first line of output gives 3 of the largest numbers present in the list grades. Similarly the second line of output prints out 4 of the smallest elements present in the list grades. Another speciality of this function is that it does not overlook repetitions. So in place of n if we were to place the length of the array the we would end up with the entire sorted array itself !! Dictionary and concept of zipping Dictionaries Dictionaries in python are truly fascinating in terms of the unique functionality that they offer. They are stored as a Key and Value pair in the form of an array like structure. Each value can be accessed by its corresponding key. The zip function is used to join two lists together or we can even join the key and value pairs in a dictionary together as a single list. The application of this concept will be made clear in the following code snippet. Python # Python code to demonstrate use of zip.import heapq stocks = { 'Goog' : 520.54, 'FB' : 76.45, 'yhoo' : 39.28, 'AMZN' : 306.21, 'APPL' : 99.76 } zipped_1 = zip(stocks.values(), stocks.keys()) # sorting according to valuesprint(sorted(zipped_1)) zipped_2 = zip(stocks.keys(), stocks.values())print(sorted(zipped_2))#sorting according to keys Output: [(39.28, 'yhoo'), (76.45, 'FB'), (99.76, 'APPL'), (306.21, 'AMZN'), (520.54, 'Goog')] [('AMZN', 306.21), ('APPL', 99.76), ('FB', 76.45), ('Goog', 520.54), ('yhoo', 39.28)] The Map function. This function is a sneaky little shortcut that allows us to implement a simple function on a list of values in a very Unconventional Manner. The following example will give a simple application of this functionality. The function takes as parameters the function name and the name of the list the function needs to be applied upon. Python # Python code to apply a function on a listincome = [10, 30, 75] def double_money(dollars): return dollars * 2 new_income = list(map(double_money, income))print(new_income) Output: [20, 60, 150] Here, we just implemented a simple function which multiplies each list value by two and returns it as a new list. Concatenation of list of strings Suppose we have been given a list of strings and we have to give the output by concatenating the list Let’s look at the previous code what we were doing: Python string = ""lst = ["Geeks", "for", "Geeks"]for i in lst: string += iprint(string) This method of joining a list of strings is definitely not the best method because a new string will be created every time the loop is run. Python lst = ["Geeks", "for", "Geeks"]string = ''.join(lst)print(string) Using join() function is memory efficient as well as handy to write which definitely proves to be the advantages over the previous code. Individually these functions might look innocent but will definitely come in handy in a TIME LIMITED CODING ENVIRONMENT in the sense that they offer large functionality in a VERY short amount of code. The functionalities discussed have very specific applications and act like a SHORTCUT or a CHEAT-SHEET in competitive coding. Having these useful tricks up your sleeve might just give someone the COMPETITIVE EDGE that they were looking for !!This article is contributed by Siddhant Bajaj. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. chaudhary_19 nidhi_biet adnanirshad158 reenadevi98412200 nikhatkhan11 joshuaesvin312 Competitive Programming Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming Bits manipulation (Important tactics) What is Competitive Programming and How to Prepare for It? Count of strings whose prefix match with the given string to a given length k Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Jun, 2022" }, { "code": null, "e": 354, "s": 52, "text": "Python is one such programming language that makes everything easier and straight forward. Anyone who has dabbled in python for Competitive Coding gets somewhat addicted to its many features. Here is a list of some of its cool features that I’ve found most useful in a competitive coding environment. " }, { "code": null, "e": 889, "s": 354, "text": "The most_common function of the Counter Package. This is probably the most useful function I’ve ever used and its always at the back of my mind while writing any python code. This function analyses a list/string and helps to return the top n entities in the list/string according to their number of occurrences in descending order where n is a number that is specified by the programmer. The individual entities are returned along with their number of occurrences in a tuple which can easily be referred/printed as and when required. " }, { "code": null, "e": 896, "s": 889, "text": "Python" }, { "code": "# Code to find top 3 elements and their counts# using most_commonfrom collections import Counter arr = [1, 3, 4, 1, 2, 1, 1, 3, 4, 3, 5, 1, 2, 5, 3, 4, 5]counter = Counter(arr)top_three = counter.most_common(3)print(top_three)", "e": 1123, "s": 896, "text": null }, { "code": null, "e": 1131, "s": 1123, "text": "Output:" }, { "code": null, "e": 1156, "s": 1131, "text": "[(1, 5), (3, 4), (4, 3)]" }, { "code": null, "e": 1269, "s": 1156, "text": "The output tuple clearly states that 1 has occurred 5 times, 3 has occurred 4 times, and 4 has occurred 3 times." }, { "code": null, "e": 1463, "s": 1269, "text": "The n-largest/n-smallest function of the heapq Package. This function helps to return the top n smallest/largest elements in any lists and here again n is a number specified by the programmer. " }, { "code": null, "e": 1470, "s": 1463, "text": "Python" }, { "code": "# Python code to find 3 largest and 4 smallest# elements of a list.import heapq grades = [110, 25, 38, 49, 20, 95, 33, 87, 80, 90]print(heapq.nlargest(3, grades))print(heapq.nsmallest(4, grades))", "e": 1666, "s": 1470, "text": null }, { "code": null, "e": 1675, "s": 1666, "text": "Output: " }, { "code": null, "e": 1706, "s": 1675, "text": "[110, 95, 90]\n[20, 25, 33, 38]" }, { "code": null, "e": 2090, "s": 1706, "text": "The first line of output gives 3 of the largest numbers present in the list grades. Similarly the second line of output prints out 4 of the smallest elements present in the list grades. Another speciality of this function is that it does not overlook repetitions. So in place of n if we were to place the length of the array the we would end up with the entire sorted array itself !!" }, { "code": null, "e": 2590, "s": 2090, "text": "Dictionary and concept of zipping Dictionaries Dictionaries in python are truly fascinating in terms of the unique functionality that they offer. They are stored as a Key and Value pair in the form of an array like structure. Each value can be accessed by its corresponding key. The zip function is used to join two lists together or we can even join the key and value pairs in a dictionary together as a single list. The application of this concept will be made clear in the following code snippet." }, { "code": null, "e": 2597, "s": 2590, "text": "Python" }, { "code": "# Python code to demonstrate use of zip.import heapq stocks = { 'Goog' : 520.54, 'FB' : 76.45, 'yhoo' : 39.28, 'AMZN' : 306.21, 'APPL' : 99.76 } zipped_1 = zip(stocks.values(), stocks.keys()) # sorting according to valuesprint(sorted(zipped_1)) zipped_2 = zip(stocks.keys(), stocks.values())print(sorted(zipped_2))#sorting according to keys", "e": 2956, "s": 2597, "text": null }, { "code": null, "e": 2965, "s": 2956, "text": "Output: " }, { "code": null, "e": 3137, "s": 2965, "text": "[(39.28, 'yhoo'), (76.45, 'FB'), (99.76, 'APPL'), (306.21, 'AMZN'), (520.54, 'Goog')]\n[('AMZN', 306.21), ('APPL', 99.76), ('FB', 76.45), ('Goog', 520.54), ('yhoo', 39.28)]" }, { "code": null, "e": 3487, "s": 3137, "text": "The Map function. This function is a sneaky little shortcut that allows us to implement a simple function on a list of values in a very Unconventional Manner. The following example will give a simple application of this functionality. The function takes as parameters the function name and the name of the list the function needs to be applied upon." }, { "code": null, "e": 3494, "s": 3487, "text": "Python" }, { "code": "# Python code to apply a function on a listincome = [10, 30, 75] def double_money(dollars): return dollars * 2 new_income = list(map(double_money, income))print(new_income)", "e": 3670, "s": 3494, "text": null }, { "code": null, "e": 3679, "s": 3670, "text": "Output: " }, { "code": null, "e": 3693, "s": 3679, "text": "[20, 60, 150]" }, { "code": null, "e": 3807, "s": 3693, "text": "Here, we just implemented a simple function which multiplies each list value by two and returns it as a new list." }, { "code": null, "e": 3994, "s": 3807, "text": "Concatenation of list of strings Suppose we have been given a list of strings and we have to give the output by concatenating the list Let’s look at the previous code what we were doing:" }, { "code": null, "e": 4001, "s": 3994, "text": "Python" }, { "code": "string = \"\"lst = [\"Geeks\", \"for\", \"Geeks\"]for i in lst: string += iprint(string)", "e": 4085, "s": 4001, "text": null }, { "code": null, "e": 4225, "s": 4085, "text": "This method of joining a list of strings is definitely not the best method because a new string will be created every time the loop is run." }, { "code": null, "e": 4232, "s": 4225, "text": "Python" }, { "code": "lst = [\"Geeks\", \"for\", \"Geeks\"]string = ''.join(lst)print(string)", "e": 4298, "s": 4232, "text": null }, { "code": null, "e": 4435, "s": 4298, "text": "Using join() function is memory efficient as well as handy to write which definitely proves to be the advantages over the previous code." }, { "code": null, "e": 5303, "s": 4435, "text": "Individually these functions might look innocent but will definitely come in handy in a TIME LIMITED CODING ENVIRONMENT in the sense that they offer large functionality in a VERY short amount of code. The functionalities discussed have very specific applications and act like a SHORTCUT or a CHEAT-SHEET in competitive coding. Having these useful tricks up your sleeve might just give someone the COMPETITIVE EDGE that they were looking for !!This article is contributed by Siddhant Bajaj. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above." }, { "code": null, "e": 5316, "s": 5303, "text": "chaudhary_19" }, { "code": null, "e": 5327, "s": 5316, "text": "nidhi_biet" }, { "code": null, "e": 5342, "s": 5327, "text": "adnanirshad158" }, { "code": null, "e": 5360, "s": 5342, "text": "reenadevi98412200" }, { "code": null, "e": 5373, "s": 5360, "text": "nikhatkhan11" }, { "code": null, "e": 5388, "s": 5373, "text": "joshuaesvin312" }, { "code": null, "e": 5412, "s": 5388, "text": "Competitive Programming" }, { "code": null, "e": 5419, "s": 5412, "text": "Python" }, { "code": null, "e": 5517, "s": 5419, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5544, "s": 5517, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 5622, "s": 5544, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 5660, "s": 5622, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 5719, "s": 5660, "text": "What is Competitive Programming and How to Prepare for It?" }, { "code": null, "e": 5797, "s": 5719, "text": "Count of strings whose prefix match with the given string to a given length k" }, { "code": null, "e": 5825, "s": 5797, "text": "Read JSON file using Python" }, { "code": null, "e": 5875, "s": 5825, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 5897, "s": 5875, "text": "Python map() function" }, { "code": null, "e": 5915, "s": 5897, "text": "Python Dictionary" } ]
Time complexities of different data structures
13 Jun, 2022 Time Complexity is a concept in computer science that deals with the quantification of the amount of time taken by a set of code or algorithm to process or run as a function of the amount of input. In other words, the time complexity is how long a program takes to process a given input. The efficiency of an algorithm depends on two parameters: Time Complexity Space Complexity Time Complexity: It is defined as the number of times a particular instruction set is executed rather than the total time is taken. It is because the total time took also depends on some external factors like the compiler used, processor’s speed, etc. Space Complexity: It is the total memory space required by the program for its execution. meetgandhi3 pallavimahajan1102 time complexity Analysis Articles Data Structures Difference Between Data Structures Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexity and Space Complexity Analysis of different sorting techniques Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Difference between NP hard and NP complete problem Tree Traversals (Inorder, Preorder and Postorder) SQL | Join (Inner, Left, Right and Full Joins) find command in Linux with examples Time Complexity and Space Complexity Understanding "extern" keyword in C
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 398, "s": 52, "text": "Time Complexity is a concept in computer science that deals with the quantification of the amount of time taken by a set of code or algorithm to process or run as a function of the amount of input. In other words, the time complexity is how long a program takes to process a given input. The efficiency of an algorithm depends on two parameters:" }, { "code": null, "e": 414, "s": 398, "text": "Time Complexity" }, { "code": null, "e": 431, "s": 414, "text": "Space Complexity" }, { "code": null, "e": 683, "s": 431, "text": "Time Complexity: It is defined as the number of times a particular instruction set is executed rather than the total time is taken. It is because the total time took also depends on some external factors like the compiler used, processor’s speed, etc." }, { "code": null, "e": 773, "s": 683, "text": "Space Complexity: It is the total memory space required by the program for its execution." }, { "code": null, "e": 785, "s": 773, "text": "meetgandhi3" }, { "code": null, "e": 804, "s": 785, "text": "pallavimahajan1102" }, { "code": null, "e": 820, "s": 804, "text": "time complexity" }, { "code": null, "e": 829, "s": 820, "text": "Analysis" }, { "code": null, "e": 838, "s": 829, "text": "Articles" }, { "code": null, "e": 854, "s": 838, "text": "Data Structures" }, { "code": null, "e": 873, "s": 854, "text": "Difference Between" }, { "code": null, "e": 889, "s": 873, "text": "Data Structures" }, { "code": null, "e": 987, "s": 889, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1024, "s": 987, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 1065, "s": 1024, "text": "Analysis of different sorting techniques" }, { "code": null, "e": 1148, "s": 1065, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 1215, "s": 1148, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 1266, "s": 1215, "text": "Difference between NP hard and NP complete problem" }, { "code": null, "e": 1316, "s": 1266, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 1363, "s": 1316, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 1399, "s": 1363, "text": "find command in Linux with examples" }, { "code": null, "e": 1436, "s": 1399, "text": "Time Complexity and Space Complexity" } ]
Reorder the position of the words in alphabetical order
07 Jun, 2022 Given an array arr[] of strings, the task is to reorder the strings lexicographically and print their positions in the original list. Examples: Input: arr[] = {“zxc”, “efg”, “jkl”} Output: 2 3 1 The sorted list will be {“efg”, “jkl”, “zxc”} and their original positions were 2, 3 and 1 respectively. Input: arr[] = {“live”, “place”, “travel”, “word”, “sky”} Output: 1 2 5 3 4 Approach: Assign all the words with an integer number equal to their position in the array. Then they sort the list of words lexicographically and their positions are altered, and therefore, their positions are printed starting from the first word in the sorted list. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // CPP implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print the ordering of wordsvoid reArrange(string words[], int n){ // Creating list of words and assigning // them index numbers map<string, int> mp; for (int i = 0; i < n; i++) mp[words[i]] = i + 1; // Sort the list of words // lexicographically sort(words, words + n); // Print the ordering for (int i = 0; i < n; i++) cout << mp[words[i]] << " ";} // Driver Codeint main(){ string words[] = { "live", "place", "travel", "word", "sky" }; int n = sizeof(words) / sizeof(words[0]); reArrange(words, n);} // This code is contributed by// Surendra_Gangwar // Java implementation of the approachimport java.util.*;class GFG { // Function to print the ordering of words static void reArrange(String words[], int n) { // Creating list of words and assigning // them index numbers HashMap<String, Integer> freq = new HashMap<>(); for (int i = 0; i < n; i++) { freq.put(words[i], (i + 1)); } // Sort the list of words // lexicographically Arrays.sort(words); // Print the ordering for (int i = 0; i < n; i++) System.out.print(freq.get(words[i]) + " "); } // Driver Code public static void main(String[] args) { String words[] = { "live", "place", "travel", "word", "sky" }; int n = words.length; reArrange(words, n); }} # Python3 implementation of the approach # Function to print the ordering of wordsdef reArrange(words, n): # Creating list of words and assigning # them index numbers mp = {} for i in range(n): mp[words[i]] = i + 1 # Sort the list of words # lexicographically words.sort(); # Print the ordering for i in range(n): print(mp[words[i]], end = " ") # Driver Code words = [ "live", "place", "travel", "word", "sky" ]n = len(words)reArrange(words, n); # This code is contributed by# Rajnis09 // C# implementation of the approachusing System;using System.Collections.Generic; class GFG { // Function to print the ordering of words static void reArrange(String[] words, int n) { // Creating list of words and assigning // them index numbers Dictionary<String, int> freq = new Dictionary<String, int>(); for (int i = 0; i < n; i++) { freq.Add(words[i], (i + 1)); } // Sort the list of words // lexicographically Array.Sort(words); // Print the ordering for (int i = 0; i < n; i++) Console.Write(freq[words[i]] + " "); } // Driver Code public static void Main(String[] args) { String[] words = { "live", "place", "travel", "word", "sky" }; int n = words.Length; reArrange(words, n); }} // This code contributed by Rajput-Ji <?php// PHP implementation of the approach // Function to print the ordering of words function reArrange($words, $n) { // Creating list of words and assigning // them index numbers $freq = array(); for ($i = 0; $i < $n; $i++) { $freq[$words[$i]] = ($i + 1) ; } // Sort the list of words // lexicographically sort($words); // Print the ordering for ($i = 0; $i < $n; $i++) echo $freq[$words[$i]], " " ; } // Driver Code $words = array( "live", "place", "travel", "word", "sky" ); $n = count($words); reArrange($words, $n); // This code is contributed by Ryuga?> <script> // Javascript implementation of the approach // Function to print the ordering of wordsfunction reArrange(words, n){ // Creating list of words and assigning // them index numbers var mp = new Map(); for (var i = 0; i < n; i++) mp.set(words[i], i + 1); // Sort the list of words // lexicographically words.sort(); // Print the ordering for (var i = 0; i < n; i++) { document.write(mp.get(words[i])+" "); }} // Driver Codevar words = ["live", "place", "travel", "word", "sky"];var n = words.length;reArrange(words, n); </script> 1 2 5 3 4 Time Complexity: O(n * log n) Auxiliary Space: O(n) ankthon Rajput-Ji SURENDRA_GANGWAR Rajnis09 rrrtnx vansikasharma1329 lexicographic-ordering Arrays Mathematical School Programming Sorting Strings Arrays Strings Mathematical Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jun, 2022" }, { "code": null, "e": 163, "s": 28, "text": "Given an array arr[] of strings, the task is to reorder the strings lexicographically and print their positions in the original list. " }, { "code": null, "e": 174, "s": 163, "text": "Examples: " }, { "code": null, "e": 331, "s": 174, "text": "Input: arr[] = {“zxc”, “efg”, “jkl”} Output: 2 3 1 The sorted list will be {“efg”, “jkl”, “zxc”} and their original positions were 2, 3 and 1 respectively. " }, { "code": null, "e": 409, "s": 331, "text": "Input: arr[] = {“live”, “place”, “travel”, “word”, “sky”} Output: 1 2 5 3 4 " }, { "code": null, "e": 677, "s": 409, "text": "Approach: Assign all the words with an integer number equal to their position in the array. Then they sort the list of words lexicographically and their positions are altered, and therefore, their positions are printed starting from the first word in the sorted list." }, { "code": null, "e": 729, "s": 677, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 733, "s": 729, "text": "C++" }, { "code": null, "e": 738, "s": 733, "text": "Java" }, { "code": null, "e": 746, "s": 738, "text": "Python3" }, { "code": null, "e": 749, "s": 746, "text": "C#" }, { "code": null, "e": 753, "s": 749, "text": "PHP" }, { "code": null, "e": 764, "s": 753, "text": "Javascript" }, { "code": "// CPP implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print the ordering of wordsvoid reArrange(string words[], int n){ // Creating list of words and assigning // them index numbers map<string, int> mp; for (int i = 0; i < n; i++) mp[words[i]] = i + 1; // Sort the list of words // lexicographically sort(words, words + n); // Print the ordering for (int i = 0; i < n; i++) cout << mp[words[i]] << \" \";} // Driver Codeint main(){ string words[] = { \"live\", \"place\", \"travel\", \"word\", \"sky\" }; int n = sizeof(words) / sizeof(words[0]); reArrange(words, n);} // This code is contributed by// Surendra_Gangwar", "e": 1467, "s": 764, "text": null }, { "code": "// Java implementation of the approachimport java.util.*;class GFG { // Function to print the ordering of words static void reArrange(String words[], int n) { // Creating list of words and assigning // them index numbers HashMap<String, Integer> freq = new HashMap<>(); for (int i = 0; i < n; i++) { freq.put(words[i], (i + 1)); } // Sort the list of words // lexicographically Arrays.sort(words); // Print the ordering for (int i = 0; i < n; i++) System.out.print(freq.get(words[i]) + \" \"); } // Driver Code public static void main(String[] args) { String words[] = { \"live\", \"place\", \"travel\", \"word\", \"sky\" }; int n = words.length; reArrange(words, n); }}", "e": 2268, "s": 1467, "text": null }, { "code": "# Python3 implementation of the approach # Function to print the ordering of wordsdef reArrange(words, n): # Creating list of words and assigning # them index numbers mp = {} for i in range(n): mp[words[i]] = i + 1 # Sort the list of words # lexicographically words.sort(); # Print the ordering for i in range(n): print(mp[words[i]], end = \" \") # Driver Code words = [ \"live\", \"place\", \"travel\", \"word\", \"sky\" ]n = len(words)reArrange(words, n); # This code is contributed by# Rajnis09", "e": 2797, "s": 2268, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG { // Function to print the ordering of words static void reArrange(String[] words, int n) { // Creating list of words and assigning // them index numbers Dictionary<String, int> freq = new Dictionary<String, int>(); for (int i = 0; i < n; i++) { freq.Add(words[i], (i + 1)); } // Sort the list of words // lexicographically Array.Sort(words); // Print the ordering for (int i = 0; i < n; i++) Console.Write(freq[words[i]] + \" \"); } // Driver Code public static void Main(String[] args) { String[] words = { \"live\", \"place\", \"travel\", \"word\", \"sky\" }; int n = words.Length; reArrange(words, n); }} // This code contributed by Rajput-Ji", "e": 3667, "s": 2797, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to print the ordering of words function reArrange($words, $n) { // Creating list of words and assigning // them index numbers $freq = array(); for ($i = 0; $i < $n; $i++) { $freq[$words[$i]] = ($i + 1) ; } // Sort the list of words // lexicographically sort($words); // Print the ordering for ($i = 0; $i < $n; $i++) echo $freq[$words[$i]], \" \" ; } // Driver Code $words = array( \"live\", \"place\", \"travel\", \"word\", \"sky\" ); $n = count($words); reArrange($words, $n); // This code is contributed by Ryuga?>", "e": 4364, "s": 3667, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to print the ordering of wordsfunction reArrange(words, n){ // Creating list of words and assigning // them index numbers var mp = new Map(); for (var i = 0; i < n; i++) mp.set(words[i], i + 1); // Sort the list of words // lexicographically words.sort(); // Print the ordering for (var i = 0; i < n; i++) { document.write(mp.get(words[i])+\" \"); }} // Driver Codevar words = [\"live\", \"place\", \"travel\", \"word\", \"sky\"];var n = words.length;reArrange(words, n); </script>", "e": 4951, "s": 4364, "text": null }, { "code": null, "e": 4961, "s": 4951, "text": "1 2 5 3 4" }, { "code": null, "e": 4993, "s": 4963, "text": "Time Complexity: O(n * log n)" }, { "code": null, "e": 5015, "s": 4993, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 5023, "s": 5015, "text": "ankthon" }, { "code": null, "e": 5033, "s": 5023, "text": "Rajput-Ji" }, { "code": null, "e": 5050, "s": 5033, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 5059, "s": 5050, "text": "Rajnis09" }, { "code": null, "e": 5066, "s": 5059, "text": "rrrtnx" }, { "code": null, "e": 5084, "s": 5066, "text": "vansikasharma1329" }, { "code": null, "e": 5107, "s": 5084, "text": "lexicographic-ordering" }, { "code": null, "e": 5114, "s": 5107, "text": "Arrays" }, { "code": null, "e": 5127, "s": 5114, "text": "Mathematical" }, { "code": null, "e": 5146, "s": 5127, "text": "School Programming" }, { "code": null, "e": 5154, "s": 5146, "text": "Sorting" }, { "code": null, "e": 5162, "s": 5154, "text": "Strings" }, { "code": null, "e": 5169, "s": 5162, "text": "Arrays" }, { "code": null, "e": 5177, "s": 5169, "text": "Strings" }, { "code": null, "e": 5190, "s": 5177, "text": "Mathematical" }, { "code": null, "e": 5198, "s": 5190, "text": "Sorting" } ]
SQL Query to Update All Columns in a Table
14 Nov, 2021 In SQL, sometimes we need to write a single query to update the values of all columns in a table. We will use the UPDATE keyword to achieve this. For this, we use a specific kind of query shown in the below demonstration. For this article, we will be using the Microsoft SQL Server as our database and Select keyword. Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks. Query: CREATE DATABASE GeeksForGeeks Output: Step 2: Use the GeeksForGeeks database. For this use the below command. Query: USE GeeksForGeeks Output: Step 3: Create a table of SALARY inside the database GeeksForGeeks. This table has 2 columns namely MONTHLY_SALARY and ANNUAL_SALARY containing the monthly and annual salaries of the workers in a factory. Query: CREATE TABLE SALARY( MONTHLY_SALARY INT, ANNUAL_SALARY INT); Output: Step 4: Describe the structure of the table SALARY. Query: EXEC SP_COLUMNS SALARY; Output: Step 5: Insert 5 rows into the SALARY table. Query: INSERT INTO SALARY VALUES(10000,120000); INSERT INTO SALARY VALUES(20000,240000); INSERT INTO SALARY VALUES(15000,180000); INSERT INTO SALARY VALUES(30000,360000); INSERT INTO SALARY VALUES(25000,300000); Output: Step 6: Display all the rows of the SALARY table. Query: SELECT * FROM SALARY; Output: Step 7: Update all the columns of the table SALARY. Increase the value of all entries of the MONTHLY_SALARY column by 1000, accordingly, increase the value of all entries of the ANNUAL_SALARY column by 12*1000=12000. Syntax: UPDATE TABLE_NAME SET COLUMN1=VALUE1, COLUMN2 = VALUE2; Query: UPDATE SALARY SET MONTHLY_SALARY = MONTHLY_SALARY+1000,ANNUAL_SALARY= ANNUAL_SALARY+12000; Output: Step 8: Display all the rows of the updated SALARY table. Query: SELECT * FROM SALARY; Output: Picked SQL-Query SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Nov, 2021" }, { "code": null, "e": 373, "s": 54, "text": "In SQL, sometimes we need to write a single query to update the values of all columns in a table. We will use the UPDATE keyword to achieve this. For this, we use a specific kind of query shown in the below demonstration. For this article, we will be using the Microsoft SQL Server as our database and Select keyword. " }, { "code": null, "e": 473, "s": 373, "text": "Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks." }, { "code": null, "e": 480, "s": 473, "text": "Query:" }, { "code": null, "e": 510, "s": 480, "text": "CREATE DATABASE GeeksForGeeks" }, { "code": null, "e": 518, "s": 510, "text": "Output:" }, { "code": null, "e": 590, "s": 518, "text": "Step 2: Use the GeeksForGeeks database. For this use the below command." }, { "code": null, "e": 597, "s": 590, "text": "Query:" }, { "code": null, "e": 615, "s": 597, "text": "USE GeeksForGeeks" }, { "code": null, "e": 623, "s": 615, "text": "Output:" }, { "code": null, "e": 828, "s": 623, "text": "Step 3: Create a table of SALARY inside the database GeeksForGeeks. This table has 2 columns namely MONTHLY_SALARY and ANNUAL_SALARY containing the monthly and annual salaries of the workers in a factory." }, { "code": null, "e": 835, "s": 828, "text": "Query:" }, { "code": null, "e": 896, "s": 835, "text": "CREATE TABLE SALARY(\nMONTHLY_SALARY INT,\nANNUAL_SALARY INT);" }, { "code": null, "e": 904, "s": 896, "text": "Output:" }, { "code": null, "e": 956, "s": 904, "text": "Step 4: Describe the structure of the table SALARY." }, { "code": null, "e": 963, "s": 956, "text": "Query:" }, { "code": null, "e": 987, "s": 963, "text": "EXEC SP_COLUMNS SALARY;" }, { "code": null, "e": 995, "s": 987, "text": "Output:" }, { "code": null, "e": 1040, "s": 995, "text": "Step 5: Insert 5 rows into the SALARY table." }, { "code": null, "e": 1047, "s": 1040, "text": "Query:" }, { "code": null, "e": 1252, "s": 1047, "text": "INSERT INTO SALARY VALUES(10000,120000);\nINSERT INTO SALARY VALUES(20000,240000);\nINSERT INTO SALARY VALUES(15000,180000);\nINSERT INTO SALARY VALUES(30000,360000);\nINSERT INTO SALARY VALUES(25000,300000);" }, { "code": null, "e": 1260, "s": 1252, "text": "Output:" }, { "code": null, "e": 1310, "s": 1260, "text": "Step 6: Display all the rows of the SALARY table." }, { "code": null, "e": 1317, "s": 1310, "text": "Query:" }, { "code": null, "e": 1339, "s": 1317, "text": "SELECT * FROM SALARY;" }, { "code": null, "e": 1347, "s": 1339, "text": "Output:" }, { "code": null, "e": 1564, "s": 1347, "text": "Step 7: Update all the columns of the table SALARY. Increase the value of all entries of the MONTHLY_SALARY column by 1000, accordingly, increase the value of all entries of the ANNUAL_SALARY column by 12*1000=12000." }, { "code": null, "e": 1572, "s": 1564, "text": "Syntax:" }, { "code": null, "e": 1628, "s": 1572, "text": "UPDATE TABLE_NAME SET COLUMN1=VALUE1,\nCOLUMN2 = VALUE2;" }, { "code": null, "e": 1635, "s": 1628, "text": "Query:" }, { "code": null, "e": 1727, "s": 1635, "text": "UPDATE SALARY SET MONTHLY_SALARY = \nMONTHLY_SALARY+1000,ANNUAL_SALARY=\nANNUAL_SALARY+12000;" }, { "code": null, "e": 1735, "s": 1727, "text": "Output:" }, { "code": null, "e": 1793, "s": 1735, "text": "Step 8: Display all the rows of the updated SALARY table." }, { "code": null, "e": 1800, "s": 1793, "text": "Query:" }, { "code": null, "e": 1822, "s": 1800, "text": "SELECT * FROM SALARY;" }, { "code": null, "e": 1830, "s": 1822, "text": "Output:" }, { "code": null, "e": 1837, "s": 1830, "text": "Picked" }, { "code": null, "e": 1847, "s": 1837, "text": "SQL-Query" }, { "code": null, "e": 1858, "s": 1847, "text": "SQL-Server" }, { "code": null, "e": 1862, "s": 1858, "text": "SQL" }, { "code": null, "e": 1866, "s": 1862, "text": "SQL" } ]
How to create a DataFrame from given vectors in R ?
24 Mar, 2022 In this article we will see how to create a Dataframe from four given vectors in R. To create a data frame in R using the vector, we must first have a series of vectors containing data. The data.frame() function is used to create a data frame from vector in R. Syntax: data.frame(vectors) Example 1. Creating dataframe from given 4 vectors. R # creating a vector with some valueid = c(1, 2, 3) # creating another vector with some valuename = c("karthik" , "nikhil" , "sravan") # creating another vector with some valuebranch = c("IT" , "CSE" , "IT") # creating another vector with some value.favourite_subject = c("SE" ,"DAA" , "OS") # passing the vectors into data.frame() function# as parametersdf1=data.frame(id, name, branch, favourite_subject) # printing the data frame.print(df1) Output: Example 2: R # creating a vector 1 with some valuesfaculty_id = c(247, 143, 01768) # creating a vector 2 with some valuesfaculty_name=c("Subbarao", "praveen kumar", "sujatha") # creating vector 3 with some valuesdesignation=c("accociate professor", "assistant professor", "accosiate professor") # creating vector 4 with some datasalary = c(60000, 50000, 60000) # passing the vectors to the data.frame() functiondf3 = data.frame(faculty_id, faculty_name, designation,salary) # printing the data frame created with 4 vectorsprint(df3) Output: surindertarika1234 surinderdawra388 Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R Merge DataFrames by Column Names in R How to Sort a DataFrame in R ?
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Mar, 2022" }, { "code": null, "e": 289, "s": 28, "text": "In this article we will see how to create a Dataframe from four given vectors in R. To create a data frame in R using the vector, we must first have a series of vectors containing data. The data.frame() function is used to create a data frame from vector in R." }, { "code": null, "e": 297, "s": 289, "text": "Syntax:" }, { "code": null, "e": 317, "s": 297, "text": "data.frame(vectors)" }, { "code": null, "e": 369, "s": 317, "text": "Example 1. Creating dataframe from given 4 vectors." }, { "code": null, "e": 371, "s": 369, "text": "R" }, { "code": "# creating a vector with some valueid = c(1, 2, 3) # creating another vector with some valuename = c(\"karthik\" , \"nikhil\" , \"sravan\") # creating another vector with some valuebranch = c(\"IT\" , \"CSE\" , \"IT\") # creating another vector with some value.favourite_subject = c(\"SE\" ,\"DAA\" , \"OS\") # passing the vectors into data.frame() function# as parametersdf1=data.frame(id, name, branch, favourite_subject) # printing the data frame.print(df1)", "e": 814, "s": 371, "text": null }, { "code": null, "e": 822, "s": 814, "text": "Output:" }, { "code": null, "e": 833, "s": 822, "text": "Example 2:" }, { "code": null, "e": 835, "s": 833, "text": "R" }, { "code": "# creating a vector 1 with some valuesfaculty_id = c(247, 143, 01768) # creating a vector 2 with some valuesfaculty_name=c(\"Subbarao\", \"praveen kumar\", \"sujatha\") # creating vector 3 with some valuesdesignation=c(\"accociate professor\", \"assistant professor\", \"accosiate professor\") # creating vector 4 with some datasalary = c(60000, 50000, 60000) # passing the vectors to the data.frame() functiondf3 = data.frame(faculty_id, faculty_name, designation,salary) # printing the data frame created with 4 vectorsprint(df3)", "e": 1368, "s": 835, "text": null }, { "code": null, "e": 1376, "s": 1368, "text": "Output:" }, { "code": null, "e": 1395, "s": 1376, "text": "surindertarika1234" }, { "code": null, "e": 1412, "s": 1395, "text": "surinderdawra388" }, { "code": null, "e": 1419, "s": 1412, "text": "Picked" }, { "code": null, "e": 1440, "s": 1419, "text": "R DataFrame-Programs" }, { "code": null, "e": 1452, "s": 1440, "text": "R-DataFrame" }, { "code": null, "e": 1463, "s": 1452, "text": "R Language" }, { "code": null, "e": 1474, "s": 1463, "text": "R Programs" }, { "code": null, "e": 1572, "s": 1474, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1624, "s": 1572, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1682, "s": 1624, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1717, "s": 1682, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1755, "s": 1717, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 1804, "s": 1755, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 1862, "s": 1804, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1911, "s": 1862, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 1954, "s": 1911, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 1992, "s": 1954, "text": "Merge DataFrames by Column Names in R" } ]
Create a Scatter Plot with Multiple Groups using ggplot2 in R - GeeksforGeeks
24 Oct, 2021 In this article, we will discuss how to create a scatter plot with multiple groups in R Programming Language. Geoms can be added to the plot to compute various graphical representations of the data in the plot (points, lines, bars). The geom_point() method is used to create scatter plots in R. The geoms may also be specified with the additional mappings, like color to differently color the points pertaining to different groups. geom_point(aes(color = )) R library("ggplot2") # creating a data framedf < - data.frame(col1=sample(rep(c(1: 5), each=3)), col2=5: 19)print("original dataframe")print(df) # plotting the dataggplot(df, aes(x=col1, y=col2)) +geom_point(aes(color=factor(col1))) Output [1] "original dataframe" col1 col2 1 2 5 2 3 6 3 4 7 4 2 8 5 4 9 6 1 10 7 3 11 8 5 12 9 5 13 10 5 14 11 4 15 12 1 16 13 3 17 14 2 18 15 1 19 Explanation: The groups are created according to the differences in values of col1. All the circles, for example, belonging to col1=1 are given the red color. This is also illustrated in the index of the plot. The following code snippet indicates the method where one of the data frame columns is a non-integral one : Python3 library("ggplot2") # creating a data framedf < - data.frame(col1=sample(rep(c(1: 5), each=3)), col2=letters[5:19]) print("original dataframe")print(df) # plotting the dataggplot(df, aes(x=col1, y=col2)) +geom_point(aes(color=factor(col1))) Output [1] "original dataframe" col1 col2 1 2 e 2 2 f 3 4 g 4 3 h 5 5 i 6 1 j 7 5 k 8 4 l 9 1 m 10 2 n 11 1 o 12 3 p 13 5 q 14 3 r 15 4 s Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to import an Excel File into R ? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? How to change the order of bars in bar chart in R ? R - if statement Replace Specific Characters in String in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n24 Oct, 2021" }, { "code": null, "e": 25352, "s": 25242, "text": "In this article, we will discuss how to create a scatter plot with multiple groups in R Programming Language." }, { "code": null, "e": 25675, "s": 25352, "text": "Geoms can be added to the plot to compute various graphical representations of the data in the plot (points, lines, bars). The geom_point() method is used to create scatter plots in R. The geoms may also be specified with the additional mappings, like color to differently color the points pertaining to different groups. " }, { "code": null, "e": 25701, "s": 25675, "text": "geom_point(aes(color = ))" }, { "code": null, "e": 25703, "s": 25701, "text": "R" }, { "code": "library(\"ggplot2\") # creating a data framedf < - data.frame(col1=sample(rep(c(1: 5), each=3)), col2=5: 19)print(\"original dataframe\")print(df) # plotting the dataggplot(df, aes(x=col1, y=col2)) +geom_point(aes(color=factor(col1)))", "e": 25955, "s": 25703, "text": null }, { "code": null, "e": 25962, "s": 25955, "text": "Output" }, { "code": null, "e": 26208, "s": 25962, "text": "[1] \"original dataframe\" \ncol1 col2 \n1 2 5 \n2 3 6 \n3 4 7 \n4 2 8 \n5 4 9 \n6 1 10 \n7 3 11 \n8 5 12 \n9 5 13 \n10 5 14 \n11 4 15 \n12 1 16 \n13 3 17 \n14 2 18 \n15 1 19" }, { "code": null, "e": 26419, "s": 26208, "text": "Explanation: The groups are created according to the differences in values of col1. All the circles, for example, belonging to col1=1 are given the red color. This is also illustrated in the index of the plot. " }, { "code": null, "e": 26528, "s": 26419, "text": "The following code snippet indicates the method where one of the data frame columns is a non-integral one : " }, { "code": null, "e": 26536, "s": 26528, "text": "Python3" }, { "code": "library(\"ggplot2\") # creating a data framedf < - data.frame(col1=sample(rep(c(1: 5), each=3)), col2=letters[5:19]) print(\"original dataframe\")print(df) # plotting the dataggplot(df, aes(x=col1, y=col2)) +geom_point(aes(color=factor(col1)))", "e": 26796, "s": 26536, "text": null }, { "code": null, "e": 26803, "s": 26796, "text": "Output" }, { "code": null, "e": 27049, "s": 26803, "text": "[1] \"original dataframe\" \ncol1 col2 \n1 2 e \n2 2 f \n3 4 g \n4 3 h \n5 5 i \n6 1 j \n7 5 k \n8 4 l \n9 1 m \n10 2 n \n11 1 o \n12 3 p \n13 5 q \n14 3 r \n15 4 s" }, { "code": null, "e": 27056, "s": 27049, "text": "Picked" }, { "code": null, "e": 27065, "s": 27056, "text": "R-ggplot" }, { "code": null, "e": 27076, "s": 27065, "text": "R Language" }, { "code": null, "e": 27174, "s": 27076, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27183, "s": 27174, "text": "Comments" }, { "code": null, "e": 27196, "s": 27183, "text": "Old Comments" }, { "code": null, "e": 27248, "s": 27196, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27286, "s": 27248, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27321, "s": 27286, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27379, "s": 27321, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27416, "s": 27379, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 27465, "s": 27416, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27515, "s": 27465, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27567, "s": 27515, "text": "How to change the order of bars in bar chart in R ?" }, { "code": null, "e": 27584, "s": 27567, "text": "R - if statement" } ]
Find maximum element of each row in a matrix in C++
Consider we have a matrix, our task is to find the maximum element of each row of that matrix and print them. This task is simple. For each row, reset the max, and find the max element, and print it. Let us see the code for better understanding. #include<iostream> #define MAX 10 using namespace std; void largestInEachRow(int mat[][MAX], int rows, int cols) { for (int i = 0; i < rows; i++) { int max_row_element = mat[i][0]; for (int j = 1; j < cols; j++) { if (mat[i][j] > max_row_element) max_row_element = mat[i][j]; } cout << max_row_element << endl; } } int main() { int row = 4, col = 4; int mat[][MAX] = { { 3, 4, 1, 81 }, { 1, 84, 9, 11 }, { 23, 7, 21, 1 }, { 2, 1, 44, 5 } }; largestInEachRow(mat, row, col); } 81 84 23 44
[ { "code": null, "e": 1308, "s": 1062, "text": "Consider we have a matrix, our task is to find the maximum element of each row of that matrix and print them. This task is simple. For each row, reset the max, and find the max element, and print it. Let us see the code for better understanding." }, { "code": null, "e": 1847, "s": 1308, "text": "#include<iostream>\n#define MAX 10\nusing namespace std;\nvoid largestInEachRow(int mat[][MAX], int rows, int cols) {\n for (int i = 0; i < rows; i++) {\n int max_row_element = mat[i][0];\n for (int j = 1; j < cols; j++) {\n if (mat[i][j] > max_row_element)\n max_row_element = mat[i][j];\n }\n cout << max_row_element << endl;\n}\n}\nint main() {\n int row = 4, col = 4;\n int mat[][MAX] = { { 3, 4, 1, 81 },\n { 1, 84, 9, 11 },\n { 23, 7, 21, 1 },\n { 2, 1, 44, 5 }\n };\n largestInEachRow(mat, row, col);\n}" }, { "code": null, "e": 1859, "s": 1847, "text": "81\n84\n23\n44" } ]
Bootstrap Event when the modal is fully shown
The shown.bs.modal event in Bootstrap fires when the modal is completely displayed. The modal is displayed using the modal(show) method − $("#button1").click(function(){ $("#newModal").modal("show"); }); Fire shown.bs.modal event and generate the alert as shown below − $("#newModal").on('shown.bs.modal', function () { alert('The modal is displayed completely!'); }); You can try to run the following code to implement the shown.bs.modal event in Bootstrap − Live Demo <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2>Entrance Exams</h2> <p>The following is the result of the entrance exams:</p> <button type="button" class="btn btn-default btn-lg" id="button1">Result</button> <div class="modal fade" id="newModal" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 class="modal-title">Selected Students</h4> </div> <div class="modal-body"> <p>Rahul, Amit and Shweta cleared the exam.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> <script> $(document).ready(function(){ $("#button1").click(function(){ $("#newModal").modal("show"); }); $("#newModal").on('shown.bs.modal', function () { alert('The modal is displayed completely!'); }); }); </script> </body> </html>
[ { "code": null, "e": 1146, "s": 1062, "text": "The shown.bs.modal event in Bootstrap fires when the modal is completely displayed." }, { "code": null, "e": 1200, "s": 1146, "text": "The modal is displayed using the modal(show) method −" }, { "code": null, "e": 1268, "s": 1200, "text": "$(\"#button1\").click(function(){\n $(\"#newModal\").modal(\"show\");\n});" }, { "code": null, "e": 1334, "s": 1268, "text": "Fire shown.bs.modal event and generate the alert as shown below −" }, { "code": null, "e": 1435, "s": 1334, "text": "$(\"#newModal\").on('shown.bs.modal', function () {\n alert('The modal is displayed completely!');\n});" }, { "code": null, "e": 1526, "s": 1435, "text": "You can try to run the following code to implement the shown.bs.modal event in Bootstrap −" }, { "code": null, "e": 1536, "s": 1526, "text": "Live Demo" }, { "code": null, "e": 3107, "s": 1536, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script>\n </head>\n<body>\n <div class=\"container\">\n <h2>Entrance Exams</h2> \n <p>The following is the result of the entrance exams:</p>\n <button type=\"button\" class=\"btn btn-default btn-lg\" id=\"button1\">Result</button>\n <div class=\"modal fade\" id=\"newModal\" role=\"dialog\">\n <div class=\"modal-dialog\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\">×</button>\n <h4 class=\"modal-title\">Selected Students</h4>\n </div>\n <div class=\"modal-body\">\n <p>Rahul, Amit and Shweta cleared the exam.</p>\n </div>\n <div class=\"modal-footer\">\n <button type=\"button\" class=\"btn btn-primary\" data-dismiss=\"modal\">Close</button>\n </div>\n </div>\n </div>\n </div>\n</div>\n\n<script>\n$(document).ready(function(){\n $(\"#button1\").click(function(){\n $(\"#newModal\").modal(\"show\");\n });\n $(\"#newModal\").on('shown.bs.modal', function () {\n alert('The modal is displayed completely!');\n });\n});\n</script>\n\n</body>\n</html>" } ]