title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
MS SQL Server - Create Database
Database is a collection of objects such as table, view, stored procedure, function, trigger, etc. In MS SQL Server, two types of databases are available. System databases User Databases System databases are created automatically when we install MS SQL Server. Following is a list of system databases − Master Model MSDB Tempdb Resource (Introduced in 2005 version) Distribution (It’s for Replication feature only) User databases are created by users (Administrators, developers, and testers who have access to create databases). Following methods are used to create user database. Following is the basic syntax for creating database in MS SQL Server. Create database <yourdatabasename> OR Restore Database <Your database name> from disk = '<Backup file location + file name> To create database called ‘Testdb’, run the following query. Create database Testdb OR Restore database Testdb from disk = 'D:\Backup\Testdb_full_backup.bak' Note − D:\backup is location of backup file and Testdb_full_backup.bak is the backup file name Connect to SQL Server instance and right-click on the databases folder. Click on new database and the following screen will appear. Enter the database name field with your database name (example: to create database with the name ‘Testdb’) and click OK. Testdb database will be created as shown in the following snapshot. 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": 2334, "s": 2235, "text": "Database is a collection of objects such as table, view, stored procedure, function, trigger, etc." }, { "code": null, "e": 2390, "s": 2334, "text": "In MS SQL Server, two types of databases are available." }, { "code": null,...
The Art of Writing Efficient Code Comments | by Elena Kosourova | Towards Data Science
If we run import this in a Jupyter notebook, or simply open this link, we'll get The Zen of Python, a collection of 19 guidelines for Python's design gathered by Tim Peters. One of them says: "Readability counts", and in this article, we're going exactly to discuss one of the aspects of this principle: code comments, which are pieces of natural language text included in the code and used for its documentation. Indeed, code comments, together with clean code, correct naming of variables and functions, and making the code as explicit as possible, contribute significantly to the readability of our projects. This can be very helpful not only to the people who will read our work in the future but also for ourselves when we return to it after some time. In this article, we’ll focus on the best practices of commenting the Python code applied to data science tasks. However, the majority of these guidelines are also valid for any other programming language or sphere. In Python, there are 2 types of code comments: block and inline ones. According to PEP 8, block comments start with a hash (#) followed by a single space, and consist of one or more sentences, with the first word capitalized and a period at the end of each sentence. If there are several sentences, they are separated by two spaces. Block comments are separated from the code above by an empty line. They apply to the code that directly follows them (with no empty line) and have the same indentation with it. A long line of a block comment should be spread over several lines, each starting with a hash followed by a single space. Another way of writing multi-line comments in Python is by using multi-line strings — those embedded in triple single or double quote marks. Technically, they were originally designed for another purpose: assigning documentation to functions, methods, or classes. However, if not used in this quality or not assigned to a variable, a multi-line string generates no code, so it can serve as an unconventional way of code commenting in Python. This approach was approved by the founder of Python Guido van Rossum in his Twitter. ✔️# Isolate the outliers with at least $3,500 spent per month except # for the cases when the respondent hadn't attended any bootcamp or # had been learning programming for a maximum 3 months before the # survey.above_3500 = usa[(usa['MoneyPerMonth']>=3500)\ &(usa['AttendedBootcamp']!=0.0)\ &(usa['MonthsProgramming']>3.0)]✔️'''Isolate the outliers with at least $3,500 spent per month except for the cases when the respondent hadn't attended any bootcamp or had been learning programming for a maximum 3 months before the survey.'''above_3500 = usa[(usa['MoneyPerMonth']>=3500)\ &(usa['AttendedBootcamp']!=0.0)\ &(usa['MonthsProgramming']>3.0)]✔️"""Isolate the outliers with at least $3,500 spent per month except for the cases when the respondent hadn't attended any bootcamp or had been learning programming for a maximum 3 months before the survey."""above_3500 = usa[(usa['MoneyPerMonth']>=3500)\ &(usa['AttendedBootcamp']!=0.0)\ &(usa['MonthsProgramming']>3.0)] An inline comment is placed on the same line as the piece of code it comments, separated from it by at least two spaces, a hash, and a single space. Inline comments are usually shorter and should be used with caution since they tend to be visually mixed with the lines of code above and below them, and, as a consequence, become unreadable, like in this piece of code: ❌ax.set_title('Book Rating Comparison', fontsize=20)ax.set_xlabel(None) # remove x labelax.tick_params(axis='both', labelsize=15)plt.show() Sometimes, though, inline comments can be indispensable: ✔️colors = [[213/255,94/255,0], # vermillion [86/255,180/255,233/255], # sky blue [230/255,159/255,0], # orange [204/255,121/255,167/255]] # reddish purple Please pay attention that in the code above, the alignment of inline comments helps to improve their readability. Even though the guidelines on the code comment syntax are designed to make the code more readable and consistent, we should keep in mind that the language itself evolves, and so do the styling conventions. Also, a company (or a particular project) can have its own coding style approaches, and then the priority is given to those case-specific recommendations, if different from PEP 8. Hence, sometimes the official guidelines can be ignored. However, some practices should be avoided almost always: Using more than one hash before a comment Using one or more hashes also at the end of a comment Omitting a space between a hash and a comment Using all capital letters (we’ll see later an exception) Omitting an empty line after a piece of code above the comment Inserting an empty line between a comment and its related code Ignoring the indentation of the commented code These approaches are undesirable, because they clutter the code with unnecessary elements, decrease its readability, and make it difficult to distinguish between separate code blocks. Compare these identical pieces of code different in comment styling: ❌###REMOVE ALL THE ENTRIES RELATED TO 2021###questions = questions[questions['Date'].dt.year < 2021]###CREATE A LIST OF TAGS###tags_list = list(tags.keys())✔️# Remove all the entries related to 2021.questions = questions[questions['Date'].dt.year < 2021]# Create a list of tags.tags_list = list(tags.keys()) If the code itself says what to do to a computer, the code comments are addressed to human beings, explaining to them what this code exactly does and especially why we need it. About the “what”, there is a widespread opinion that if our code is as explicit and plain as possible, if we used self-explanatory names for variables and functions, then we almost don’t need code comments at all. Even though I agree that writing an easily understandable code and selecting variable/function names carefully is very important, I would argue that code comments are rather useful as well. They help to section the code into several logical parts making it easier to navigate. They are useful for explaining the functionality of a rarely used or new method / function. Also, it’s a good idea to add code comments if we have to apply an unusual/non-evident approach to coding because maybe of some bugs / technical issues / version conflicts detected when trying to follow a more explicit way. Writing a code, we should keep in mind people (e.g. our colleagues) who could read our code in the future. What is clear for one person can be not evident at all for another. Hence, we should try to take into consideration a potential gap in experience, technical and contextual knowledge of different people, and facilitate their task by using comments. Code comments are valuable for adding the information on the authors, a date, and status of modifications (e.g. # Updated by Elena Kosourova, 22.04.2021. Added an annotation of the current year on the graph.). Hence, code commenting is a fast and powerful approach to improve code readability and accessibility, and for writing clear and meaningful comments, it’s not enough just to be a good coder — it’s important also to be a good writer, which is almost a skill to learn per se. Let’s consider some suggestions we should follow to apply code commenting efficiently and prevent overusing it. Our comments shouldn’t state evident or clear from the context things. Once again, let’s remember here that the “evident” can vary from one person to another, and also the scope and target audience of our work matters (for example, if we’re writing a real-data project on data science or a manual for students). Our task here is to find the balance. ❌# Import libraries.import pandas as pdimport numpy as np For being useful at maximum, our code comments should be as precise and laconic as possible, giving all the necessary details about their piece of code and excluding any irrelevant information such as observations from the previous code, intentions for the future, or parenthesis. Also, since the code usually implies some dynamics (it does, creates, removes, etc.), a good practice is to use verbs rather than nouns: ❌ Too vague# Select a specific type of columns.characters = star_wars.iloc[:, 15:29]❌ Too wordy# Now, let's select all the columns of a radio-button type from our dataframe.characters = star_wars.iloc[:, 15:29]❌ Observations from the previous code# Select radio-button type columns, as done earlier for checkbox type ones.characters = star_wars.iloc[:, 15:29]❌ Using a noun instead of a verb# Selection of radio-button type columns.characters = star_wars.iloc[:, 15:29]✔️ Good# Select radio-button type columns.characters = star_wars.iloc[:, 15:29] It’s a tricky and very common pitfall, but we should always remember to introduce all the necessary modifications also to the code comments when the code changes. As PEP 8 states, “comments that contradict the code are worse than no comments”. What’s more, sometimes we have to check not only the code comment related to the modified piece of code but also the other ones that can be indirectly influenced by such changes. A common practice is to write code comments always in English. However, this is one of those rules that can be ignored in some cases: if we’re absolutely sure that our code will never be read by people who don’t speak our language (or whatever other language in common), then we’d better write the comments exactly in that language. In this case, the code becomes more comprehensible exactly for our particular target audience. Sometimes, working on a project, we find it useful to test several methods for the same task or for debugging the code, and then we can decide to keep some of those tested pieces commented-out, even if we select another one at the end, just in case. However, this approach is good only temporarily, and in the final version of the project, it’s important to clean out such fragments. Indeed, it can be very distracting for those people (including ourselves after some time) who will read this code in the future. The reader could start having doubts if the commented-out piece of code was somehow useful at any step, and if it should be kept in the project. To avoid this confusion, it’s better just to remove all commented-out code. As usual, there can be very rare exceptions from this best practice. Let’s say, our work is about showing different ways of obtaining the same result, and one approach is more preferable to another (which is still feasible but less used). In this case, we may focus on the main approach and show the second one as a commented-out code, with a corresponding comment to it. Also, here we can make another exception mentioned earlier and use capital letters for the code comment, to make it a bit more visible: ✔️# Create a stem plot.plt.stem(months.index, months)# # ALTERNATIVE WAY TO CREATE A STEM PLOT.# plt.vlines(x=months.index, ymin=0, ymax=months)# plt.plot(months.index, months, 'o') All in all, code commenting is a handy technique for communicating the approaches we used for coding and the reasons behind them to other people . It improves the overall code readability and makes it easier to navigate between different logical blocks. To create meaningful code comments in Python, we have to follow simple and straightforward technical guidelines, keep in mind possible local company- or project-specific conventions, make our comments as laconic and informative as possible, update them in case of code modifications, and — the last but not the least — avoid overusing them. Thanks for reading! If you liked this article, you can also find interesting the following ones:
[ { "code": null, "e": 930, "s": 172, "text": "If we run import this in a Jupyter notebook, or simply open this link, we'll get The Zen of Python, a collection of 19 guidelines for Python's design gathered by Tim Peters. One of them says: \"Readability counts\", and in this article, we're going exactl...
TestNG - Basic Annotations - Transformers
In some scenarios you might want to execute TestNG tests based on some condition or criteria that is evaluated dynamically while test execution is in progress.Such as : Enable or disable a test Enable or disable a test Add data provider at run time Add data provider at run time In order to achieve this, you need to use an Annotation Transformer. An Annotation Transformer is a class that implements the following interface: public interface IAnnotationTransformer { /** * This method will be invoked by TestNG to give you a chance * to modify a TestNG annotation read from your test classes. * You can change the values you need by calling any of the * setters on the ITest interface. * * Note that only one of the three parameters testClass, * testConstructor and testMethod will be non-null. * * @param annotation The annotation that was read from your * test class. * @param testClass If the annotation was found on a class, this * parameter represents this class (null otherwise). * @param testConstructor If the annotation was found on a constructor, * this parameter represents this constructor (null otherwise). * @param testMethod If the annotation was found on a method, * this parameter represents this method (null otherwise). */ public void transform(ITest annotation, Class testClass, Constructor testConstructor, Method testMethod); } You can specify this class either on the command line or with ant as shown below: java org.testng.TestNG -listener TestTransformer testng.xml or programmatically as shown below: TestNG test = new TestNG(); test.setAnnotationTransformer(new TestTransformer()); // ... This interface IAnnotationTransformer modifies the default TestNG tests behavior at run time. Using this listener, we can modify values of all attributes defined in @Test annotation by calling their setters. Let's see the usage of annotation transformer in below example. Let us skip tests that are tagged to a specified group without changing TestNG suite every time. Create a java class to be tested, say, ListenerTest.java in /work/testng/src. import org.testng.annotations.Test; public class ListenerTest { @Test(groups={"betaTest","aplhaTest"}) public void test1() { System.out.println("I am test1"); } @Test(groups={"aplhaTest"}) public void test2() { System.out.println("I am test2"); } } Create a java test class, say, TestTransformer.java(that implements IAnnotationTransformer) in /work/testng/src. Create a java test class, say, TestTransformer.java(that implements IAnnotationTransformer) in /work/testng/src. Override method transform(). Override method transform(). Add an Annotation @Test to methods test1() and test2() and group them. Add an Annotation @Test to methods test1() and test2() and group them. Add logic to skip tests with group name betaTest. Add logic to skip tests with group name betaTest. Following are the TestTransformer.java contents. import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import org.testng.IAnnotationTransformer; import org.testng.annotations.ITestAnnotation; public class TestTransformer implements IAnnotationTransformer{ @Override public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { List groupNames = Arrays.asList(annotation.getGroups()); System.out.println(groupNames.toString()); //Value 'betaTest' can be read from many places like properties file, run time parameter etc... //For Simplicity, group is hardcoded in this program String groupNameToSkip = "betaTest"; if(groupNames.contains(groupNameToSkip)){ System.out.println("found group name"); annotation.setEnabled(false); } } } Next, let's create testng.xml file in /work/testng/src, to execute test case(s). <suite name="Suite" parallel="classes" thread-count="2"> <listeners> <listener class-name="TestTransformer"></listener> </listeners> <test name="Test"> <classes> <class name="ListenerTest"/> </classes> </test> </suite> Compile the test case using javac. /work/testng/src$ javac TestTransformer.java ListenerTest.java Now, run the testng.xml, which will run the test case defined in <test> tag. As you can see the tests grouped under name betaTest are skipped. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. [aplhaTest] [betaTest, aplhaTest] found group name I am test2 =============================================== Suite Total tests run: 1, Passes: 1, Failures: 0, Skips: 0 =============================================== 38 Lectures 4.5 hours Lets Kode It 15 Lectures 1.5 hours Quaatso Learning 28 Lectures 3 hours Dezlearn Education Print Add Notes Bookmark this page
[ { "code": null, "e": 2229, "s": 2060, "text": "In some scenarios you might want to execute TestNG tests based on some condition or criteria that is evaluated dynamically while test execution is in progress.Such as :" }, { "code": null, "e": 2254, "s": 2229, "text": "Enable or dis...
Admirable Numbers - GeeksforGeeks
13 Jul, 2021 Given an integer N, the task is to check if N is an Admirable Number. An admirable number is a number, if there exists a proper divisor D’ of N such that sigma(N)-2D’ = 2N, where sigma(N) is the sum of all divisors of N Examples: Input: N = 12 Output: Yes Explanation: 12’s proper divisors are 1, 2, 3, 4, 6, and 12 sigma(N) = 1 + 2 + 3 + 4 + 6 + 12 = 28 sigma(N) – 2D’ = 2N 28 – 2*2 = 2*12 24 == 24 Input: N = 28 Output: No Approach: The idea is to find the sum of all factors of a number that is sigma(N). And then we will find every proper divisor of a number D’ and check if there exists a proper divisor D’ of N such that Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to check if// N is an admirable number #include <bits/stdc++.h>using namespace std; // Function to calculate the sum of// all divisors of a given numberint divSum(int n){ // Sum of divisors int result = 0; // Find all divisors // which divides 'num' for (int i = 2; i <= sqrt(n); i++) { // if 'i' is divisor of 'n' if (n % i == 0) { // if both divisors are same // then add it once else add if (i == (n / i)) result += i; else result += (i + n / i); } } // Add 1 and n to result as above loop // considers proper divisors greater return (result + n + 1);} // Function to check if there// exists a proper divisor// D' of N such that sigma(n)-2D' = 2Nbool check(int num){ int sigmaN = divSum(num); // Find all divisors which divides 'num' for (int i = 2; i <= sqrt(num); i++) { // if 'i' is divisor of 'num' if (num % i == 0) { // if both divisors are same then add // it only once else add both if (i == (num / i)) { if (sigmaN - 2 * i == 2 * num) return true; } else { if (sigmaN - 2 * i == 2 * num) return true; if (sigmaN - 2 * (num / i) == 2 * num) return true; } } } // Check 1 since 1 is also a divisor if (sigmaN - 2 * 1 == 2 * num) return true; return false;} // Function to check if N// is an admirable numberbool isAdmirableNum(int N){ return check(N);} // Driver codeint main(){ int n = 12; if (isAdmirableNum(n)) cout << "Yes"; else cout << "No"; return 0;} // Java implementation to check if N// is a admirable numberclass GFG{ // Function to calculate the sum of// all divisors of a given numberstatic int divSum(int n){ // Sum of divisors int result = 0; // Find all divisors // which divides 'num' for (int i = 2; i <= Math.sqrt(n); i++) { // if 'i' is divisor of 'n' if (n % i == 0) { // if both divisors are same // then add it once else add if (i == (n / i)) result += i; else result += (i + n / i); } } // Add 1 and n to result as above loop // considers proper divisors greater return (result + n + 1);} // Function to check if there// exists a proper divisor// D' of N such that sigma(n)-2D' = 2Nstatic boolean check(int num){ int sigmaN = divSum(num); // Find all divisors which divides 'num' for (int i = 2; i <= Math.sqrt(num); i++) { // if 'i' is divisor of 'num' if (num % i == 0) { // if both divisors are same then add // it only once else add both if (i == (num / i)) { if (sigmaN - 2 * i == 2 * num) return true; } else { if (sigmaN - 2 * i == 2 * num) return true; if (sigmaN - 2 * (num / i) == 2 * num) return true; } } } // Check 1 since 1 is also a divisor if (sigmaN - 2 * 1 == 2 * num) return true; return false;} // Function to check if N// is an admirable numberstatic boolean isAdmirableNum(int N){ return check(N);} // Driver codepublic static void main(String[] args){ int n = 12; if (isAdmirableNum(n)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed by shubham # Python3 implementation to check if# N is an admirable numberimport math # Function to calculate the sum of# all divisors of a given numberdef divSum(n): # Sum of divisors result = 0 # Find all divisors # which divides 'num' for i in range(2, int(math.sqrt(n)) + 1): # If 'i' is divisor of 'n' if (n % i == 0): # If both divisors are same # then add it once else add if (i == (n // i)): result += i else: result += (i + n // i) # Add 1 and n to result as above loop # considers proper divisors greater return (result + n + 1) # Function to check if there# exists a proper divisor# D' of N such that sigma(n)-2D' = 2Ndef check(num): sigmaN = divSum(num) # Find all divisors which divides 'num' for i in range(2, int(math.sqrt(num)) + 1): # If 'i' is divisor of 'num' if (num % i == 0): # If both divisors are same then add # it only once else add both if (i == (num // i)): if (sigmaN - 2 * i == 2 * num): return True else: if (sigmaN - 2 * i == 2 * num): return True if (sigmaN - 2 * (num // i) == 2 * num): return True # Check 1 since 1 is also a divisor if (sigmaN - 2 * 1 == 2 * num): return True return False # Function to check if N# is an admirable numberdef isAdmirableNum(N): return check(N) # Driver coden = 12 if (isAdmirableNum(n)): print("Yes")else: print("No") # This code is contributed by divyeshrabadiya07 // C# implementation to check if N// is a admirable numberusing System;class GFG{ // Function to calculate the sum of// all divisors of a given numberstatic int divSum(int n){ // Sum of divisors int result = 0; // Find all divisors // which divides 'num' for(int i = 2; i <= Math.Sqrt(n); i++) { // If 'i' is divisor of 'n' if (n % i == 0) { // If both divisors are same // then add it once else add if (i == (n / i)) result += i; else result += (i + n / i); } } // Add 1 and n to result as above loop // considers proper divisors greater return (result + n + 1);} // Function to check if there// exists a proper divisor// D' of N such that sigma(n)-2D' = 2Nstatic bool check(int num){ int sigmaN = divSum(num); // Find all divisors which divides 'num' for(int i = 2; i <= Math.Sqrt(num); i++) { // If 'i' is divisor of 'num' if (num % i == 0) { // If both divisors are same then add // it only once else add both if (i == (num / i)) { if (sigmaN - 2 * i == 2 * num) return true; } else { if (sigmaN - 2 * i == 2 * num) return true; if (sigmaN - 2 * (num / i) == 2 * num) return true; } } } // Check 1 since 1 is also a divisor if (sigmaN - 2 * 1 == 2 * num) return true; return false;} // Function to check if N// is an admirable numberstatic bool isAdmirableNum(int N){ return check(N);} // Driver codepublic static void Main(){ int n = 12; if (isAdmirableNum(n)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by Code_Mech <script>// Javascript implementation to check if N// is a admirable number // Function to calculate the sum of // all divisors of a given number function divSum( n) { // Sum of divisors let result = 0; // Find all divisors // which divides 'num' for ( let i = 2; i <= Math.sqrt(n); i++) { // if 'i' is divisor of 'n' if (n % i == 0) { // if both divisors are same // then add it once else add if (i == (n / i)) result += i; else result += (i + n / i); } } // Add 1 and n to result as above loop // considers proper divisors greater return (result + n + 1); } // Function to check if there // exists a proper divisor // D' of N such that sigma(n)-2D' = 2N function check( num) { let sigmaN = divSum(num); // Find all divisors which divides 'num' for (let i = 2; i <= Math.sqrt(num); i++) { // if 'i' is divisor of 'num' if (num % i == 0) { // if both divisors are same then add // it only once else add both if (i == (num / i)) { if (sigmaN - 2 * i == 2 * num) return true; } else { if (sigmaN - 2 * i == 2 * num) return true; if (sigmaN - 2 * (num / i) == 2 * num) return true; } } } // Check 1 since 1 is also a divisor if (sigmaN - 2 * 1 == 2 * num) return true; return false; } // Function to check if N // is an admirable number function isAdmirableNum( N) { return check(N); } // Driver code let n = 12; if (isAdmirableNum(n)) document.write("Yes"); else document.write("No"); // This code is contributed by todaysgaurav</script> Yes Time Complexity: O(N1/2) References: OEIS shubham prakash 1 Code_Mech divyeshrabadiya07 todaysgaurav souravmahato348 series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Program to find GCD or HCF of two numbers Modulo Operator (%) in C/C++ with Examples Prime Numbers Sieve of Eratosthenes Program to find sum of elements in a given array Program for Decimal to Binary Conversion Program for factorial of a number Operators in C / C++ The Knight's tour problem | Backtracking-1
[ { "code": null, "e": 25256, "s": 25228, "text": "\n13 Jul, 2021" }, { "code": null, "e": 25326, "s": 25256, "text": "Given an integer N, the task is to check if N is an Admirable Number." }, { "code": null, "e": 25478, "s": 25326, "text": "An admirable number ...
C# | OrderedDictionary Class
24 Jan, 2019 OrderedDictionary Class represents a collection of key/value pairs that are accessible by the key or index. It is present in System.Collections.Specialized namespace. Properties of OrderedDictionary Class : Each element is a key/value pair stored in a DictionaryEntry object. A key cannot be null, but a value can be. The elements of an OrderedDictionary are not sorted by the key. Elements can be accessed either by the key or by the index. Example: // C# code to create a OrderedDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver method public static void Main() { // Creating a orderedDictionary named myDict OrderedDictionary myDict = new OrderedDictionary(); // Adding key and value in myDict myDict.Add("1", "ONE"); myDict.Add("2", "TWO"); myDict.Add("3", "THREE"); // Displaying the number of key/value // pairs in myDict Console.WriteLine(myDict.Count); // Displaying the key/value pairs in myDict foreach(DictionaryEntry de in myDict) Console.WriteLine(de.Key + " --> " + de.Value); }} Output: 3 1 --> ONE 2 --> TWO 3 --> THREE Example 1: // C# code to check if OrderedDictionary// collection is read-onlyusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver method public static void Main() { // Creating a orderedDictionary named myDict OrderedDictionary myDict = new OrderedDictionary(); // Adding key and value in myDict myDict.Add("key1", "value1"); myDict.Add("key2", "value2"); myDict.Add("key3", "value3"); myDict.Add("key4", "value4"); myDict.Add("key5", "value5"); // Checking if OrderedDictionary // collection is read-only Console.WriteLine(myDict.IsReadOnly); }} Output: False Example 2: // C# code to get the number of// key/values pairs contained// in the OrderedDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver method public static void Main() { // Creating a orderedDictionary named myDict OrderedDictionary myDict = new OrderedDictionary(); // Adding key and value in myDict myDict.Add("A", "Apple"); myDict.Add("B", "Banana"); myDict.Add("C", "Cat"); myDict.Add("D", "Dog"); // To Get the number of key/values // pairs contained in the OrderedDictionary Console.WriteLine("Number of key/value pairs are : " + myDict.Count); }} Output: Number of key/value pairs are : 4 Example 1: // C# code to get a read-only// copy of the OrderedDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver method public static void Main() { // Creating a orderedDictionary named myDict OrderedDictionary myDict = new OrderedDictionary(); // Adding key and value in myDict myDict.Add("key1", "value1"); myDict.Add("key2", "value2"); myDict.Add("key3", "value3"); myDict.Add("key4", "value4"); myDict.Add("key5", "value5"); // To Get a read-only copy of // the OrderedDictionary OrderedDictionary myDict_1 = myDict.AsReadOnly(); // Checking if myDict_1 is read-only Console.WriteLine(myDict_1.IsReadOnly); }} Output: True Example 2: // C# code to remove the entry// with the specified key from// the OrderedDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver method public static void Main() { // Creating a orderedDictionary named myDict OrderedDictionary myDict = new OrderedDictionary(); // Adding key and value in myDict myDict.Add("key1", "value1"); myDict.Add("key2", "value2"); myDict.Add("key3", "value3"); myDict.Add("key4", "value4"); myDict.Add("key5", "value5"); // Displaying the number of element initially Console.WriteLine("Number of elements are : " + myDict.Count); // Displaying the elements in myDict foreach(DictionaryEntry de in myDict) Console.WriteLine(de.Key + " -- " + de.Value); // Removing the entry with the specified // key from the OrderedDictionary myDict.Remove("key2"); // Displaying the number of element initially Console.WriteLine("Number of elements are : " + myDict.Count); // Displaying the elements in myDict foreach(DictionaryEntry de in myDict) Console.WriteLine(de.Key + " -- " + de.Value); }} Output: Number of elements are : 5 key1 -- value1 key2 -- value2 key3 -- value3 key4 -- value4 key5 -- value5 Number of elements are : 4 key1 -- value1 key3 -- value3 key4 -- value4 key5 -- value5 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.ordereddictionary?view=netframework-4.7.2 CSharp-Specialized-Namespace CSharp-Specialized-OrderedDictionary C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jan, 2019" }, { "code": null, "e": 195, "s": 28, "text": "OrderedDictionary Class represents a collection of key/value pairs that are accessible by the key or index. It is present in System.Collections.Specialized namespace." }, ...
How to inject service in angular 6 component ?
01 Jul, 2021 Service is a special class in Angular which is primarily used for inter-component communication. Sometimes there are components that need a common pool to interact with each other mostly for data or information procurement. Service makes it possible. The two (or more) components may or may not be related to each other. That means there may exist a parent-child relationship or nothing at all. Services and other dependencies are injected directly into the constructor of the component like this: constructor(private _myService: MyService) { } By doing this, we are actually creating an instance of the service. That means we have to access all the public variables and methods of the service. To create a new service, we can use the code scaffolding tool: // Generate service ng g s my-custom-service Injecting a service into a component is pretty straightforward. Let’s say we have a service called MyCustomService. This is how we can inject it into a component: MyCustomComponent.ts import {...} from "@angular/core";import { MyCustomService } from "../...PATH"; @Component({ selector: "...", templateUrl: "...", styleUrls: ["..."],})export class MyCustomComponent { // INJECTING SERVICE INTO THE CONSTRUCTOR constructor(private _myCustomService: MyCustomService) {} // USING THE SERVICE MEMBERS this._myCustomService.sampleMethod();} This may not make any sense until and unless we get our hands dirty. So let’s quickly create a service and see how it is injected and can be accessed easily. For this demo, we will create two simple custom components. Let’s say, Ladies and Gentlemen. There is no parent-child relationship between these two components. Both are absolutely independent. Gentlemen will greet Ladies with “Good morning” with the click of a button. For this, we will use a service that will interact between the two components. We will call it InteractionService. First thing first, we will create our 2 components and 1 service. Now we have everything that we need. Since this demo is particularly for service injection. We will not discuss the components in detail. Let’s start with service first. Here is the code: interaction.service.ts import { Injectable } from '@angular/core';import { Subject } from 'rxjs'; @Injectable({ providedIn: 'root'})export class InteractionService { private _messageSource = new Subject<string>(); greeting$=this._messageSource.asObservable(); sendMessage(message: string) { this._messageSource.next(message); }} This been done. We will now inject this service into both our components. gentlemen.component.html <!DOCTYPE html><html> <head> <title>Page Title</title> </head> <body> <h2>Welcome To GFG</h2> <button (click)="greetLadies()">Greet</button> </body></html> We will now create the first component using: // Generate componentng g c gentlemen gentlemen.component.ts import {...} from "@angular/core";...import { InteractionService } from "../services/interaction.service"; @Component({ selector: "app-gentlemen", templateUrl: "./gentlemen.component.html", styleUrls: ["./gentlemen.component.scss"],})export class GentlemenComponent { // SERVICE INJECTION constructor(private _interactionService: InteractionService) {} greetLadies() { this._interactionService.sendMessage("Good morning"); }} Quickly create our last component: // Generate componentng g c ladies ladies.component.ts import {...} from "@angular/core";...import { InteractionService } from "../services/interaction.service"; @Component({ selector: "app-ladies", templateUrl: "./ladies.component.html", styleUrls: ["./ladies.component.scss"],})export class LadiesComponent implements OnInit { // SERVICE INJECTION constructor(private _interactionService: InteractionService) {} ngOnInit() { this._interactionService.greeting$.subscribe(message => { console.log(message); }) }} This is how we can inject and use the service to interact between components. We just saw a use case of service injection. We will have this as our final product: UI/UX Screenshot On click on buttons we can expect the following output: Expected output AngularJS-Questions Picked AngularJS 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": "\n01 Jul, 2021" }, { "code": null, "e": 423, "s": 28, "text": "Service is a special class in Angular which is primarily used for inter-component communication. Sometimes there are components that need a common pool to interact with each o...
Python – Remove space between tuple elements
05 Oct, 2021 Sometimes, while working with Tuples, we can have a problem in which we need to print tuples, with no space between the comma and next element, which by convention, is present. This problem can have use in day-day and school programming. Let’s discuss certain ways in which this task can be performed. Input : test_tuple = (7, 6, 8) Output : (7, 6, 8)Input : test_tuple = (6, 8) Output : (6, 8) Method #1 : Using str() + replace() The combination of above functions can be used to solve this problem. In this, we perform the task of removing the additional space, by replacing with empty space. Python3 # Python3 code to demonstrate working of# Remove space between tuple elements# Using replace() + str() # initializing tuplestest_tuple = (4, 5, 7, 6, 8) # printing original tupleprint("The original tuple : " + str(test_tuple)) # Remove space between tuple elements# Using replace() + str()res = str(test_tuple).replace(' ', '') # printing resultprint("The tuple after space removal : " + str(res)) The original tuple : (4, 5, 7, 6, 8) The tuple after space removal : (4, 5, 7, 6, 8) Method #2 : Using join() + map() Another method to solve this problem. In this, we perform the task of removal of space by external joining of each element using join() and extending the logic of string conversion to each element using map(). Python3 # Python3 code to demonstrate working of# Remove space between tuple elements# Using join() + map() # initializing tuplestest_tuple = (4, 5, 7, 6, 8) # printing original tupleprint("The original tuple : " + str(test_tuple)) # Remove space between tuple elements# Using join() + map()res = "(" + ", ".join(map(str, test_tuple)) + ")" # printing resultprint("The tuple after space removal : " + str(res)) The original tuple : (4, 5, 7, 6, 8) The tuple after space removal : (4, 5, 7, 6, 8) kashishsoda Python tuple-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Oct, 2021" }, { "code": null, "e": 331, "s": 28, "text": "Sometimes, while working with Tuples, we can have a problem in which we need to print tuples, with no space between the comma and next element, which by convention, is present...
Print matrix in snake pattern
13 Jun, 2022 Given an n x n matrix .In the given matrix, you have to print the elements of the matrix in the snake pattern. Examples : Input :mat[][] = { {10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}}; Output : 10 20 30 40 45 35 25 15 27 29 37 48 50 39 33 32 Input :mat[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; Output : 1 2 3 6 5 4 7 8 9 We traverse all rows. For every row, we check if it is even or odd. If even, we print from left to right else print from right to left. C++ Java Python3 C# PHP Javascript // C++ program to print matrix in snake order#include <iostream>#define M 4#define N 4using namespace std; void print(int mat[M][N]){ // Traverse through all rows for (int i = 0; i < M; i++) { // If current row is even, print from // left to right if (i % 2 == 0) { for (int j = 0; j < N; j++) cout << mat[i][j] << " "; // If current row is odd, print from // right to left } else { for (int j = N - 1; j >= 0; j--) cout << mat[i][j] << " "; } }} // Driver codeint main(){ int mat[M][N] = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 27, 29, 37, 48 }, { 32, 33, 39, 50 } }; print(mat); return 0;} // Java program to print matrix in snake orderimport java.util.*;class GFG{ static void print(int [][] mat) { // Traverse through all rows for (int i = 0; i < mat.length; i++) { // If current row is even, print from // left to right if (i % 2 == 0) { for (int j = 0; j < mat[0].length; j++) System.out.print(mat[i][j] +" "); // If current row is odd, print from // right to left } else { for (int j = mat[0].length - 1; j >= 0; j--) System.out.print(mat[i][j] +" "); } } } // Driver code public static void main(String[] args) { int mat[][] = new int[][] { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 27, 29, 37, 48 }, { 32, 33, 39, 50 } }; print(mat); }}/* This code is contributed by Mr. Somesh Awasthi */ # Python 3 program to print# matrix in snake orderM = 4N = 4 def printf(mat): global M, N # Traverse through all rows for i in range(M): # If current row is # even, print from # left to right if i % 2 == 0: for j in range(N): print(str(mat[i][j]), end = " ") # If current row is # odd, print from # right to left else: for j in range(N - 1, -1, -1): print(str(mat[i][j]), end = " ") # Driver codemat = [[ 10, 20, 30, 40 ], [ 15, 25, 35, 45 ], [ 27, 29, 37, 48 ], [ 32, 33, 39, 50 ]] printf(mat) # This code is contributed# by ChitraNayal // C# program to print// matrix in snake orderusing System;class GFG{ static void print(int [,]mat) { // Traverse through all rows for (int i = 0; i < mat.GetLength(0); i++) { // If current row is // even, print from // left to right if (i % 2 == 0) { for (int j = 0; j < mat.GetLength(1); j++) Console.Write(mat[i, j] + " "); // If current row is // odd, print from // right to left } else { for (int j = mat.GetLength(1) - 1; j >= 0; j--) Console.Write(mat[i, j] + " "); } } } // Driver code public static void Main() { int [,]mat = {{ 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 27, 29, 37, 48 }, { 32, 33, 39, 50 }}; print(mat); }} // This code is contributed// by ChitraNayal <?php// PHP program to print// matrix in snake order$M= 4;$N =4; function printLN($mat){ global $M; global $N; // Traverse through all rows for ($i = 0; $i < $M; $i++) { // If current row is even, // print from left to right if ($i % 2 == 0) { for ($j = 0; $j < $N; $j++) echo $mat[$i][$j], " "; // If current row is odd, // print from right to left } else { for ($j = $N - 1; $j >= 0; $j--) echo $mat[$i][$j] , " "; } }} // Driver code$mat = array(array(10, 20, 30, 40), array(15, 25, 35, 45), array(27, 29, 37, 48), array(32, 33, 39, 50)); printLN($mat); // This code is contributed by ajit?> <script> // Javascript program to print// matrix in snake orderlet M = 4;let N = 4; function print(mat){ // Traverse through all rows for(let i = 0; i < M; i++) { // If current row is even, print from // left to right if (i % 2 == 0) { for(let j = 0; j < N; j++) document.write(mat[i][j] + " "); // If current row is odd, print from // right to left } else { for(let j = N - 1; j >= 0; j--) document.write(mat[i][j] + " "); } }} // Driver codelet mat = [ [ 10, 20, 30, 40 ], [ 15, 25, 35, 45 ], [ 27, 29, 37, 48 ], [ 32, 33, 39, 50 ] ]; print(mat); // This code is contributed by rameshtravel07</script> Output : 10 20 30 40 45 35 25 15 27 29 37 48 50 39 33 32 Time Complexity: O(n x m) Auxiliary Space: O(1) This article is contributed by Rakesh 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. jit_t ukasp rameshtravel07 iqlipseabhi codewithmini Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 163, "s": 52, "text": "Given an n x n matrix .In the given matrix, you have to print the elements of the matrix in the snake pattern." }, { "code": null, "e": 175, "s": 163, "te...
Python | Pandas Series.eq()
15 Oct, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas series.eq() is used to compare every element of Caller series with passed series. It returns True for every element which is Equal to the element in passed series. Note: The results are returned on the basis of comparison caller series = other series. Syntax: Series.eq(other, level=None, fill_value=None) Parameters:other: other series to be compared withlevel: int or name of level in case of multi levelfill_value: Value to be replaced instead of NaN Return type: Boolean series Example #1: Handling Null Values In this example, two series are created using pd.Series(). The series contains some Null values and some equal values at same indices too. The series are compared using .eq() method and 5 is passed to fill_value parameter to replace NaN values by 5. # importing pandas module import pandas as pd # importing numpy module import numpy as np # creating series 1 series1 = pd.Series([70, 5, 0, 225, 1, 16, np.nan, 10, np.nan]) # creating series 2 series2 = pd.Series([70, np.nan, 2, 23, 1, 95, 53, 10, 5]) # NaN replacementreplace_nan = 5 # calling and returning to result variableresult = series1.eq(series2, fill_value = replace_nan) # display result Output:As shown in output, True was returned wherever value in caller series was Equal to value in passed series. Also it can be seen Null values were replaced by 5 and the comparison was made using that value. Example #2: Calling on Series with str objectsIn this example, two series are created using pd.Series(). The series contains some string values too. In case of strings, the comparison is made with their ASCII values. # importing pandas module import pandas as pd # importing numpy module import numpy as np # creating series 1 series1 = pd.Series(['Aaa', 10, 'cat', 43, 9, 'Dog', np.nan, 'x', np.nan]) # creating series 2 series2 = pd.Series(['vaa', np.nan, 'Cat', 23, 5, 'Dog', 54, 'x', np.nan]) # NaN replacementreplace_nan = 10 # calling and returning to result variableresult = series1.eq(series2, fill_value = replace_nan) # display result Output:As it can be seen in output, in case of strings, the comparison was made using their ASCII values. True was returned wherever the string in Caller series was equal to string in passed series. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Oct, 2018" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes imp...
C# | PadLeft() Method
31 Jan, 2019 In C#, PadLeft() is a string method. This method is used to right-aligns the characters in String by padding them with spaces or specified character on the left, for a specified total length. This method can be overloaded by passing different parameters to it. String.PadLeft Method(Int32) String.PadLeft Method(Int32, Char) String.PadLeft Method(Int32) This method is used to right-aligns the characters in this string by padding them with spaces on the left. The parameter “totalWidth” will specify the number of padding characters in the string and this method will return a new string. Syntax: public string PadLeft(int totalWidth) Parameter: This method will accept one parameter “totalWidth” which specify the number of padding characters in string. The type of this parameter is System.Int32. Return Value: This method will return the string which pads the right portion of the string. The return value type is System.String. Exception: If totalWidth is less than zero then it will arise ArgumentOutOfRangeException. Example: Program to demonstrate the public string PadLeft(int totalWidth) method. The string is right-aligned and padded on the left with whitespace as needed to create a length of totalWidth. However, If totalWidth is less than or equal to the length of the string, the method returns a new string that is identical to string. For example, If the current string is “Geeks” and total width is 7 then PadLeft method returns ” Geeks”. // C# program to illustrate the// String.PadLeft(totalWidth) methodusing System;class Geeks { // Main Method public static void Main() { string s1 = "GeeksForGeeks"; Console.WriteLine("String : " + s1); // totalwidth is less than string length Console.WriteLine("Pad 2 :'{0}'", s1.PadLeft(2)); // totalwidth is equal to string length Console.WriteLine("Pad 13 :'{0}'", s1.PadLeft(13)); // totalwidth is greater then string length Console.WriteLine("Pad 20 :'{0}'", s1.PadLeft(20)); }} Output: String : GeeksForGeeks Pad 2 :'GeeksForGeeks' Pad 13 :'GeeksForGeeks' Pad 20 :' GeeksForGeeks' String.PadLeft Method(Int32, Char) This method is used to right-aligns the characters in this string by padding them with specified character on the left. The parameter “totalWidth” will specify the number of padding characters in string and “paddingChar” is the specified Character. Syntax: public string PadLeft(int totalWidth, char paddingChar) Parameter: This method accept two parameter “totalWidth” and “paddingChar“. The parameter “totalWidth” will specify the number of padding characters in string and type of this parameter is System.Int32. The parameter “paddingChar” will specify the padding character and type of this parameter is System.Char. Return Value: This method will return a new string which will be equivalent to current string, but right-aligned and padded on the left with the characters specified by “paddingChar” parameter. If totalWidth is less than the length of the string, the method returns the same string. If totalWidth is equal to the length of the string, the method returns a new string that is identical to the current String. The return value type is System.String. Exception: If totalWidth is less than zero then it will arise ArgumentOutOfRangeException. Example: Program to demonstrate the public string PadLeft(int totalWidth, char paddingChar) method. The string is right-aligned and padded on the left with as paddingChar characters as needed to create a length of totalWidth. However, If totalWidth is less than or equal to the length of this instance, the method returns a new string that is identical to this instance. For example, If the current string is “Geeks” and totalWidth is 7 and paddingChar is ‘*’ then PadLeft method returns “**Geeks”. // C# program to illustrate the// String.PadLeft(int totalWidth, // char paddingChar) methodusing System; class Geeks { // Main Method public static void Main() { string s1 = "GeeksForGeeks"; char pad = '*'; Console.WriteLine("String : " + s1); // totalwidth is less than string length Console.WriteLine("Pad 2 :'{0}'", s1.PadLeft(2, pad)); // totalwidth is equal to string length Console.WriteLine("Pad 13 :'{0}'", s1.PadLeft(13, pad)); // totalwidth is greater then string length Console.WriteLine("Pad 20 :'{0}'", s1.PadLeft(20, pad)); }} Output: String : GeeksForGeeks Pad 2 :'GeeksForGeeks' Pad 13 :'GeeksForGeeks' Pad 20 :'*******GeeksForGeeks' Important Points About PadLeft() Method: If the PadLeft method pads the current instance with whitespace characters, this method does not modify the value of the current instance. Instead, it returns a new string that is padded with leading white space so that its total length is totalWidth characters. If totalWidth is less than the length of String, the method returns a reference to the existing instance. References: https://msdn.microsoft.com/en-us/library/system.string.padleft1 https://msdn.microsoft.com/en-us/library/system.string.padleft2 CSharp-method CSharp-string C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n31 Jan, 2019" }, { "code": null, "e": 314, "s": 53, "text": "In C#, PadLeft() is a string method. This method is used to right-aligns the characters in String by padding them with spaces or specified character on the left, for a specif...
K largest elements | Practice | GeeksforGeeks
Given an array of N positive integers, print k largest elements from the array. Example 1: Input: N = 5, k = 2 arr[] = {12,5,787,1,23} Output: 787 23 Explanation: First largest element in the array is 787 and the second largest is 23. Example 2: Input: N = 7, k = 3 arr[] = {1,23,12,9,30,2,50} Output: 50 30 23 Explanation: Three Largest element in the array are 50, 30 and 23. Your Task: Complete the function kLargest() that takes the array, N and K as input parameters and returns a list of k largest element in descending order. Expected Time Complexity: O(N log K) Expected Auxiliary Space: O(K) Constraints: 1 ≤ N ≤ 104 K ≤ N 1 ≤ array[i] ≤ 105 0 adityasuhane47 hours ago vector<int> kLargest(int arr[], int n, int k) { vector<int> v; sort(arr,arr+n,greater<int>()); for (int i = 0; i < k; i++) { v.push_back(arr[i]); } return v; } 0 gupta2411sumit2 days ago vector<int> kLargest(int arr[], int n, int k) { // code here vector<int>ans ; priority_queue<int>pq ; for( int i = 0 ; i< n ; i++ ) { pq.push(arr[i]) ; } for( int i = 0 ; i<k ; i++) { ans.push_back(pq.top()) ; pq.pop() ; } return ans ; } 0 dpahariya14 days ago li.sort() li.reverse() return li[:k] 0 ashishbutola75 days ago Javascript solution with Maxheap -: kLargest(arr,n,k) { let maxHeap = [] let removed = [] const heapifyUp = () => { let childIndex = (maxHeap.length - 1) let parentIndex = Math.floor((childIndex - 1)/2) if (!childIndex) return while(maxHeap[parentIndex] && (maxHeap[parentIndex] < maxHeap[childIndex])) { const temp = maxHeap[parentIndex] maxHeap[parentIndex] = maxHeap[childIndex] maxHeap[childIndex] = temp childIndex = parentIndex parentIndex = Math.floor((childIndex - 1)/2) } } const heapifyDown = () => { let parentIndex = 0 let leftChild = (2*parentIndex + 1) let rightChild = (2*parentIndex + 2) let maxIndex = parentIndex while(maxHeap[leftChild]) { if (maxHeap[parentIndex] < maxHeap[leftChild]) { maxIndex = leftChild } if (maxHeap[rightChild] && (maxHeap[maxIndex] < maxHeap[rightChild])) { maxIndex = rightChild } if (parentIndex === maxIndex) return const temp = maxHeap[parentIndex] maxHeap[parentIndex] = maxHeap[maxIndex] maxHeap[maxIndex] = temp parentIndex = maxIndex leftChild = (2*parentIndex + 1) rightChild = (2*parentIndex + 2) } } for (let i = 0; i < n; i++) { maxHeap.push(arr[i]) heapifyUp() } for (let i = 0; i < k; i++) { const topElement = maxHeap[0] const lastElem = maxHeap[maxHeap.length - 1] maxHeap.pop() maxHeap[0] = lastElem heapifyDown() removed.push(topElement) } return removed } +1 beast_bhavesh1 week ago using min heap { // code here priority_queue< int,vector<int>,greater<int> >pq; vector<int>ans; for(int i=0;i<n;i++){ pq.push(arr[i]); if(pq.size() > k){ pq.pop(); } } while(pq.empty() == false){ ans.push_back(pq.top()); pq.pop(); } reverse(ans.begin(), ans.end()); return ans; } +2 sudhanshushekhar15582 weeks ago prog.java:57: error: incompatible types: Integer cannot be converted to ArrayList<Integer> return largest.peek(); ^ //Initial Template for Java import java.util.*; import java.io.*; class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t > 0) { int n = sc.nextInt(); int k = sc.nextInt(); int arr[] = new int[n]; for(int i = 0; i<n; ++i) arr[i] = sc.nextInt(); Solution ob = new Solution(); ArrayList<Integer> list = ob.kLargest(arr, n, k); for(int i = 0; i<list.size(); i++) System.out.print(list.get(i) + " "); System.out.println(); t--; } } } // } Driver Code Ends //User function Template for Java class Solution { //Function to return k largest elements from an array. public static ArrayList<Integer> kLargest(int arr[], int n, int k) { PriorityQueue<Integer>largest = new PriorityQueue<>(); for (int i=0 ;i<=k-1;i++) { largest.add(arr[i]); } for(int i=k ; i<n-1;i++) { if(largest.peek() < arr[i]) { largest.remove(); largest.add(arr[i]); } } return largest.peek(); } } -3 kumarr32033 weeks ago //c++ solution vector<int> kLargest(int a[], int n, int k) { // code here vector<int>v; sort(a,a+n); for(int i=n-1;i>=n-k;i--) { v.push_back(a[i]); } return v; }}; 0 shivamtech20241 month ago vector<int> kLargest(int arr[], int n, int k) { // code here vector<int> vec; stack<int> st; priority_queue< int , vector<int> , greater<int> > pq; for(int i=0;i<k;i++){ pq.push(arr[i]); } for(int i=k;i<n;i++){ if(arr[i] > pq.top()){ pq.pop(); pq.push(arr[i]); } } for(int i=0;i<k;i++){ int ans = pq.top(); st.push(ans); pq.pop(); } for(int i=0;i<k;i++){ vec.push_back(st.top()); st.pop(); } return vec; } +1 mbi20210121 month ago vector<int> kLargest(int arr[], int n, int k) { priority_queue<int,vector<int>,greater<int>>minh; for(int i=0;i<n;i++) { minh.push(arr[i]); if(minh.size()>k) { minh.pop(); } } vector<int>ans(k,0); while(k>0) { ans[k-1]=minh.top(); minh.pop(); k--; } return ans; } 0 tusharkhatriofficial1 month ago Python Solution #User function Template for python3 class Solution: #Function to return k largest elements from an array. def kLargest(self,li,n,k): # code here li.sort(reverse=True) return li[:k] 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": 319, "s": 238, "text": "Given an array of N positive integers, print k largest elements from the array. " }, { "code": null, "e": 330, "s": 319, "text": "Example 1:" }, { "code": null, "e": 475, "s": 330, "text": "Input:\nN = 5, k = 2\narr...
JavaScript | Detecting a mobile browser
31 Jan, 2022 In order to detect if the user is using the mobile’s browser, we have a number of methods.Most preferred are few of them. Example-1: This example go through a list of devices and check if the userAgent matches with any of the devices. <!DOCTYPE html><html> <head> <title> javaScript | Detecting a mobile browser </title> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <button id="GFG_Button" onclick="detec()"> detect </button> <p id="GFG_P" style="color:green; font-size: 20px;"> </p> <script> var a = ''; var up = document.getElementById("GFG_P"); function detec() { if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i)) { a = true; } else { a = false; } up.innerHTML = a; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example-2: Using “window.orientation” <!DOCTYPE html><html> <head> <title> javaScript | Detecting a mobile browser </title> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <button id="GFG_Button" onclick="detec()"> detect </button> <p id="GFG_P" style="color:green; font-size: 20px;"> </p> <script> var a = ''; var up = document.getElementById("GFG_P"); function detec() { var isMobile = window.orientation > -1; alert(isMobile ? 'Mobile' : 'Not mobile'); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example-3:This examples uses the regex to check the device. It returns True if it is mobile phone’s browser. <!DOCTYPE html><html> <head> <title> javaScript | Detecting a mobile browser </title> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <button id="GFG_Button" onclick="detec()"> detect </button> <p id="GFG_P" style="color:green; font-size: 20px;"> </p> <script> var a = ''; var up = document.getElementById( "GFG_P"); function detec() { var ch = false; (function(a) { if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetch|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true; })(navigator.userAgent || navigator.vendor || window.opera); t = ch; up.innerHTML = t; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: sumitgumber28 JavaScript-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Jan, 2022" }, { "code": null, "e": 150, "s": 28, "text": "In order to detect if the user is using the mobile’s browser, we have a number of methods.Most preferred are few of them." }, { "code": null, "e": 263, "s": 15...
Introduction to Tkinter
22 May, 2020 Graphical User Interface(GUI) is a form of user interface which allows users to interact with computers through visual indicators using items such as icons, menus, windows, etc. It has advantages over the Command Line Interface(CLI) where users interact with computers by writing commands using keyboard only and whose usage is more difficult than GUI. Tkinter is the inbuilt python module that is used to create GUI applications. It is one of the most commonly used modules for creating GUI applications in Python as it is simple and easy to work with. You don’t need to worry about the installation of the Tkinter module separately as it comes with Python already. It gives an object-oriented interface to the Tk GUI toolkit.Some other Python Libraries available for creating our own GUI applications are Kivy Python Qt wxPython Among all Tkinter is most widely used Widgets in Tkinter are the elements of GUI application which provides various controls (such as Labels, Buttons, ComboBoxes, CheckBoxes, MenuBars, RadioButtons and many more) to users to interact with the application. Fundamental structure of tkinter programBasic Tkinter Widgets: Example from tkinter import * from tkinter.ttk import * # writing code needs to# create the main window of # the application creating # main window object named rootroot = Tk() # giving title to the main windowroot.title("First_Program") # Label is what output will be # show on the windowlabel = Label(root, text ="Hello World !").pack() # calling mainloop method which is used# when your application is ready to run# and it tells the code to keep displaying root.mainloop() Output Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 May, 2020" }, { "code": null, "e": 405, "s": 52, "text": "Graphical User Interface(GUI) is a form of user interface which allows users to interact with computers through visual indicators using items such as icons, menus, windows, e...
Python Program for Find remainder of array multiplication divided by n
07 Jun, 2022 Given multiple numbers and a number n, the task is to print the remainder after multiplying all the numbers divided by n.Examples: Input : arr[] = {100, 10, 5, 25, 35, 14}, n = 11Output : 9Explaination: 100 x 10 x 5 x 25 x 35 x 14 = 61250000 % 11 = 9 Naive approach: First multiple all the numbers then take % by n to find the remainder, But in this approach, if the number is a maximum of 2^64 then it gives the wrong answer. An approach that avoids overflow: First take a remainder or individual number like arr[i] % n. Then multiply the remainder with the current result. After multiplication, again take the remainder to avoid overflow. This works because of the distributive properties of modular arithmetic. ( a * b) % c = ( ( a % c ) * ( b % c ) ) % c Python3 # to use reduce function import reduce from functoolsfrom functools import reduce def find_remainder(arr, n): sum_1 = reduce(lambda x, y: x*y, arr) remainder = sum_1 % n print(remainder) arr = [100, 10, 5, 25, 35, 14]n = 11find_remainder(arr, n) 9 Please refer complete article on Find remainder of array multiplication divided by n for more details! Akanksha_Rai pavanimadhira86 namritbe18 harendrakumar123 Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jun, 2022" }, { "code": null, "e": 184, "s": 52, "text": "Given multiple numbers and a number n, the task is to print the remainder after multiplying all the numbers divided by n.Examples: " }, { "code": null, "e": 304, ...
PHP | time() Function
05 May, 2018 The time() function is a built-in function in PHP which returns the current time measured in the number of seconds since the Unix Epoch. The number of seconds can be converted to the current date using date() function in PHP. Syntax: int time() Parameter: This function does not accepts any parameters as shown above. Return Value: This function returns the current time measured in the number of seconds since the Unix Epoch. Note: All output of programs corresponds to the date when the article was written. Below programs illustrate the time() function: Program 1: The program below prints the current time in term of seconds. <?php// PHP program to demonstrate the use of current // time in seconds since Unix Epoch // variable to store the current time in seconds $currentTimeinSeconds = time(); // prints the current time in secondsecho $currentTimeinSeconds; ?> Output: 1525376494 Program 2: The program below prints the current time in date format. <?php// PHP program to demonstrate the use of current // date since Unix Epoch // variable to store the current time in seconds $currentTimeinSeconds = time(); // converts the time in seconds to current date $currentDate = date('Y-m-d', $currentTimeinSeconds); // prints the current dateecho ($currentDate); ?> Output: 2018-05-03 PHP-date-time PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n05 May, 2018" }, { "code": null, "e": 279, "s": 53, "text": "The time() function is a built-in function in PHP which returns the current time measured in the number of seconds since the Unix Epoch. The number of seconds can be converte...
Basic Transformations in OPENGL
02 May, 2022 Transformations play a very important role in manipulating objects on the screen. It should be noted that here the algorithms will be implemented in code and the built-in functions will not be used to give a good understanding of how the algorithms work. Also, note that all transformations are implemented in 2D. There are three basic kinds of Transformations in Computer Graphics: 1. Translation 2. Rotation 3. Scaling Algorithms: 1. Translation: Translation refers to moving an object to a different position on the screen. Formula: X = x + tx Y = y + ty where tx and ty are translation coordinates The OpenGL function is glTranslatef( tx, ty, tz ); 2. Rotation: Rotation refers to rotating a point. Formula: X = xcosA - ysinA Y = xsinA + ycosA, A is the angle of rotation. The above formula will rotate the point around the origin. To rotate around a different point, the formula: X = cx + (x-cx)*cosA - (y-cy)*sinA, Y = cy + (x-cx)*sinA + (y-cy)*cosA, cx, cy is centre coordinates, A is the angle of rotation. The OpenGL function is glRotatef (A, x, y, z). 3. Scaling: Scaling refers to zooming in and out an object on different scales across axes. Formula: X = x*sx Y = y*sy, sx, sy being scaling factors. The OpenGL function is glScalef(float x, float y, float z) Note: If combined transformations are to be applied, follow the order: translate, rotate, scale Implementation: C // C code to implement basic// transformations in OPENGL#include <stdio.h>#include <math.h>#include <time.h>#include <GL/glut.h> // Window size#define maxWD 640#define maxHT 480 // Rotation speed#define thetaSpeed 0.05 // This creates delay between// two actionsvoid delay(unsigned int mseconds){ clock_t goal = mseconds + clock(); while (goal > clock());} // This is a basic init for the// glut windowvoid myInit(void){ glClearColor(1.0, 1.0, 1.0, 0.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, maxWD, 0.0, maxHT); glClear(GL_COLOR_BUFFER_BIT); glFlush();} // This function just draws// a pointvoid drawPoint(int x, int y){ glPointSize(7.0); glColor3f(0.0f, 0.0f, 1.0f); glBegin(GL_POINTS); glVertex2i(x, y); glEnd();} void rotateAroundPt(int px, int py, int cx, int cy){ float theta = 0.0; while (1) { glClear(GL_COLOR_BUFFER_BIT); int xf, yf; // Update theta anticlockwise // rotation theta = theta + thetaSpeed; // Check overflow if (theta>= (2.0 * 3.14159)) theta = theta - (2.0 * 3.14159); // actual calculations.. xf = (cx + (int)((float)(px - cx) * cos(theta)) - ((float)(py - cy) * sin(theta))); yf = (cy + (int)((float)(px - cx) * sin(theta)) + ((float)(py - cy) * cos(theta))); // Drawing the centre point drawPoint(cx, cy); // Drawing the rotating point drawPoint(xf, yf); glFlush(); // Creating a delay // So that the point can be noticed delay(10); }} // This function will translate// the pointvoid translatePoint(int px, int py, int tx, int ty){ int fx = px, fy = py; while (1) { glClear(GL_COLOR_BUFFER_BIT); // Update px = px + tx; py = py + ty; // Check overflow to keep // point in screen if (px > maxWD || px < 0 || py > maxHT || py < 0) { px = fx; py = fy; } // Drawing the point drawPoint(px, py); glFlush(); // Creating a delay // So that the point can be noticed delay(10); }} // This function drawsvoid scalePoint(int px, int py, int sx, int sy){ int fx, fy; while (1) { glClear(GL_COLOR_BUFFER_BIT); // Update fx = px * sx; fy = py * sy; // Drawing the point drawPoint(fx, fy); glFlush(); // Creating a delay // So that the point can // be noticed delay(500); glClear(GL_COLOR_BUFFER_BIT); // Update fx = px; fy = py; // Drawing the point drawPoint(fx, fy); glFlush(); // Creating a delay // So that the point can be // noticed delay(500); }} // Actual display functionvoid myDisplay(void){ int opt; printf("\nEnter\n\t<1> for translation" "\n\t<2> for rotation" "\n\t<3> for scaling\n\t:"); scanf("%d", &opt); printf("\nGo to the window..."); switch (opt){ case 1: translatePoint(100, 200, 1, 5); break; case 2: rotateAroundPt(200, 200, maxWD / 2, maxHT / 2); // Point will circle around // the centre of the window break; case 3: scalePoint(10, 20, 2, 3); break; }} // Driver codevoid main(int argc, char** argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(maxWD, maxHT); glutInitWindowPosition(100, 150); glutCreateWindow("Transforming point"); glutDisplayFunc(myDisplay); myInit(); glutMainLoop();} This article is contributed by Suprotik Dey. 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. jalbert5 OpenGL GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You! Geek Streak - 24 Days POTD Challenge What is Hashing | A Complete Tutorial GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge? GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa Roadmap to Learn JavaScript For Beginners Types of Software Testing How To Switch From A Service-Based To A Product-Based Company? What is Data Structure: Types, Classifications and Applications
[ { "code": null, "e": 53, "s": 25, "text": "\n02 May, 2022" }, { "code": null, "e": 475, "s": 53, "text": "Transformations play a very important role in manipulating objects on the screen. It should be noted that here the algorithms will be implemented in code and the built-in fun...
How to Install MongoDB on Windows? - GeeksforGeeks
06 Oct, 2021 MongoDB is an open-source document-oriented database that is designed to store a large scale of data and also allows you to work with that data very efficiently. It is categorized under the NoSQL(Not only SQL) database because the storage and retrieval of data in MongoDB are not in the form of tables. This is the general introduction of MongoDB now we learn how to install MongoDB on your Windows?. You can install MongoDB using two different methods one is using msi and another is using zip. Here, we will discuss how to install MongoDB using msi, so you need to follow each step carefully: Step 1: Go to MongoDB Download Center to download MongoDB Community Server. Here, You can select any version, Windows, and package according to your requirement. For Windows, we need to choose: Version: 4.2.2 OS: WindowsOS Package: msi Step 2: When the download is complete open the msi file and click the next button in the startup screen: Step 3: Now accept the End-User License Agreement and click the next button: Step 4: Now select the complete option to install all the program features. Here, if you can want to install only selected program features and want to select the location of the installation, then use the Custom option: Step 5: Select “Run service as Network Service user” and copy the path of the data directory. Click Next: Step 6: Click the Install button to start the installation process: Step 7: After clicking on the install button installation of MongoDB begins: Step 8: Now click the Finish button to complete the installation process: Step 9: Now we go to the location where MongoDB installed in step 5 in your system and copy the bin path: Step 10: Now, to create an environment variable open system properties << Environment Variable << System variable << path << Edit Environment variable and paste the copied link to your environment system and click Ok: Step 11: After setting the environment variable, we will run the MongoDB server, i.e. mongod. So, open the command prompt and run the following command: mongod When you run this command you will get an error i.e. C:/data/db/ not found. Step 12: Now, Open C drive and create a folder named “data” inside this folder create another folder named “db”. After creating these folders. Again open the command prompt and run the following command: mongod Now, this time the MongoDB server(i.e., mongod) will run successfully. Step 13: Now we are going to connect our server (mongod) with the mongo shell. So, keep that mongod window and open a new command prompt window and write mongo. Now, our mongo shell will successfully connect to the mongod. Important Point: Please do not close the mongod window if you close this window your server will stop working and it will not able to connect with the mongo shell. Now, you are ready to write queries in the mongo Shell. Example: Now you can make a new database, collections, and documents in your shell. Below is an example of how to make a new database: The use Database_name commend makes a new database in the system if it does not exist, if the database exists it uses that database: use gfg Now your database is ready of name gfg. The db.Collection_name commend makes a new collection in the gfg database and the insertOne() method inserts the document in the student collection: db.student.insertOne({Akshay:500}) how-to-install MongoDB Picked How To Installation Guide MongoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install FFmpeg on Windows? How to Set Git Username and Password in GitBash? How to Install Jupyter Notebook on MacOS? How to Add External JAR File to an IntelliJ IDEA Project? How to Create and Setup Spring Boot Project in Eclipse IDE? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Pygame on Windows ? How to Install Jupyter Notebook on MacOS? How to Add External JAR File to an IntelliJ IDEA Project?
[ { "code": null, "e": 24585, "s": 24557, "text": "\n06 Oct, 2021" }, { "code": null, "e": 24986, "s": 24585, "text": "MongoDB is an open-source document-oriented database that is designed to store a large scale of data and also allows you to work with that data very efficiently. I...
Decimal.Multiply() Method in C#
The Decimal.Add() method in C# is used to multiply two specified Decimal values. Following is the syntax − public static decimal Multiply (decimal val1, decimal val2); Above, va1 is the multiplicand, whereas val2 is the multiplier. Let us now see an example to implement the Decimal.Multiply() method − using System; public class Demo { public static void Main(){ Decimal val1 = 3.45m; Decimal val2 = 2.35m; Console.WriteLine("Decimal 1 = "+val1); Console.WriteLine("Decimal 2 = "+val2); Decimal res = Decimal.Multiply(val1, val2); Console.WriteLine("Result (Multiplication) = "+res); } } This will produce the following output − Decimal 1 = 3.45 Decimal 2 = 2.35 Result (Multiplication) = 8.1075 Let us now see another example to implement the Decimal.Multiply() method − using System; public class Demo { public static void Main(){ Decimal val1 = Decimal.MinValue; Decimal val2 = 1.21m; Console.WriteLine("Decimal 1 = "+val1); Console.WriteLine("Decimal 2 = "+val2); Decimal res = Decimal.Multiply(val1, val2); Console.WriteLine("Result (Multiplication) = "+res); } } This will produce the following output displaying exception that the value exceeded for decimal − Decimal 1 = -79228162514264337593543950335 Decimal 2 = 1.21 Run-time exception (line 13): Value was either too large or too small for a Decimal. Stack Trace: [System.OverflowException: Value was either too large or too small for a Decimal.] at System.Decimal.FCallMultiply(Decimal& d1, Decimal& d2) at System.Decimal.Multiply(Decimal d1, Decimal d2) at Demo.Main() :line 13
[ { "code": null, "e": 1143, "s": 1062, "text": "The Decimal.Add() method in C# is used to multiply two specified Decimal values." }, { "code": null, "e": 1169, "s": 1143, "text": "Following is the syntax −" }, { "code": null, "e": 1230, "s": 1169, "text": "publ...
Count the number of occurrences of a particular digit in a number - GeeksforGeeks
05 May, 2021 Given a number N and a digit D, the task is to count the occurrences of D in N.Examples: Input: N = 25, D = 2 Output: 1 Input: N = 100, D = 0 Output: 2 Approach: Take out the digits one by one in N and check if this digit is equal to D. If equal, then increment the count by 1. In the end, print the count.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to count the number of occurrences// of a particular digit in a number #include <iostream>using namespace std; // Function to count the occurrences// of the digit D in Nlong long int countOccurrances(long long int n, int d){ long long int count = 0; // Loop to find the digits of N while (n > 0) { // check if the digit is D count = (n % 10 == d) ? count + 1 : count; n = n / 10; } // return the count of the // occurrences of D in N return count;} // Driver codeint main(){ int d = 2; long long int n = 214215421; cout << countOccurrances(n, d) << endl; return 0;} // Java program to count the number of occurrences// of a particular digit in a numberimport java.util.*; class GFG{ // Function to count the occurrences// of the digit D in Nstatic int countOccurrances(int n, int d){ int count = 0; // Loop to find the digits of N while (n > 0) { // check if the digit is D count = (n % 10 == d) ? count + 1 : count; n = n / 10; } // return the count of the // occurrences of D in N return count;} // Driver codepublic static void main(String args[]){ int d = 2; int n = 214215421; System.out.println(countOccurrances(n, d));}} // This code is contributed by Surendra_Gangwar # Python3 program to count the# number of occurrences of a# particular digit in a number # Function to count the occurrences# of the digit D in Ndef countOccurrances(n, d): count = 0 # Loop to find the digits of N while (n > 0): # check if the digit is D if(n % 10 == d): count = count + 1 n = n // 10 # return the count of the # occurrences of D in N return count # Driver coded = 2n = 214215421print(countOccurrances(n, d)) # This code is contributed by Mohit Kumar // C# program to count the number// of occurrences of a particular// digit in a numberusing System;class GFG{ // Function to count the occurrences// of the digit D in Nstatic int countOccurrances(int n, int d){ int count = 0; // Loop to find the digits of N while (n > 0) { // check if the digit is D count = (n % 10 == d) ? count + 1 : count; n = n / 10; } // return the count of the // occurrences of D in N return count;} // Driver codepublic static void Main(){ int d = 2; int n = 214215421; Console.WriteLine(countOccurrances(n, d));}} // This code is contributed by Code_Mech. <script> // Javascript program to count// the number of occurrences// of a particular digit in a number // Function to count the occurrences// of the digit D in Nfunction countOccurrances(n, d){ let count = 0; // Loop to find the digits of N while (n > 0) { // check if the digit is D count = (n % 10 == d) ? count + 1 : count; n = parseInt(n / 10); } // return the count of the // occurrences of D in N return count;} // Driver code let d = 2; let n = 214215421; document.write(countOccurrances(n, d)); </script> 3 mohit kumar 29 SURENDRA_GANGWAR Code_Mech ManasChhabra2 rishavmahato348 number-digits school-programming Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to find sum of elements in a given array Modulo Operator (%) in C/C++ with Examples The Knight's tour problem | Backtracking-1 Algorithm to solve Rubik's Cube Modular multiplicative inverse Merge two sorted arrays Euclidean algorithms (Basic and Extended) Sieve of Eratosthenes Program to find GCD or HCF of two numbers Find minimum number of coins that make a given value
[ { "code": null, "e": 24858, "s": 24830, "text": "\n05 May, 2021" }, { "code": null, "e": 24949, "s": 24858, "text": "Given a number N and a digit D, the task is to count the occurrences of D in N.Examples: " }, { "code": null, "e": 25013, "s": 24949, "text": ...
Button in C# - GeeksforGeeks
21 May, 2021 A Button is an essential part of an application, or software, or webpage. It allows the user to interact with the application or software. For example, if a user wants to exit from the current application so, he/she click the exit button which closes the application. It can be used to perform many actions like to submit, upload, download, etc. according to the requirement of your program. It can be available with different shape, size, color, etc. and you can reuse them in different applications. In .NET Framework, Button class is used to represent windows button control and it is inherited from ButtonBase class. It is defined under System.Windows.Forms namespace. In C# you can create a button on the windows form by using two different ways:1. Design-Time: It is the easiest method to create a button. Use the below steps: Step 1: Create a windows form as shown in the below image: Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the Button control from the ToolBox and drop it on the windows form. You are allowed to place a Button control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the Button control to set the properties of the Button. 2. Run-Time: It is a little bit trickier than the above method. In this method, you can create your own Button using the Button class. Step 1: Create a button using the Button() constructor is provided by the Button class. // Creating Button using Button class Button MyButton = new Button(); Step 2: After creating Button, set the properties of the Button provided by the Button class. // Set the location of the button Mybutton.Location = new Point(225, 198); // Set text inside the button Mybutton.Text = "Submit"; // Set the AutoSize property of the button Mybutton.AutoSize = true; // Set the background color of the button Mybutton.BackColor = Color.LightBlue; // Set the padding of the button Mybutton.Padding = new Padding(6); // Set font of the text present in the button Mybutton.Font = new Font("French Script MT", 18); Step 3: And last add this button control to form using Add() method. // Add this Button to form this.Controls.Add(Mybutton); Example: CSharp using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the properties of label Label l = new Label(); l.AutoSize = true; l.Text = "Do you want to submit this project?"; l.Location = new Point(222, 145); l.Font = new Font("French Script MT", 18); // Adding this label to form this.Controls.Add(l); // Creating and setting the properties of Button Button Mybutton = new Button(); Mybutton.Location = new Point(225, 198); Mybutton.Text = "Submit"; Mybutton.AutoSize = true; Mybutton.BackColor = Color.LightBlue; Mybutton.Padding = new Padding(6); Mybutton.Font = new Font("French Script MT", 18); // Adding this button to form this.Controls.Add(Mybutton); // Creating and setting the properties of Button Button Mybutton1 = new Button(); Mybutton1.Location = new Point(360, 198); Mybutton1.Text = "Cancel"; Mybutton1.AutoSize = true; Mybutton1.BackColor = Color.LightPink; Mybutton1.Padding = new Padding(6); Mybutton1.Font = new Font("French Script MT", 18); // Adding this button to form this.Controls.Add(Mybutton1); }}} Output: sumitgumber28 C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# Dictionary with examples C# | Method Overriding C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# C# | Delegates Introduction to .NET Framework Difference between Ref and Out keywords in C# Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework HashSet in C# with Examples Partial Classes in C#
[ { "code": null, "e": 23858, "s": 23830, "text": "\n21 May, 2021" }, { "code": null, "e": 24693, "s": 23858, "text": "A Button is an essential part of an application, or software, or webpage. It allows the user to interact with the application or software. For example, if a user w...
Understanding the Normal Distribution (with Python) | by Tony Yiu | Towards Data Science
I’ve been writing about data science for a while now and realized that while I had touched on many subjects, I’ve yet to cover the normal distribution — one of the foundational concepts of statistics. That’s an oversight I intend to fix with this post. Regardless of whether you work in a quantitative field or not, you’ve probably heard of the normal distribution at some point. It’s commonly referred to as the bell curve because well, it looks like a bell. Before we dive into the normal distribution, let’s first go over what a statistical distribution is. Borrowing from my previous post on the binomial distribution: One thing that may trouble newcomers to probability and statistics is the idea of a probability distribution. We tend to think deterministically such as “I flipped a coin 10 times and produced 6 heads”. So the outcome is 6 — where is the distribution then? The probability distribution derives from variance. If both you and I flipped 10 coins, it’s pretty likely that we would get different results (you might get 5 heads and I get 7). This variance, a.k.a. uncertainty around the outcome, produces a probability distribution, which basically tells us what outcomes are relatively more likely (such as 5 heads) and which outcomes are relatively less likely (such as 10 heads). So each set of 10 coin flips is like a random variable. We don’t know beforehand exactly how many heads we will get. But if we know its distribution, then we know which outcomes are probable and which are not. And that’s basically what any statistical distribution tells us — it’s a graph that tells us how likely it is to get each of the possible results. Or another way to think about it, it is what the distribution of outcomes would converge to if we ran an experiment with an uncertain outcome over and over again (collecting the results each time). Now let’s return to the normal distribution. A normally distributed random variable might have a mean of 0 and a standard deviation of 1. What does that mean? That means that we expect the value to be 0 (on average) but the actual realized values of our random variable wiggle around 0. The amount that it wiggles by is 1. I’ve plotted a normal distribution below. The higher the blue line is in the plot, the higher the frequency of seeing that value below it on the x-axis. Notice how a value of 3 or more is extremely unlikely. That’s because our normally distributed random variable has a wiggle amount (standard deviation) of 1, and 3 is three standard deviations away from the mean 0 (really far!). So the individual instances that combine to make the normal distribution are like the outcomes from a random number generator — a random number generator that can theoretically take on any value between negative and positive infinity but that has been preset to be centered around 0 and with most of the values occurring between -1 and 1 (because the standard deviation is 1). Seems simple enough right? The normal distribution just tells us what the outcomes of running a random number generator (with the above mentioned preset characteristics) many, many times would look like. So why is this useful? That’s because many real world phenomena conform to the normal distribution. For example, people’s heights are famously normally distributed. If you survey the heights of 5 of your friends, you will get a wonky looking distribution. But as you increase the number of friends sampled (e.g. all your Facebook friends, assuming you are reasonably social), the distribution will start looking more and more like a normal distribution. In the corporate world, the distribution of the severity of manufacturing defects was found to be normally distributed (this makes sense: usually you make it right, a few times you make it slightly wrong, and once in a blue moon you completely mess it up) — in fact, the process improvement framework Six Sigma was basically built around this observation. In the investment world, the periodic (daily, monthly, even annual) returns of assets like stocks and bonds are assumed to follow a normal distribution. Making this assumption probably understates the likelihood and therefore risk of fat tails (severe market crashes occur more frequently than the models tell us they should), but that is a discussion for another day. In data science and statistics, statistical inference (and hypothesis testing) relies heavily on the normal distribution. Since we like data science, let’s explore this particular application in more depth. When I first learned statistics, I was confused by standard error. I thought, “why do they sometimes call it standard deviation and other times standard error?” Only later did I learn that standard error actually refers to the volatility (standard deviation) of the mean. Why does the mean vary? We are used to thinking of the mean, the expected value of something, as a static value. You take all the heights, divide it by the number of heights, and you get the mean (average) height. This is the expected value. If someone were to ask you to guess (and you can’t give your guess as a range) the height of a person based on no prior information at all, you would guess the mean (that’s why we call it the expected value). But the mean itself is actually a random variable. That’s because our average height is based on a sample — it would be impossible to sample the entire population (everyone in the world), so no matter how large our height study might be, it would still be a sample. So even if we try to be unbiased and pick each sample in a way that is representative of the population, every time we take a new sample, the average calculated from that sample will be a bit different from the prior ones. That’s annoying. If we can’t be certain of the value, then how can we do anything with it? For example, say our friend asked us: “Is the average height of a person greater than 6 feet.” So we get to work and obtain some data (by conducting a quick survey of 10 people standing around us) and calculate the average of our sample to be 5 feet 9 inches. But then we tell our friend, “I don’t know, my sample mean is lower than 6 feet but at the end of the day it might be higher or it might be lower. The mean itself bounces around depending on the sample, so nobody really knows.” That’s not very helpful (and extremely indecisive). After a while, nobody would ask for our insight anymore. This is where the normal distribution comes in — the mean of our sample means is itself a normally distributed random variable. Meaning that if we took a large enough number of samples and calculated the mean for each one, the distribution of those means would be shaped just like the normal distribution. This allows us to make inferences about the overall population even from relatively small samples — meaning from just a few observations, we can learn a great deal about the statistical characteristics of the overall population. In our previous example, the normally distributed random variable had a mean of 0 and a standard deviation of 1. But the mean and standard deviation can be whatever we need it to be. Let’s use some Python code to check out how the normal distribution can help us deliver a better answer to our friend. (For the full code, please check out my GitHub here) First, let’s get our inputs out of the way: import numpy as npfrom scipy.stats import normimport matplotlib.pyplot as pltimport seaborn as sns Now let’s generate some data. We will assume that the true mean height of a person is 5 feet 6 inches and the true standard deviation is 1 foot (12 inches). We also define a variable called “target” of 6 feet, which is the height that our friend inquired about. To make life easier, we will convert everything to inches. mean_height = 5.5*12stdev_height = 1*12target = 6*12 With these parameters, we can now fabricate some height data. We will make a 10,000 by 10 array to hold our survey results, where each row is a survey. Then we will fill out each element of the array with a normally distributed random variable. You can give the random variable function a mean and a standard deviation, but I wanted to show you how to manually customize the mean and standard deviation of your random variable (more intuitive): You can shift the mean by adding a constant to your normally distributed random variable (where the constant is your desired mean). It changes the central location of the random variable from 0 to whatever number you added to it. You can modify the standard deviation of your normally distributed random variable by multiplying a constant to your random variable (where the constant is your desired standard deviation). In the code below, np.random.normal() generates a random number that is normally distributed with a mean of 0 and a standard deviation of 1. Then we multiply it by “stdev_height” to obtain our desired volatility of 12 inches and add “mean_height” to it in order to shift the central location by 66 inches. mean_height + np.random.normal()*stdev_height We can use nested for loops to fill out our survey data and then check that the output conforms to our expectations: height_surveys = np.zeros((10000,10))for i in range(height_surveys.shape[0]): for j in range(height_surveys.shape[1]): height_surveys[i,j] = mean_height +\ np.random.normal()*stdev_heightprint('Mean Height:', round(np.mean(height_surveys)/12,1), 'feet')print('Standard Deviation of Height:', round(np.var(height_surveys)**0.5/12,1), 'foot') When I ran the code, it printed that the mean height was 5.5 feet and the standard deviation of peoples’ heights was 1 foot — these match our inputs. OK cool, we have our survey data. Now let’s do some statistical inference. Assume for a second that we only had the time and resources to run one height survey (of 10 people). And we got the following result: Half the people are taller than 6 feet and half are shorter (the red line denotes 6 feet) — not super informative. The average height in our sample is 69 inches, slightly below 6 feet. Still, we remember that because our sample size is small (only 10 people in a survey), we should expect a lot of variance in our results. The cool thing is that even with just a single survey, we can get a pretty decent estimate of how much the mean varies. And we know the shape of the distribution — it’s normally distributed (hardcore statisticians will say that I need to say it is roughly normally distributed)! Standard Error = Sample Standard Deviation / sqrt(N) Where N is the number of observations (10 in our case) and sqrt denotes taking the square root. The standard error is the standard deviation of the mean (if we keep conducting 10 people surveys and calculating a mean from each, the standard deviation of these means would eventually converge to the standard error). Like we mentioned, the distribution of sample means is the normal distribution. Meaning that if we were to conduct a large number of surveys and look at their individual means in aggregate, we would expect to see a bell curve. Let’s check this out. Recall that earlier we created a 10,000 by 10 array of survey results. Each of our 10,000 rows is a survey. Let’s calculate the mean for each of our 10,000 surveys and plot the histogram via the following lines of code: # Histogram that shows the distribution for the mean of all surveysfig, ax = plt.subplots(figsize=(12,8))sns.distplot(np.mean(height_surveys,axis=1), kde=False, label='Height')ax.set_xlabel("Height in Inches",fontsize=16)ax.set_ylabel("Frequency",fontsize=16)plt.axvline(target, color='red')plt.legend()plt.tight_layout() Which gives us the following histogram — that’s a bell curve if I ever saw one: Now let’s use just our original survey (the first wonky looking histogram I showed) to calculate the distribution. With just a single sample of 10 people, we have no choice but to guess the sample mean to be the true mean (the population mean as they say in statistics). So we will guess the mean to be 69 inches. Now let’s calculate the standard error. The standard deviation of our sample is 12.5 inches: # I picked sample number 35 at random to plot earliernp.var(height_surveys[35])**0.5) # = 12.5 Let’s overlay our inferred distribution, a normal distribution with a mean of 69 inches and a standard deviation of 12.5 inches on the true distribution (from our 10,000 simulated surveys, which we assume to be ground truth). We can do so with the following lines of code where # Compare mean of all surveys with inferred distributionfig, ax = plt.subplots(figsize=(12,8))# Plot histogram of 10,000 sample meanssns.distplot(np.mean(height_surveys,axis=1), kde=False, label='True')# Calculate stats using single samplesample_mean = np.mean(height_surveys[35])sample_stdev = np.var(height_surveys[35])**0.5# Calculate standard errorstd_error = sample_stdev/(height_surveys[35].shape[0])**0.5# Infer distribution using single sampleinferred_dist = [sample_mean + np.random.normal()*\ std_error for i in range(10000)]# Plot histogram of inferred distributionsns.distplot(inferred_dist, kde=False, label='Inferred', color='red')ax.set_xlabel("Height in Inches",fontsize=16)ax.set_ylabel("Frequency",fontsize=16)plt.legend()plt.tight_layout() And we get the following set of histograms: We are somewhat off, but honestly it’s not too bad given that we generated the inferred distribution (in red) with just 10 observations. And we are able to achieve this thanks to the fact that the distribution of sample means is normally distributed. For the curious, the distribution of the sample standard deviations is also roughly normal (where a sample standard deviation is the standard deviation of a single survey of 10 people): # Check out the distribution of the sample standard deviationsvol_dist = np.var(height_surveys, axis=1)**0.5# Histogram that shows the distribution of sample stdevfig, ax = plt.subplots(figsize=(12,8))sns.distplot(vol_dist, kde=False, label='Sample Stdev Distribution')ax.set_xlabel("Inches",fontsize=16)ax.set_ylabel("Frequency",fontsize=16)plt.legend()plt.tight_layout() Which gives us the plot below. That’s a pretty wide range of standard deviations. Does that mean our estimate of standard error is not as reliable as we first thought? Let’s add the standard error distribution (in red) to the plot above (recall that the standard error is a function of the standard deviation). It’s lower (since standard error is standard deviation divided by the square root of the number of observations in each survey). The standard error also wiggles less for the same reason. Even so, that’s still more wiggle than we are comfortable with — but there’s an easy fix. We can easily reduce the wiggle of our standard error distribution by including more observations. Let’s double it to 20 and see what happens — the red histogram has gotten significantly skinnier by just including 10 more people in our survey. Cool! Finally, we can give a better answer to our friend (who was wondering whether the average height of the population was greater than 6 feet). We can do this one of two ways. First, we can just simulate it by generating a bunch of random variables (normally distributed of course). When I ran the code below, I got that 23% of the observations were 6 feet or taller. # Simulation method for answering the question# Generate 10,000 random variablesinferred_dist = [sample_mean + np.random.normal()*\ std_error for i in range(10000)]# Figure out how many are > than targetsum([1 for i in inferred_dist if i>=target])/len(inferred_dist) Or since we know that it’s normally distributed, we can use the cumulative density function to figure out the area under the curve for 6 feet or more (the area under the curve tells us the probability). The single line of code below tells us that the probability of being 6 feet or taller is 23%, the same as above. 1 - norm.cdf(target, loc=sample_mean, scale=std_error) So we should tell our friend that while there is uncertainty given how informal and small our sample was, it’s still more likely than not (given the data that we have) that people’s average height is less than 6 feet (we could also do a more formal hypothesis test, but that’s a story for another time). There are three points that I want you to keep in mind: The normal distribution and its helpful properties allow us to infer a lot about the statistical properties of the underlying population. However, if there is a lot of uncertainty around the correctness of our mean and/or standard deviation, then we are at the risk of garbage in garbage out. We should be especially careful when our sample is very small (rough rule of thumb is 30 or less, but this number depends a lot on the data) or not representative (biased in some way).When possible, always take more observations. Of course, there might be costs that limit your ability to do so. But where you can, more data will greatly increase your ability to make good inferences.And more generally, it’s helpful to think in terms of distributions. Despite how they appear, outcomes are rarely ever deterministic. When you see a value, you want to be concerned not only with what the value is but how it might vary (like for example the temperature in San Francisco). Expecting variance in the outcome prepares us for the unexpected (so cliche I know). The normal distribution and its helpful properties allow us to infer a lot about the statistical properties of the underlying population. However, if there is a lot of uncertainty around the correctness of our mean and/or standard deviation, then we are at the risk of garbage in garbage out. We should be especially careful when our sample is very small (rough rule of thumb is 30 or less, but this number depends a lot on the data) or not representative (biased in some way). When possible, always take more observations. Of course, there might be costs that limit your ability to do so. But where you can, more data will greatly increase your ability to make good inferences. And more generally, it’s helpful to think in terms of distributions. Despite how they appear, outcomes are rarely ever deterministic. When you see a value, you want to be concerned not only with what the value is but how it might vary (like for example the temperature in San Francisco). Expecting variance in the outcome prepares us for the unexpected (so cliche I know). The thought process we just followed is very similar to hypothesis testing (or A/B testing). You can read more about it in this blog post. But more generally, because so many things in the world follow it, the normal distribution allows us to model various phenomena as long as we have a reasonable estimate of the mean and standard deviation. If you want to learn more about how it's used, you can check out the following articles: Learn how the normal distribution can be used to simulate investment and portfolio returns over many years. To hypothesis test whether stocks outperform cash. To simulate the performance of a business. Thanks for reading. Cheers! If you liked this article and my writing in general, please consider supporting my writing by signing up for Medium via my referral link here. Thanks!
[ { "code": null, "e": 425, "s": 172, "text": "I’ve been writing about data science for a while now and realized that while I had touched on many subjects, I’ve yet to cover the normal distribution — one of the foundational concepts of statistics. That’s an oversight I intend to fix with this post." ...
Update each element in tuple list in Python
When it is required to update every element in a tuple list (i.e list of tuples), list comprehension can be used. The list comprehension is a shorthand to iterate through the list and perform operations on it. Below is a demonstration of the same − Live Demo my_list_1 = [(7, 8, 0), (3, 45, 3), (2, 22,4)] print ("The list of tuple is : " ) print(my_list_1) element_to_add = 41 my_result = [tuple(j + element_to_add for j in sub ) for sub in my_list_1] print("List of tuple after update is : ") print(my_result) The list of tuple is : [(7, 8, 0), (3, 45, 3), (2, 22, 4)] List of tuple after update is : [(48, 49, 41), (44, 86, 44), (43, 63, 45)] A list of tuple is defined, and is displayed on the console. An element that needs to be added to the list of tuple is defined. This list of tuple is iterated over, and the element is added to every tuple in the list of tuples. This result is assigned to a value. It is displayed as output on the console.
[ { "code": null, "e": 1176, "s": 1062, "text": "When it is required to update every element in a tuple list (i.e list of tuples), list comprehension can be used." }, { "code": null, "e": 1272, "s": 1176, "text": "The list comprehension is a shorthand to iterate through the list an...
Count all distinct pairs of repeating elements from the array for every array element - GeeksforGeeks
10 Nov, 2021 Given an array arr[] of N integers. For each element in the array, the task is to count the possible pairs (i, j), excluding the current element, such that i < j and arr[i] = arr[j]. Examples: Input: arr[] = {1, 1, 2, 1, 2}Output: 2 2 3 2 3Explanation:For index 1, remaining elements after excluding current element are [1, 2, 1, 2]. So the count is 2.For index 2, remaining elements after excluding element at index 2 are [1, 2, 1, 2]. So the count is 2.For index 3, remaining elements after excluding element at index 3 are [1, 1, 1, 2]. So the count is 3.For index 4, remaining elements after excluding element at index 4 are [1, 1, 2, 2]. So the count is 2.For index 5, remaining elements after excluding element at index 5 are [1, 1, 2, 1. So the count is 3. Input: arr[] = {1, 2, 3, 4}Output: 0 0 0 0Explanation:Since all the elements are distinct, so no pair with equal value exists. Naive Approach: The naive idea is to traverse the given array and for each element exclude the current element from the array and with the remaining array elements find all the possible pairs (i, j) such that arr[i] is equal to arr[j] and i < j. Print the count of pairs for each element. Time Complexity: O(N2)Auxiliary Space: O(N) Efficient Approach: The idea is to store the frequency of every element and count all the possible pairs(say cnt) with the given conditions. After the above steps for each element remove the count of equal possible pairs from the total count cnt and print that value. Follow the below steps to solve the problem: Store the frequency of each element in Map.Create a variable to store the contribution of each element.Contribution of some number x can be calculated as freq[x]*(freq[x] – 1) divided by 2, where freq[x] is the frequency of x.Traverse the given array and remove the contribution of each element from the total count and store it in ans[].Print all the elements stored in ans[]. Store the frequency of each element in Map. Create a variable to store the contribution of each element. Contribution of some number x can be calculated as freq[x]*(freq[x] – 1) divided by 2, where freq[x] is the frequency of x. Traverse the given array and remove the contribution of each element from the total count and store it in ans[]. Print all the elements stored in ans[]. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for// the above approach#include <bits/stdc++.h>#define int long long intusing namespace std; // Function to print the required// count of pairs excluding the// current elementvoid solve(int arr[], int n){ // Store the frequency unordered_map<int, int> mp; for (int i = 0; i < n; i++) { mp[arr[i]]++; } // Find all the count int cnt = 0; for (auto x : mp) { cnt += ((x.second) * (x.second - 1) / 2); } int ans[n]; // Delete the contribution of // each element for equal pairs for (int i = 0; i < n; i++) { ans[i] = cnt - (mp[arr[i]] - 1); } // Print the answer for (int i = 0; i < n; i++) { cout << ans[i] << " "; }} // Driver Codeint32_t main(){ // Given array arr[] int arr[] = { 1, 1, 2, 1, 2 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call solve(arr, N); return 0;} // Java program for// the above approachimport java.util.*;class GFG{ // Function to print the required// count of pairs excluding the// current elementstatic void solve(int arr[], int n){ // Store the frequency HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); for (int i = 0; i < n; i++) { if(mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i]) + 1); } else { mp.put(arr[i], 1); } } // Find all the count int cnt = 0; for (Map.Entry<Integer, Integer> x : mp.entrySet()) { cnt += ((x.getValue()) * (x.getValue() - 1) / 2); } int []ans = new int[n]; // Delete the contribution of // each element for equal pairs for (int i = 0; i < n; i++) { ans[i] = cnt - (mp.get(arr[i]) - 1); } // Print the answer for (int i = 0; i < n; i++) { System.out.print(ans[i] + " "); }} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = {1, 1, 2, 1, 2}; int N = arr.length; // Function Call solve(arr, N);}} // This code is contributed by 29AjayKumar # Python3 program for# the above approach # Function to print required# count of pairs excluding the# current elementdef solve(arr, n): # Store the frequency mp = {} for i in arr: mp[i] = mp.get(i, 0) + 1 # Find all the count cnt = 0 for x in mp: cnt += ((mp[x]) * (mp[x] - 1) // 2) ans = [0] * n # Delete the contribution of # each element for equal pairs for i in range(n): ans[i] = cnt - (mp[arr[i]] - 1) # Print the answer for i in ans: print(i, end = " ") # Driver Codeif __name__ == '__main__': # Given array arr[] arr = [1, 1, 2, 1, 2] N = len(arr) # Function call solve(arr, N) # This code is contributed by mohit kumar 29 // C# program for// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to print the required// count of pairs excluding the// current elementstatic void solve(int []arr, int n){ // Store the frequency Dictionary<int, int> mp = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { if(mp.ContainsKey(arr[i])) { mp[arr[i]] = mp[arr[i]] + 1; } else { mp.Add(arr[i], 1); } } // Find all the count int cnt = 0; foreach (KeyValuePair<int, int> x in mp) { cnt += ((x.Value) * (x.Value - 1) / 2); } int []ans = new int[n]; // Delete the contribution of // each element for equal pairs for (int i = 0; i < n; i++) { ans[i] = cnt - (mp[arr[i]] - 1); } // Print the answer for (int i = 0; i < n; i++) { Console.Write(ans[i] + " "); }} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = {1, 1, 2, 1, 2}; int N = arr.Length; // Function Call solve(arr, N);}} // This code is contributed by 29AjayKumar <script> // Javascript program for// the above approach // Function to print the required// count of pairs excluding the// current elementfunction solve(arr, n){ // Store the frequency var mp = new Map(); for (var i = 0; i < n; i++) { if(mp.has(arr[i])) mp.set(arr[i], mp.get(arr[i])+1) else mp.set(arr[i], 1); } // Find all the count var cnt = 0; mp.forEach((value, key) => { cnt += ((value) * (value - 1) / 2); }); var ans = Array(n); // Delete the contribution of // each element for equal pairs for (var i = 0; i < n; i++) { ans[i] = cnt - (mp.get(arr[i]) - 1); } // Print the answer for (var i = 0; i < n; i++) { document.write( ans[i] + " "); }} // Driver Code// Given array arr[]var arr = [1, 1, 2, 1, 2];var N = arr.length;// Function Callsolve(arr, N); </script> 2 2 3 2 3 Time Complexity: O(NlogN)Auxiliary Space: O(N) mohit kumar 29 29AjayKumar itsok khushboogoyal499 cpp-map frequency-counting Hash Arrays Hash Mathematical Arrays Hash Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Program to find sum of elements in a given array Reversal algorithm for array rotation Trapping Rain Water Find duplicates in O(n) time and O(1) extra space | Set 1 Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Count pairs with given sum Hashing | Set 2 (Separate Chaining)
[ { "code": null, "e": 24716, "s": 24688, "text": "\n10 Nov, 2021" }, { "code": null, "e": 24899, "s": 24716, "text": "Given an array arr[] of N integers. For each element in the array, the task is to count the possible pairs (i, j), excluding the current element, such that i < j a...
How to create a Box (3D) in JavaFX?
A box is a three-dimensional shape with a length (depth), width, and a height. In JavaFX a box is represented by the javafx.scene.shape.Box class. This class contains 3 properties they are − depth − This property represents depth of the box, you can set value to this property using the setDepth() method. depth − This property represents depth of the box, you can set value to this property using the setDepth() method. height − This property represents the height of the box, you can set value to this property using the setHeight() method. height − This property represents the height of the box, you can set value to this property using the setHeight() method. width − This property represents the width of the box, you can set value to this property using the setWidth() method. width − This property represents the width of the box, you can set value to this property using the setWidth() method. To create a 3D Box you need to − Instantiate this class. Instantiate this class. Set the required properties using the setter methods or, by passing them as arguments to the constructor. Set the required properties using the setter methods or, by passing them as arguments to the constructor. Add the created node (shape) to the Group object. Add the created node (shape) to the Group object. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.PerspectiveCamera; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.paint.PhongMaterial; import javafx.stage.Stage; import javafx.scene.shape.Box; import javafx.scene.shape.CullFace; import javafx.scene.shape.DrawMode; public class DrawingBox extends Application { public void start(Stage stage) { //Drawing a Box Box cube = new Box(); //Setting the properties of the Box(cube) cube.setDepth(150.0); cube.setHeight(150.0); cube.setWidth(150.0); //Setting other properties cube.setCullFace(CullFace.BACK); cube.setDrawMode(DrawMode.FILL); PhongMaterial material = new PhongMaterial(); material.setDiffuseColor(Color.BROWN); cube.setMaterial(material); //Translating the box cube.setTranslateX(300.0); cube.setTranslateY(150.0); cube.setTranslateZ(150.0); //Setting the perspective camera PerspectiveCamera cam = new PerspectiveCamera(); cam.setTranslateX(-150); cam.setTranslateY(25); cam.setTranslateZ(150); //Setting the Scene Group root = new Group(cube); Scene scene = new Scene(root, 595, 300, Color.BEIGE); scene.setCamera(cam); stage.setTitle("Drawing A Cube"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1253, "s": 1062, "text": "A box is a three-dimensional shape with a length (depth), width, and a height. In JavaFX a box is represented by the javafx.scene.shape.Box class. This class contains 3 properties they are −" }, { "code": null, "e": 1368, "s": 1253, ...
Interactive Controls in Jupyter Notebooks | by Will Koehrsen | Towards Data Science
There are few actions less efficient in data exploration than re-running the same cell over and over again, each time slightly changing the input parameters. Despite knowing this, I still find myself repeatedly executing cells just to make the slightest change, for example, choosing a different value for a function, selecting various date ranges for analysis, or even adjusting the theme of a plotly visualization. Not only is this inefficient, but it’s also frustrating, disrupting the flow of an exploratory data analysis. The ideal solution to this issue would be interactive controls to change inputs without needing to rewrite or rerun code. Fortunately, as is often the case in Python, someone has already run into this problem and developed a great tool to solve it. In this article, we’ll see how to get started with IPython widgets ( ipywidgets), interactive controls you can build with one line of code. This library allows us to turn Jupyter Notebooks from static documents into interactive dashboards, perfect for exploring and visualizing data. You can view a completely interactive running notebook with the widgets in this article on mybinder by clicking the image below. IPython widgets, unfortunately, do not render on GitHub or nbviewer but you can still access the notebook and run locally. The first step, as usual, is installing the library: pip install ipywidgets . Once that finishes, you can activate widgets for Jupyter Notebook with jupyter nbextension enable --py widgetsnbextension To use with JupyterLab, run: jupyter labextension install @jupyter-widgets/jupyterlab-manager To import the ipywidgetslibrary in a notebook, run import ipywidgets as widgetsfrom ipywidgets import interact, interact_manual Let’s say we have the following dataframe with Medium article statistics (these are my actual stats, you can see how to get them in this article): How can we view all articles with more than 1000 reads? Here’s one way: df.loc[df['reads'] > 1000] But if we want to show articles with more than 500 claps, we have to write another line of code: df.loc[df['claps'] > 500] Wouldn’t it be nice if we could just rapidly change these parameters — both the column and threshold — without writing more code? Try this: @interactdef show_articles_more_than(column='claps', x=5000): return df.loc[df[column] > x] With the @interact decorator, the IPywidgets library automatically gives us a text box and a slider for choosing a column and number! It looks at the inputs to our function and creates interactive controls based on the types. Now we can segment the data using the controls (widgets) without writing code. You may have noticed some problems with the widgets — x can go negative and we had to type in the correct column name. We can fix these by providing specific arguments to the function parameters: Now we get a dropdown for the column (with the options in the list) and an integer slider limited to a range (the format is (start, stop, step) ). Read through the documentation for the full details of how function parameters are mapped to widgets. We can use this same @interact decorator to quickly turn any ordinary function into an interactive widget. For example, we may have a lot of images in a directory we want to quickly look through: import osfrom IPython.display import Image@interactdef show_images(file=os.listdir('images/')): display(Image(fdir+file)) Now we can quickly cycle through all the images without re-running the cell. This might actually be useful if you were building a convolutional neural network and wanted to examine the images your network had missclassified. The uses of widgets for data exploration are boundless. Another simple example is finding correlations between two columns: There are numerous helpful examples on the ipywidgets GitHub. Interactive widgets are especially helpful for selecting data to plot. We can use the same @interact decorator with functions that visualize our data: Here we are using the amazing cufflinks+plotly combination to make an interactive plot with interactive IPython widget controls. You may have noticed the plot was a little slow to update. If that is the case, we can use @interact_manual which requires a button for updating. Now the plot will only be updated when the button is pressed. This is useful for functions that take a while to return an output. To get more from the IPywidgets library, we can make the widgets ourselves and use them int the interact function. One of my favorite widgets is the DatePicker. Say we have a function, stats_for_article_published_between, that takes a start and end date and prints stats for all the articles published between them. We can make this interactive using the following code Now we get two interactive date selection widgets and the values are passed into the function (see notebook for details): Similarly, we can make a function that plots the cumulative total of a column up until a date using the same DataPicker interactive widget. If we want to make the options for one widget dependent on the value of another, we use the observe function. Here, we alter the image browser function to choose both the directory and image. The list of images displayed is updated based on the directory we select. When we want to reuse widgets across cells, we just need to assign them to the output of theinteract function. Now, to reuse the stats widget, we can just call stats.widget in a cell. This lets us reuse our widgets across a notebook. As a note, the widgets are tied to one another meaning the value in one cell will be automatically updated to the value you select for the same widget in another cell. We haven’t gotten close to covering all the capabilities of IPywidgets. For instance, we can link values together, create custom widgets, make buttons, build animations, create a dashboard with tabs, and so on. Take a look at the documentation for further uses. Even with the small amount covered here, I hope you see how interactive controls can enhance a notebook workflow! The Jupyter Notebook is a great data exploration and analysis environment. However, by itself, it doesn’t offer the best functionality. Using tools like notebooks extensions and interactive widgets make the notebook come to life and make our jobs as data scientists more efficient. Furthermore, building widgets and using them in a notebook is simply fun! Writing lots of code to do the same task repeatedly is not enjoyable, but using interactive controls creates a more natural flow for our data explorations and analyses. As always, I welcome feedback and constructive criticism. I can be reached on Twitter @koehrsen_will.
[ { "code": null, "e": 699, "s": 172, "text": "There are few actions less efficient in data exploration than re-running the same cell over and over again, each time slightly changing the input parameters. Despite knowing this, I still find myself repeatedly executing cells just to make the slightest c...
Gibbs Sampling. Yet Another MCMC Method | by Cory Maklin | Towards Data Science
Like other MCMC methods, the Gibbs sampler constructs a Markov Chain whose values converge towards a target distribution. Gibbs Sampling is in fact a specific case of the Metropolis-Hastings algorithm wherein proposals are always accepted. To elaborate, suppose you wanted to sample a multivariate probability distribution. Note: A multivariate probability distribution is a function of multiple variables (i.e. 2 dimensional normal distribution). We don’t know how to sample from the latter directly. However, because of some mathematical convenience or maybe just sheer luck, we happen to know the conditional probabilities. This is where Gibbs sampling comes in. Gibbs Sampling is applicable when the joint distribution is not known explicitly or is difficult to sample from directly, but the conditional distribution of each variable is known and is easier to sample from. We start off by selecting an initial value for the random variables X & Y. Then, we sample from the conditional probability distribution of X given Y = Y0 denoted p(X|Y0). In the next step, we sample a new value of Y conditional on X1, which we just computed. We repeat the procedure for an additional n - 1 iterations, alternating between drawing a new sample from the conditional probability distribution of X and the conditional probability distribution of Y, given the current value of the other random variable. Let’s take a look at an example. Suppose we had the following posterior and conditional probability distributions. where g(y) contains the terms that don’t include x, and g(x) contains the those don’t depend on y. We don’t know the value of C (normalizing constant). However, we do know the conditional probability distributions. Therefore, we can use Gibbs Sampling to approximate the posterior distribution. Note: The conditional probability are in fact normal distributions, and can be rewritten as follows. Given the preceding equations, we proceed to implement the Gibbs Sampling algorithm in Python. To begin, we import the following libraries. import numpy as npimport scipy as spimport matplotlib.pyplot as pltimport pandas as pdimport seaborn as snssns.set() We define the function for the posterior distribution (assume C=1). f = lambda x, y: np.exp(-(x*x*y*y+x*x+y*y-8*x-8*y)/2.) Then, we plot the probability distribution. xx = np.linspace(-1, 8, 100)yy = np.linspace(-1, 8, 100)xg,yg = np.meshgrid(xx, yy)z = f(xg.ravel(), yg.ravel())z2 = z.reshape(xg.shape)plt.contourf(xg, yg, z2, cmap='BrBG') Now, we’ll attempt to estimate the probability distribution using Gibbs Sampling. As we mentioned previously, the conditional probabilities are normal distributions. Therefore, we can express them in terms of mu and sigma. In the following block of code, we define functions for mu and sigma, initialize our random variables X & Y, and set N (the number of iterations). N = 50000x = np.zeros(N+1)y = np.zeros(N+1)x[0] = 1.y[0] = 6.sig = lambda z, i: np.sqrt(1./(1.+z[i]*z[i]))mu = lambda z, i: 4./(1.+z[i]*z[i]) We step through the Gibbs Sampling algorithm. for i in range(1, N, 2): sig_x = sig(y, i-1) mu_x = mu(y, i-1) x[i] = np.random.normal(mu_x, sig_x) y[i] = y[i-1] sig_y = sig(x, i) mu_y = mu(x, i) y[i+1] = np.random.normal(mu_y, sig_y) x[i+1] = x[i] Finally, we plot the results. plt.hist(x, bins=50);plt.hist(y, bins=50); plt.contourf(xg, yg, z2, alpha=0.8, cmap='BrBG')plt.plot(x[::10],y[::10], '.', alpha=0.1)plt.plot(x[:300],y[:300], c='r', alpha=0.3, lw=1) As we can see, the probability distribution obtained using the Gibbs Sampling algorithm does a good job of approximating the target distribution. The Gibbs Sampling is a Monte Carlo Markov Chain method that iteratively draws an instance from the distribution of each variable, conditional on the current values of the other variables in order to estimate complex joint distributions. In contrast to the Metropolis-Hastings algorithm, we always accept the proposal. Thus, Gibbs Sampling can be much more efficient.
[ { "code": null, "e": 411, "s": 171, "text": "Like other MCMC methods, the Gibbs sampler constructs a Markov Chain whose values converge towards a target distribution. Gibbs Sampling is in fact a specific case of the Metropolis-Hastings algorithm wherein proposals are always accepted." }, { "...
PrintWriter close() method in Java with Examples - GeeksforGeeks
31 Jan, 2019 The close() method of PrintWriter Class in Java is used to close the stream. Closing a stream deallocates any value in it or any resources associated with it. The PrintWriter instance once closed won’t work. Also a PrintWriter instance once closed cannot be closed again. Syntax: public void close() Parameters: This method do not accepts any parameter. Return Value: This method do not returns any value. It just closes the Stream. Below methods illustrates the working of close() method: Program 1: // Java program to demonstrate// PrintWriter close() method import java.io.*; class GFG { public static void main(String[] args) { // The string to be written in the Writer String str = "GeeksForGeeks"; try { // Create a PrintWriter instance PrintWriter writer = new PrintWriter(System.out); // Write the above string to this writer // This will put the string in the stream // till it is printed on the console writer.write(str); // Now close the stream // using close() method writer.close(); } catch (Exception e) { System.out.println(e); } }} GeeksForGeeks Program 2: // Java program to demonstrate// PrintWriter close() method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a PrintWriter instance PrintWriter writer = new PrintWriter(System.out); // Write the char to this writer // This will put the char in the stream // till it is printed on the console writer.write(65); // Now close the stream // using close() method writer.close(); } catch (Exception e) { System.out.println(e); } }} A Java-Functions Java-IO package Java-PrintWriter Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25911, "s": 25883, "text": "\n31 Jan, 2019" }, { "code": null, "e": 26183, "s": 25911, "text": "The close() method of PrintWriter Class in Java is used to close the stream. Closing a stream deallocates any value in it or any resources associated with it. The ...
p5.js | strokeCap() Function - GeeksforGeeks
05 Sep, 2019 The strokeCap() function in p5.js is used to set the style of line endings. The ends of line can be rounded, squared or extended based on their parameters SQUARE, PROJECT, and ROUND. The default value is ROUND. Syntax: strokeCap( cap ) Parameters: This function accepts single parameter cap which holds the style of end of line (ROUND, SQUARE or PROJECT). Example: This example shows all the different kinds of line ending edges. function setup() { // Create canvas of given size createCanvas(400, 400);} function draw() { // Set the background color background(50); // Set the weight of line stroke strokeWeight(15); // Set the color of line stroke stroke(20, 250, 100); // Set different edges style strokeCap(SQUARE); line(100, 200, 300, 200); strokeCap(ROUND); line(100, 100, 300, 100); strokeCap(PROJECT); line(100, 300, 300, 300);} Output: Reference: https://p5js.org/reference/#/p5/strokeCap JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 44937, "s": 44909, "text": "\n05 Sep, 2019" }, { "code": null, "e": 45148, "s": 44937, "text": "The strokeCap() function in p5.js is used to set the style of line endings. The ends of line can be rounded, squared or extended based on their parameters SQUARE, ...
GATE | GATE-CS-2004 | Question 23 - GeeksforGeeks
28 Jun, 2021 Identify the correct translation into logical notation of the following assertion. "Some boys in the class are taller than all the girls" Note : taller(x,y) is true if x is taller than y. (A) (∃x) (boy(x) → (∀y) (girl(y) ∧ taller(x,y)))(B) (∃x) (boy(x) ∧ (∀y) (girl(y) ∧ taller(x,y)))(C) (∃x) (boy(x) → (∀y) (girl(y) → taller(x,y)))(D) (∃x) (boy(x) ∧ (∀y) (girl(y) → taller(x,y)))Answer: (D)Explanation:Now many people get confused when to use ∧ and when to use →. This question tests exactly that. We use ∧ when we want to say that the both predicates in this statement are always true, no matter what the value of x is.We use → when we want to say that although there is no need for left predicate to be true always, but whenever it becomes true, right predicate must also be true. D means there exist some boys x which taller than all girls y. Quiz of this Question GATE-CS-2004 GATE-GATE-CS-2004 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25721, "s": 25693, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25804, "s": 25721, "text": "Identify the correct translation into logical notation of the following assertion." }, { "code": null, "e": 25860, "s": 25804, "text": "\"Some ...
_Find_first() function in C++ bitset with Examples - GeeksforGeeks
03 Dec, 2019 The _Find_first() is a built-in function in C++ Biteset class which returns an integer that refers the position of first set bit in bitset. If there isn’t any set bit, _Find_first() will return the size of the bitset. Syntax: iterator bitset._Find_first() or int bitset._Find_first() Parameters: The function accepts no parameter. Return Value: The function returns an integer which refers to the position of first set bit in bitset. If there isn’t any set bit, _Find_first() will return the size of the bitset. Below is the illustration of the above function: // C++ program for illustration// of _Find_first() function #include <bits/stdc++.h>using namespace std; #define M 32 int main(){ // default constructor initializes with all bits 0 bitset<M> bset; bitset<M> bset1; // 00000000000000000000000000100000 bset[5] = 1; // 00000000000000000000010000100000 bset[10] = 1; // function returns the first set bit in Bitset cout << "position of first set bit in bset\n"; cout << bset._Find_first() << "\n"; // function returns bset1.size() // when no bit is set in bitset. cout << "position of first set bit in bset1\n"; cout << bset1._Find_first() << "\n"; return 0;} position of first set bit in bset 5 position of first set bit in bset1 32 Reference: https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-3.4/bitset-source.html CPP-bitset CPP-Functions C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Inline Functions in C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++
[ { "code": null, "e": 25343, "s": 25315, "text": "\n03 Dec, 2019" }, { "code": null, "e": 25561, "s": 25343, "text": "The _Find_first() is a built-in function in C++ Biteset class which returns an integer that refers the position of first set bit in bitset. If there isn’t any set ...
Zoom In and Out to TextView in Android - GeeksforGeeks
14 Apr, 2021 In this article, we are going to implement the zoom in and zoom out feature in TextView. As we zoom we will see the image after zoom in. Basically, we are going to learn how to increase or decrease the text size in android. A sample GIF 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: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:id="@+id/zoomin" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:gravity="center" android:text="GeeksForGeeks" android:textColor="#CE1D59" android:textSize="32sp" /> </LinearLayout> Step 3: 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.view.MotionEvent;import android.view.View;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity implements View.OnTouchListener { TextView text; final static float move = 200; float ratio = 1.0f; int bastDst; float baseratio; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text = findViewById(R.id.zoomin); text.setTextSize(ratio + 15); } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getPointerCount() == 2) { int action = event.getAction(); int mainaction = action & MotionEvent.ACTION_MASK; if (mainaction == MotionEvent.ACTION_POINTER_DOWN) { bastDst = getDistance(event); baseratio = ratio; } else { // if ACTION_POINTER_UP then after finding the distance // we will increase the text size by 15 float scale = (getDistance(event) - bastDst) / move; float factor = (float) Math.pow(2, scale); ratio = Math.min(1024.0f, Math.max(0.1f, baseratio * factor)); text.setTextSize(ratio + 15); } } return true; } // get distance between the touch event private int getDistance(MotionEvent event) { int dx = (int) (event.getX(0) - event.getX(1)); int dy = (int) (event.getY(0) - event.getY(1)); return (int) Math.sqrt(dx * dx + dy * dy); } @Override public boolean onTouch(View v, MotionEvent event) { return false; }} Output: Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 26381, "s": 26353, "text": "\n14 Apr, 2021" }, { "code": null, "e": 26770, "s": 26381, "text": "In this article, we are going to implement the zoom in and zoom out feature in TextView. As we zoom we will see the image after zoom in. Basically, we are going to...
PHP | array_diff() function - GeeksforGeeks
23 Oct, 2019 The array_diff() is an inbuilt function in PHP ans is used to calculate the difference between two or more arrays. This function computes difference according to the values of the elements, between one or more array and return differences in the form of a new array. This function basically returns all the entries that are present in the first array which are not present in any other arrays. Syntax: array_diff($array1, $array2, $array3, ...,$arrayn) Parameters: The function can take any number of arrays as parameters needed to be compared. Return Type: This function compares the first array in parameters with rest of the arrays and returns an array containing all the entries from $array1 that are not present in any of the other arrays. Examples: Input : $array1 = ('a', 'b', 'c'); $array2 = ('a', 'd', 'e'); $array3 = ('a', 'b', 'f'); array_diff($array1, $array2, $array3); Output : Array ( [2] => c ) Input : $array1 = ('a', 'b', 'a'); $array2 = ('a', 'd', 'e'); Output : Array ( [1] => b ) Below program illustrates the working of array_diff() in PHP: <?php// PHP code to illustrate the working of array_diff()function Difference($array1, $array2, $array3){ return(array_diff($array1, $array2, $array3));} // Driver Code$array1 = array('a', 'b', 'c', 'd', 'e', 'f');$array2 = array('a', 'b', 'g', 'h');$array3 = array('a', 'f', 'i');print_r(Difference($array1, $array2, $array3));?> Output: Array ( [2] => c [3] => d [4] => e ) Important points to note: It compares the elements in their string representation. That is, 1 and ‘1’ are both equal for array_diff(). The number of repetition of element in first array doesn’t matter. That is if an element occurs 3 times in $array1 and only 1 time in other arrays then all of the 3 occurrences of that element in first array will be omitted in output. For multi-dimensional arrays, we need to compare each of the dimensions separately. For example:- $array1[2],$array2[2] etc. Reference: http://php.net/manual/en/function.array-diff.php 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 ? How to convert array to string in PHP ? PHP in_array() Function How to pop an alert message box using PHP ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 42139, "s": 42111, "text": "\n23 Oct, 2019" }, { "code": null, "e": 42533, "s": 42139, "text": "The array_diff() is an inbuilt function in PHP ans is used to calculate the difference between two or more arrays. This function computes difference according to t...
Economical Numbers - GeeksforGeeks
16 Jul, 2021 Economical Number is a number N if the number of digits in the prime factorization of N (including powers) is less than the number of digits in N.The first few Economical numbers are: 125, 128, 243, 256, 343, 512, 625, 729, ... Given a number N, the task is to print all Economical Numbers upto N.Examples: Input: N = 200 Output: 125 128Input: N = 700 Output: 125 128 243 256 343 512 625 Approach: Count all primes upto 10^6 using Sieve of Sundaram.Find number of digits in N.Find all prime factors of N and do following for every prime factor P. Find number of digits in P.Count highest power of P that divides N.Find sum of above two.If digits in prime factors is less than digits in original number then return true. Else return false. Count all primes upto 10^6 using Sieve of Sundaram. Find number of digits in N. Find all prime factors of N and do following for every prime factor P. Find number of digits in P.Count highest power of P that divides N.Find sum of above two. Find number of digits in P. Count highest power of P that divides N. Find sum of above two. If digits in prime factors is less than digits in original number then return true. Else return false. Below is the implementation of the approach: C++ Java Python3 C# // C++ implementation to find// Economical Numbers till n #include <bits/stdc++.h>using namespace std;const int MAX = 10000; // Array to store all prime less// than and equal to MAX.vector<int> primes; // Utility function for sieve of sundaramvoid sieveSundaram(){ // In general Sieve of Sundaram, // produces primes smaller // than (2*x + 2) for a number // given number x. Since // we want primes smaller than MAX, // we reduce MAX to half bool marked[MAX / 2 + 1] = { 0 }; // Main logic of Sundaram. Mark all numbers which // do not generate prime number by doing 2*i+1 for (int i = 1; i <= (sqrt(MAX) - 1) / 2; i++) for (int j = (i * (i + 1)) << 1; j <= MAX / 2; j = j + 2 * i + 1) marked[j] = true; // Since 2 is a prime number primes.push_back(2); // Print other primes. Remaining primes are of the // form 2*i + 1 such that marked[i] is false. for (int i = 1; i <= MAX / 2; i++) if (marked[i] == false) primes.push_back(2 * i + 1);} // Function to check if a number is// a Economical numberbool isEconomical(int n){ if (n == 1) return false; // Count digits in original number int original_no = n; int sumDigits = 0; while (original_no > 0) { sumDigits++; original_no = original_no / 10; } // Count all digits in prime factors of n // pDigit is going to hold this value. int pDigit = 0, count_exp = 0, p; for (int i = 0; primes[i] <= n / 2; i++) { // Count powers of p in n while (n % primes[i] == 0) { // If primes[i] is a prime factor, p = primes[i]; n = n / p; // Count the power of prime factors count_exp++; } // Add its digits to pDigit. while (p > 0) { pDigit++; p = p / 10; } // Add digits of power of // prime factors to pDigit. while (count_exp > 1) { pDigit++; count_exp = count_exp / 10; } } // If n!=1 then one prime // factor still to be // summed up; if (n != 1) { while (n > 0) { pDigit++; n = n / 10; } } // If digits in prime factors is less than // digits in original number then // return true. Else return false. return (pDigit < sumDigits);} // Driver codeint main(){ // Finding all prime numbers // before limit. These // numbers are used to // find prime factors. sieveSundaram(); for (int i = 1; i < 200; i++) if (isEconomical(i)) cout << i << " "; return 0;} // Java implementation to find// Economical Numbers till nimport java.util.*;class GFG{ static int MAX = 10000; // Array to store all prime less// than and equal to MAX.static Vector<Integer> primes = new Vector<Integer>(); // Utility function for sieve of sundaramstatic void sieveSundaram(){ // In general Sieve of Sundaram, // produces primes smaller // than (2*x + 2) for a number // given number x. Since // we want primes smaller than MAX, // we reduce MAX to half boolean []marked = new boolean[MAX / 2 + 1]; // Main logic of Sundaram. Mark all numbers which // do not generate prime number by doing 2*i+1 for (int i = 1; i <= (Math.sqrt(MAX) - 1) / 2; i++) for (int j = (i * (i + 1)) << 1; j <= MAX / 2; j = j + 2 * i + 1) marked[j] = true; // Since 2 is a prime number primes.add(2); // Print other primes. Remaining primes are of the // form 2*i + 1 such that marked[i] is false. for (int i = 1; i <= MAX / 2; i++) if (marked[i] == false) primes.add(2 * i + 1);} // Function to check if a number is// a Economical numberstatic boolean isEconomical(int n){ if (n == 1) return false; // Count digits in original number int original_no = n; int sumDigits = 0; while (original_no > 0) { sumDigits++; original_no = original_no / 10; } // Count all digits in prime factors of n // pDigit is going to hold this value. int pDigit = 0, count_exp = 0, p = 0; for (int i = 0; primes.get(i) <= n / 2; i++) { // Count powers of p in n while (n % primes.get(i) == 0) { // If primes[i] is a prime factor, p = primes.get(i); n = n / p; // Count the power of prime factors count_exp++; } // Add its digits to pDigit. while (p > 0) { pDigit++; p = p / 10; } // Add digits of power of // prime factors to pDigit. while (count_exp > 1) { pDigit++; count_exp = count_exp / 10; } } // If n!=1 then one prime // factor still to be // summed up; if (n != 1) { while (n > 0) { pDigit++; n = n / 10; } } // If digits in prime factors is less than // digits in original number then // return true. Else return false. return (pDigit < sumDigits);} // Driver codepublic static void main(String[] args){ // Finding all prime numbers // before limit. These // numbers are used to // find prime factors. sieveSundaram(); for (int i = 1; i < 200; i++) if (isEconomical(i)) System.out.print(i + " ");}} // This code is contributed by Rajput-Ji # Python3 implementation to find# Economical Numbers till nimport mathMAX = 10000 # Array to store all prime less# than and equal to MAX.primes = [] # Utility function for sieve of sundaramdef sieveSundaram(): # In general Sieve of Sundaram, # produces primes smaller # than (2*x + 2) for a number # given number x. Since # we want primes smaller than MAX, # we reduce MAX to half marked = [0] * (MAX // 2 + 1) # Main logic of Sundaram. Mark all numbers which # do not generate prime number by doing 2*i+1 for i in range(1, (int(math.sqrt(MAX)) - 1) // 2 + 1): j = (i * (i + 1)) << 1 while(j <= MAX // 2): marked[j] = True j = j + 2 * i + 1 # Since 2 is a prime number primes.append(2) # Prother primes. Remaining primes are of the # form 2*i + 1 such that marked[i] is false. for i in range(1, MAX // 2 + 1): if (marked[i] == False): primes.append(2 * i + 1) # Function to check if a number is# a Economical numberdef isEconomical(n): if (n == 1): return False # Count digits in original number original_no = n sumDigits = 0 while (original_no > 0): sumDigits += 1 original_no = original_no // 10 # Count all digits in prime factors of n # pDigit is going to hold this value. pDigit = 0 count_exp = 0 i = 0 p = 0 while(primes[i] <= n // 2): # Count powers of p in n while (n % primes[i] == 0): # If primes[i] is a prime factor, p = primes[i] n = n // p # Count the power of prime factors count_exp += 1 i += 1 # Add its digits to pDigit. while (p > 0): pDigit += 1 p = p // 10 # Add digits of power of # prime factors to pDigit. while (count_exp > 1): pDigit += 1 count_exp = count_exp // 10 # If n!=1 then one prime # factor still to be # summed up if (n != 1): while (n > 0): pDigit += 1 n = n // 10 # If digits in prime factors is less than # digits in original number then # return true. Else return false. if (pDigit < sumDigits): return True return False # Driver code # Finding all prime numbers# before limit. These# numbers are used to# find prime factors.sieveSundaram() for i in range(1, 200): if (isEconomical(i)): print(i, end = " ") # This code is contributed by shubhamsingh10 // C# implementation to find// Economical Numbers till nusing System;using System.Collections.Generic; class GFG{ static int MAX = 10000; // Array to store all prime less// than and equal to MAX.static List<int> primes = new List<int>(); // Utility function for sieve of sundaramstatic void sieveSundaram(){ // In general Sieve of Sundaram, // produces primes smaller // than (2*x + 2) for a number // given number x. Since // we want primes smaller than MAX, // we reduce MAX to half bool[] marked = new bool[MAX / 2 + 1]; // Main logic of Sundaram. Mark all numbers which // do not generate prime number by doing 2*i+1 for(int i = 1; i <= (Math.Sqrt(MAX) - 1) / 2; i++) for(int j = (i * (i + 1)) << 1; j <= MAX / 2; j = j + 2 * i + 1) marked[j] = true; // Since 2 is a prime number primes.Add(2); // Print other primes. Remaining primes are of the // form 2*i + 1 such that marked[i] is false. for(int i = 1; i <= MAX / 2; i++) if (marked[i] == false) primes.Add(2 * i + 1);} // Function to check if a number is// a Economical numberstatic bool isEconomical(int n){ if (n == 1) return false; // Count digits in original number int original_no = n; int sumDigits = 0; while (original_no > 0) { sumDigits++; original_no = original_no / 10; } // Count all digits in prime factors of n // pDigit is going to hold this value. int pDigit = 0, count_exp = 0, p = 0; for(int i = 0; primes[i] <= n / 2; i++) { // Count powers of p in n while (n % primes[i] == 0) { // If primes[i] is a prime factor, p = primes[i]; n = n / p; // Count the power of prime factors count_exp++; } // Add its digits to pDigit. while (p > 0) { pDigit++; p = p / 10; } // Add digits of power of // prime factors to pDigit. while (count_exp > 1) { pDigit++; count_exp = count_exp / 10; } } // If n!=1 then one prime // factor still to be // summed up; if (n != 1) { while (n > 0) { pDigit++; n = n / 10; } } // If digits in prime factors is less than // digits in original number then // return true. Else return false. return (pDigit < sumDigits);} // Driver codepublic static void Main(String[] args){ // Finding all prime numbers // before limit. These // numbers are used to // find prime factors. sieveSundaram(); for(int i = 1; i < 200; i++) if (isEconomical(i)) Console.Write(i + " ");}} // This code is contributed by Rajput-Ji 125 128 Time Complexity: O(n1/2) Auxiliary Space: O(1) Reference: https://mathworld.wolfram.com/EconomicalNumber.html SHUBHAMSINGH10 Rajput-Ji souravmahato348 series Arrays Mathematical Arrays Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Program for Fibonacci numbers Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) C++ Data Types Coin Change | DP-7
[ { "code": null, "e": 25885, "s": 25857, "text": "\n16 Jul, 2021" }, { "code": null, "e": 26071, "s": 25885, "text": "Economical Number is a number N if the number of digits in the prime factorization of N (including powers) is less than the number of digits in N.The first few Eco...
JSON Parsing in Android - GeeksforGeeks
23 Oct, 2020 JSON (JavaScript Object Notation) is a straightforward data exchange format to interchange the server’s data, and it is a better alternative for XML. This is because JSON is a lightweight and structured language. Android supports all the JSON classes such as JSONStringer, JSONObject, JSONArray, and all other forms to parse the JSON data and fetch the required information by the program. JSON’s main advantage is that it is a language-independent, and the JSON object will contain data like a key/value pair. In general, JSON nodes will start with a square bracket ([) or with a curly bracket ({). The square and curly bracket’s primary difference is that the square bracket ([) represents the beginning of a JSONArray node. Whereas, the curly bracket ({) represents a JSONObject. So one needs to call the appropriate method to get the data. Sometimes JSON data start with [. We then need to use the getJSONArray() method to get the data. Similarly, if it starts with {, then we need to use the getJSONobject() method. The syntax of the JSON file is as following: { "Name": "GeeksforGeeks", "Estd": 2009, "age": 10, "address": { "buildingAddress": "5th & 6th Floor Royal Kapsons, A- 118", "city": "Sector- 136, Noida", "state": "Uttar Pradesh (201305)", "postalCode": "201305" }, In this article, we are going to parse a JSON file in Android. Note that we are going to implement this project using the Kotlin language. To parse a JSON file in Android, follow the following steps: 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 Kotlin as the programming language. Step 2: Working with the activity_main.xml file Go to the activity_main.xml file which represents the UI of the application. Create a ListView as shown. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <!--This listView will display the list items--> <ListView android:id="@+id/user_list" android:layout_width="fill_parent" android:layout_height="wrap_content" android:dividerHeight="1dp" /> </LinearLayout> Step 3: Create another layout resource file Go to app > res > layout > right-click > New > Layout Resource File and create another layout list_row.xml to show the data in the ListView. Below is the code for the list_row.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="5dip"> <!--TextView to display the name--> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="17dp" android:textStyle="bold" /> <!--TextView to display the designation--> <TextView android:id="@+id/designation" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/name" android:layout_marginTop="7dp" android:textColor="#343434" android:textSize="14dp" /> <!--TextView to display the location--> <TextView android:id="@+id/location" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/designation" android:layout_alignBottom="@+id/designation" android:layout_alignParentRight="true" android:textColor="#343434" android:textSize="14dp" /></RelativeLayout> Step 4: Working with the MainActivity.kt file Go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import android.os.Bundleimport android.util.Logimport android.widget.ListAdapterimport android.widget.ListViewimport android.widget.SimpleAdapterimport androidx.appcompat.app.AppCompatActivityimport org.json.JSONExceptionimport org.json.JSONObjectimport java.util.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // private string declare in the latter section of the program val jsonStr = listData try { // Create a userList string hashmap arraylist val userList = ArrayList<HashMap<String, String?>>() // Declaring the listView from the layout file val lv = findViewById<ListView>(R.id.user_list) // Initializing the JSON object and extracting the information val jObj = JSONObject(jsonStr) val jsonArry = jObj.getJSONArray("users") for (i in 0 until jsonArry.length()) { val user = HashMap<String, String?>() val obj = jsonArry.getJSONObject(i) user["name"] = obj.getString("name") user["designation"] = obj.getString("designation") user["location"] = obj.getString("location") userList.add(user) } // ListAdapter to broadcast the information to the list elements val adapter: ListAdapter = SimpleAdapter( this, userList, R.layout.list_row, arrayOf("name", "designation", "location"), intArrayOf( R.id.name, R.id.designation, R.id.location ) ) lv.adapter = adapter } catch (ex: JSONException) { Log.e("JsonParser Example", "unexpected JSON exception", ex) } } // JSON object in the form of input stream private val listData: String get() = ("{ \"users\" :[" + "{\"name\":\"Ace\",\"designation\":\"Engineer\",\"location\":\"New York\"}" + ",{\"name\":\"Tom\",\"designation\":\"Director\",\"location\":\"Chicago\"}" + ",{\"name\":\"Tim\",\"designation\":\"Charted Accountant\",\"location\":\"Sunnyvale\"}] }")} android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Resource Raw Folder in Android Studio Services in Android with Example Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Android UI Layouts Kotlin Array Services in Android with Example Android RecyclerView in Kotlin
[ { "code": null, "e": 26425, "s": 26397, "text": "\n23 Oct, 2020" }, { "code": null, "e": 27491, "s": 26425, "text": "JSON (JavaScript Object Notation) is a straightforward data exchange format to interchange the server’s data, and it is a better alternative for XML. This is becau...
turtle.circle() method in Python - GeeksforGeeks
01 Aug, 2020 The Turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. This method is used to draw a circle with a given radius. Syntax: turtle.circle(radius, extent=None, steps=None) Parameters: radius: Radius of the circle. extent: The part of the circle in degrees as an arc. steps: Divide the shape in the equal number of given steps. Below is the implementation of the above method with some examples : Example 1: Python3 # importing turtle packageimport turtle # draw circle of radius # 80 pixelturtle.circle(80) Output : Example 2: Python3 # importing turtle packageimport turtle # draw circle of radius 80 # pixel and extent = 180# so it draw half circleturtle.circle(80, extent = 180) Output : Example 3: Python3 # importing turtle packageimport turtle # draw circle of radius 80# pixel and steps = 5# so it draw pentagon with# equal length 5 sidesturtle.circle(80, steps = 5) Output : Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25561, "s": 25533, "text": "\n01 Aug, 2020" }, { "code": null, "e": 25778, "s": 25561, "text": "The Turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it...
How to Mock AWS DynamoDB Services for Unit Testing? - GeeksforGeeks
24 Nov, 2020 In this article, we will be understanding how to mock out DynamoDB resources with the help of short examples. But before this, first, we have to make out why we use mocking for testing purposes? Mocking is something where we try to make a copy or replica of some resources that are required for testing purposes. Sounds confusing right? In simple terms we make a copy of something so that we can test each and every aspect of anything without having the fear of being lost or updated something important. Let’s suppose we are having a function that writes the given data into the given DynamoDB table as shown below. This is the simplest method that we can take to illustrate the working of mocking AWS DynamoDB. In the given function, it uses DynamoDB resources to store the data. So, here we will be mocking the AWS DynamoDB with the help of the Moto Python module. Moto is very easy & convenient to implement. Python3 # store.py def write(data, table_name): dynamodb = boto3.resource('dynamodb') table = dynamodb.Table(table_name) with table.batch_writer() as batch: batch.put_item(Item=data) For mocking this function we will use a few steps as follows – At first, build the skeleton by importing the necessary modules & decorating our test method with @mock_dynamodb2. Create a new file called test_write_into_table.py and add the following line: Python3 import boto3from moto import mock_dynamodb2import store @mock_dynamodb2def test_write_into_table(): "Test the write_into_table with a valid input data" Now, within the test_write_into_table() method, create a DynamoDB resource like following – dynamodb = boto3.resource('dynamodb') Let’s create a DynamoDB table using the DynamoDB resource like below-given code. There we created a table named ‘test’ with primary key ‘date’ of type string(‘S’). Python3 table_name = 'test'table = dynamodb.create_table(TableName=table_name, KeySchema=[{'AttributeName': 'date','KeyType': 'HASH'}], AttributeDefinitions=[{'AttributeName': 'date','AttributeType': 'S'}]) Here, we will create input data to store.write(), which will also act as the expected data after reading. data = {'date' : '06-Nov-2020','organization' : 'GeeksforGeeks','articles' : 123456} For better understanding, we took single data but one can have more as per the requirement. After writing the above data into the table, the table will look as follows – At this point, when store.write() is executed, it should store the given input data to the corresponding given table. store.write(data,table_name) Let’s read the data by passing ‘date’ as the primary key. Note that we are getting a dictionary with a couple of keys, so for getting our data we have to fetch the value of the ‘Item’ key. response = table.get_item(Key={'date':data['date']}) actual_output = response['Item'] Let’s assert that the body of the data is the same as we stored. assert actual_output == data Complete Source Code: Python3 """Example of using moto to mock out DynamoDB table""" import boto3from moto import mock_dynamodb2import store @mock_dynamodb2def test_write_into_table(): "Test the write_into_table with a valid input data" dynamodb = boto3.resource('dynamodb') table_name = 'test' table = dynamodb.create_table(TableName = table_name, KeySchema = [ {'AttributeName': 'date', 'KeyType': 'HASH'}], AttributeDefinitions = [ {'AttributeName': 'date', 'AttributeType': 'S'}]) data = {'date': '06-Nov-2020', 'organization': 'GeeksforGeeks', 'articles': 123456} store.write(data, table_name) response = table.get_item(Key={'date': data['date']}) actual_output = response['Item'] assert actual_output == data Output : DynamoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Best Time to Buy and Sell Stock Must Do Coding Questions for Product Based Companies What is Transmission Control Protocol (TCP)? How to Convert Categorical Variable to Numeric in Pandas? How to Replace Values in Column Based on Condition in Pandas? How to Fix: SyntaxError: positional argument follows keyword argument in Python C Program to read contents of Whole File How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE? Insert Image in a Jupyter Notebook How to Replace Values in a List in Python?
[ { "code": null, "e": 25303, "s": 25275, "text": "\n24 Nov, 2020" }, { "code": null, "e": 25808, "s": 25303, "text": "In this article, we will be understanding how to mock out DynamoDB resources with the help of short examples. But before this, first, we have to make out why we us...
Reflexive Access-List - GeeksforGeeks
29 Oct, 2021 By default, an access-list doesn’t keep track of the sessions. An access list consists of various permit and denies rules which are scanned from top to bottom. If any of the conditions match then it is executed and no other condition is matched. For a very small office, a reflexive Access-list acts as a stateful firewall as it allows only the traffic that is initiated within the network and denies other packets coming from outside the network. Reflexive Access-list – Reflexive Access-list is an access-list that allows only the replies of the packets of the sessions initiated within the network (from the outside network). Working – When a session is initiated within the network and goes outside the network through the router (operating reflexive Access-list), reflexive Access-list are triggered. Therefore, it creates a temporary entry for the traffic which is initiated within the network and allows only those traffic from the outside network which is a part of the session (traffic generated within the network). This temporary entry is removed when the session ends. characteristics of temporary entry – The entry specifies the same source and destination address as the original outbound packet (the packet going outside the network), except they are swapped when coming from outside the network. The entries should have the same source and destination port number as the original outbound packet, except they are swapped when coming from outside the network. The entry should have the same protocol as the original outbound packet. The entry specifies the same source and destination address as the original outbound packet (the packet going outside the network), except they are swapped when coming from outside the network. The entries should have the same source and destination port number as the original outbound packet, except they are swapped when coming from outside the network. The entry should have the same protocol as the original outbound packet. Characteristics of Reflexive access-list – Reflexive Access-list should be nested inside the named Extended Access-list. It cannot be applied directly to an interface. A temporary entry is generated when a session begins and automatically destroyed when the session ends. It does not have implicit deny at the end of the Access-list. Just like a normal access list, if one of the conditions matches then no more entries are evaluated. Reflexive Access-list cannot be defined with numbered Access-list Reflexive Access-list cannot be defined with named or numbered standard Access-list. Reflexive Access-list should be nested inside the named Extended Access-list. It cannot be applied directly to an interface. A temporary entry is generated when a session begins and automatically destroyed when the session ends. It does not have implicit deny at the end of the Access-list. Just like a normal access list, if one of the conditions matches then no more entries are evaluated. Reflexive Access-list cannot be defined with numbered Access-list Reflexive Access-list cannot be defined with named or numbered standard Access-list. Configuration – There are 2 routers namely router1 (IP address – 10.1.1.1/24 on fa0/0 and 11. 1.1.1/24 on fa0/1), router2 (IP address-11.1.1.2/24 on fa0/0 and 12.1.1.1/24 on fa0/1) and PC1 (IP address-10.1.1.2/24) and PC2 (IP address-12.1.1.2/24). First, we will give routes, through EIGRP, to all the routers so that PCs will be able to ping each other. Configuring Eigrp on router1: router1(config)#router Eigrp 100 router1(config-router)#network 10.1.1.0 router1(config-router)#network 11.1.1.0 router1(config-router)#No auto-summary Configuring Eigrp on router2: router2(config)#router Eigrp 100 router2(config-router)#network 11.1.1.0 router2(config-router)#network 12.1.1.0 router2(config-router)#No auto-summary Now, we will allow IP, TCP, and UDP traffic from inside the network (10.1.1.0 network) and evaluate the traffic coming from outside the network (12.1.1.0 and 11.1.1.0 network). Creating Access-list named as reflexive for the inside traffic going outside. router1(config)#ip Access-list extended reflexive router1(config-ext-na)#permit ip any any reflect ip_database router1(config-ext-nacl)#permit tcp any any reflect tcp_database router1(config-ext-nacl)#permit udp any any reflect udp_database Here, we have allowed IP, TCP, and UDP traffic and we have named it as ip_database, tcp_database, and udp_database. Note – Here, Reflexive is the name of the Access-list and not a keyword. Now, apply this Access-list to the outbound of int fa0/1 of router1 so that the traffic going out the router should be allowed. router1(config)#int fa0/1 router1(config-if)#ip access-group reflexive out Now, apply an access list for inbound traffic i.e traffic coming inside the network. We should allow only that traffic to come inside if it is initiated by the inside (10.1.1.0) network. router1(config)#ip access-list extended reflexive_in router1(config-ext-nacl)#permit Eigrp any any router1(config-ext-nacl)#evaluate tcp_database router1(config-ext-nacl)#evaluate udp_database router1(config-ext-nacl)#evaluate ip_database Here, we have allowed Eigrp traffic so that reachability should be there between the routers otherwise no traffic will be able to come back inside the ether network. We have evaluated the udp_databse, ip_database, and tcp_database so that traffic (TCP, UDP, or IP) is allowed which has been initiated inside the network. Now, apply this to interface fa0/1 in the inside direction because the traffic coming inside should be evaluated. router1(config)#int fa0/1 router1(config-if)#ip access-group reflexive_in in Here, reflexive_in is the name of the Access-list. Advantages – Advantages of reflexive Access-list are: Easy to implement. Provides greater control over the traffic coming from the outside network. Provides security from certain Dos attacks and spoofing. Disadvantage – Some applications use dynamic ports due to which failure can occur as for the reflexive Access-list the source and destination ports should be static. vaibhavsinghtanwar3 Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between IPv4 and IPv6 Implementation of Diffie-Hellman Algorithm UDP Server-Client implementation in C User Datagram Protocol (UDP) Socket Programming in Java Hamming Code in Computer Network Advanced Encryption Standard (AES) Distance Vector Routing (DVR) Protocol Types of area networks - LAN, MAN and WAN Error Detection in Computer Networks
[ { "code": null, "e": 25701, "s": 25673, "text": "\n29 Oct, 2021" }, { "code": null, "e": 25948, "s": 25701, "text": "By default, an access-list doesn’t keep track of the sessions. An access list consists of various permit and denies rules which are scanned from top to bottom. If ...
Scala Map remove() method with example - GeeksforGeeks
13 Aug, 2019 The remove() method is utilized to remove a key from the map and return its value only. Method Definition: def remove(key: A): Option[B] Return Type: It returns the value of the key present in the above method as argument. Example #1: // Scala program of remove()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating map val m1 = scala.collection.mutable.Map("geeks" -> 5, "for" -> 3, "cs" -> 2) // Applying remove method val result = m1.remove("for") // Displays output println(result) }} Some(3) We use mutable map here, as remove method is a member of mutable map.Example #2: // Scala program of remove()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating map val m1 = scala.collection.immutable.Map("geeks" -> 5, "for" -> 3, "cs" -> 2) // Applying remove method val result = m1.remove("for") // Displays output println(result) }} prog.scala:16: error: value remove is not a member of scala.collection.immutable.Map[String, Int]val result = m1.remove(“for”)^one error found So, if we use immutable map then there is a compile time error. Scala Scala-Map Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Type Casting in Scala Class and Object in Scala Scala Lists Scala Tutorial – Learn Scala with Step By Step Guide Inheritance in Scala Operators in Scala Scala Constructors Scala | Arrays Scala String substring() method with example Lambda Expression in Scala
[ { "code": null, "e": 25229, "s": 25201, "text": "\n13 Aug, 2019" }, { "code": null, "e": 25317, "s": 25229, "text": "The remove() method is utilized to remove a key from the map and return its value only." }, { "code": null, "e": 25366, "s": 25317, "text": "Me...
10 Essential Jupyter Notebook Extensions for Data Scientists | Towards Data Science
IntroductionExtensionsSummaryReferences Introduction Extensions Summary References As a Data Scientist who primarily works in Jupyter Notebook, I have experienced several pros of development in my notebook, while also encountering many various issues as well. Some of those issues can be solved by jupyter_contrib_nbextensions [2]. If not solved, then the notebook can be enhanced. This Python package has numerous nb extensions that you can configure that help to make your Data Science development process easier. It is important to note that once you install this package, you will need to restart your notebook from your terminal to see its effects. Below, I will be describing the top 10 or essential Jupyter Notebook extensions that have helped me in my Data Science process. As you can see from the above screenshot, there are a ton of extensions that you can enable to make your Jupyter coding and Data Science development easier. I have selected and enabled the 10 extensions that I will also be describing down below. There are a few clicked that come pre-clicked already like the jupyter-js-widgets/extensions, which shows the widgets and icons once you enable your extensions. Similarly, there is also Nbextensions edit menu item already preselected. Code prettify This extension helps to prettify or correctly format your Python code in your Jupyter Notebook cells. You can click on the icon to reformat your code in your current cell. Here is a before and after the execution of this extension down below. This code was already nicely formatted to start off so I wanted to show that it created formatted spacing correctly on the right. For some notebooks, it might be a small change, but for others, you may have hundreds of functions that are improperly formatted and this extension can fix your formatting almost instantly. Collapsible Headings If you structure your Jupyter Notebook with headings, you can collapse the information and cells within that same heading section with the down arrow to the left of the heading. Here is the before and after for Collapsible Headings. It is useful when you have, say 10 headings for one notebook and you want to only highlight one heading section during a code review or stakeholder meeting, or even just for yourself to help you focus more on one section. There are also more important parameters that can add to your extension, in addition to options, CSS, internals, and exporting changes (these, as well as other further implementations, are included for most extensions once you install this library). Notify This extension allows your notebook to send you a web notification when your kernel becomes idle. If you have a long task running, this extension can be useful by becoming aware of your current process. You can have options of 0, 5, 10, and 30 seconds as well. Here is the dropdown menu example in your notebook. Codefolding (and Codefolding in Editor) This is perhaps my favorite extension. Similar to the Collapsible Headings, this extension folds your code sections so that you can more easily scroll and view your notebook. If you have a long dictionary or a long function, you can collapse them so that they are mainly hidden but still show the function naming so that you can still see the main part. In the example below, you can see how the function is now collapsed, you can even collapse up to the comment level to hide both functions and keep the text of your comment only. The purple arrows icon shows that your code is there, but hidden. This extension is beneficial when sharing your code with others or when you would like to focus on certain parts of your notebook. highlighter This extension is rather simple and self-explanatory. You can highlight your markdown text by clicking on the highlighter icon. You can see that there are a few options like red with yellow used below. Here is the before and after of this easy, yet useful extension. spellchecker Also simple, yet useful, is the spellchecker. This extension is especially useful if you are sharing your notebook, pushing it to GitHub, or displaying it to stakeholders. You will want to make sure you have correctly spelled your words in your markdown cells. You will not see misspelled words show up in your displayed markdown, but only in your edit. This feature is beneficial so that if you do have some words that you disagree on with the spellchecker, like Jupyter Notebook (is not actually Jupiter Notebook), you can still display it without a distracting, red, highlighted text. Code Font Size If you want to change the code font size, this extension allows you to do that. When sharing and collaborating, especially sharing your screen, this feature can prove to be beneficial so that your code is easier to view. datestamper This extension allows you to paste your current date and time into your cell. I recommend saving it as a markdown so that the formatting does not run as code with hard-to-see formatting. If you want to keep track of when you started a process that involved different cells and functions, this extension can be useful (on top of the popular tqdm library). Scratchpad This extension is incredibly useful. You can use your scratchpad as seen below, by selection Ctrl-B on your keyboard. You can modify the current code that can work off the same kernel as well. It is also useful for viewing side-by-side code and comments if you need to compare them within your notebook. Skip-Traceback This unique extension allows you to ignore some of the duplicate or long error messages you see in your Jupyter Notebook cells. It works similarly to the Collapsible Headings and Codefolding. In the screenshot below, you can see how the main part of the error is still there on the right, but reduces the duplicate error information that can sometimes cause a headache and overwhelm you from fixing that same error. So there you go, these were 10 essential Jupyter Notebook extensions for Data Scientists or anyone else who likes to code and develop in a Jupyter Notebook as well. I hope you learned some new tricks that can make your job as a Data Scientist easier. Keep in mind that there are plenty more extensions to explore as well. These are some that I find particularly interesting and useful. Here are all of the extensions I mentioned above in one spot: Code prettifyCollapsible HeadingsNotifyCodefoldinghighlighterspellcheckerCode Font SizedatestamperScratchpadSkip-Traceback Thank you for reading! Please comment down below if you have had an experience with any of these or other Jupyter Notebook extensions. [1] Photo by Brett Ritchie on Unsplash, (2018) [2] Jupyter Contrib Team, jupyter-contrib-nbextensions, (2015–2018) [3] M.Przybyla, NBextensions tab screenshot, (2020) [4] M.Przybyla, Before and after prettify screenshot, (2020) [5] M.Przybyla, Before and after Collapsible Headings screenshot, (2020) [6] M.Przybyla, Notify dropdown menu screenshot, (2020) [7] M. Przybyla, Codefolding example screenshot, (2020) [8] M.Przybyla, Before and after of the highlighter extension screenshot, (2020) [9] M.Przybyla, Spellcheck example screenshot, (2020) [10] M.Przybyla, Scratchpad example screenshot, (2020) [11] M.Przybyla, Skip-Traceback example screenshot by Author, (2020) [12] Photo by Jess Bailey on Unsplash, (2018)
[ { "code": null, "e": 212, "s": 172, "text": "IntroductionExtensionsSummaryReferences" }, { "code": null, "e": 225, "s": 212, "text": "Introduction" }, { "code": null, "e": 236, "s": 225, "text": "Extensions" }, { "code": null, "e": 244, "s": 23...
Add legend for multiple lines in R using ggplot2 - GeeksforGeeks
24 Jun, 2021 In this article, we are going to see how to add legends for multiple line plots in R Programming Language using ggplot2. First, you need to install the ggplot2 package if it is not previously installed in R Studio. The functions used to create the line plots are : geom_line( ) : To plot the line and assign its size, shape, color, etc. Syntax: geom_line(mapping=NULL, data=NULL, stat=”identity”, position=”identity”,...) geom_point( ) : It is used to add points to the end of the lines. It is used to assign the shape, size, color of the points. Syntax: geom_point(mapping=NULL, data=NULL, stat=”identity”, position=”identity”,...) Dataset in use : Let us first plot the initial graph without any modification so that the difference is apparent. Example: R # Inserting data vacc <- data.frame(catgry=rep(c("Covishield", "Covaxin"), each=2), dose=rep(c("D1", "D2"),2), slots=c(33, 45, 66, 50)) library(ggplot2) # Plotting basic lines with multiple groups plt <- ggplot(data=vacc, aes(x=dose, y=slots, group=catgry))+ geom_line()+ geom_point(color="red", size=3)+ labs(x="Doses",y="Free Slots")+ ggtitle("Vaccine Details") plt Output: The line plots are plotted successfully. We can’t interpret the lines directly i.e. which line belongs to Covaxin and the same for Covishield just by seeing the above plot. So, we need legends that will help in segregating these lines on the basis of groups. There is no direct way in R to add legends in case of multiple lines like in Excel and other scripting languages. So, to add legends we need to distribute the lines into multiple groups on the basis of coloring. The key idea is to differentiate the lines by assigning different colors to each line and make them into separate groups. Now, the lines will be categorized into different groups and legends will be added automatically in the plot. Method 1: Default grouping In this, we directly use the color attribute within geom_line() with the attribute that will be used for differentiating. Syntax: geom_line(aes(color=group_var)) group_var is the name of the variable in the data frame which is used to segregate the lines. Example: R # Inserting data vacc <- data.frame(catgry=rep(c("Covishield", "Covaxin"), each=2), dose=rep(c("D1", "D2"),2), slots=c(33, 45, 66, 50)) library(ggplot2) # Plotting basic line with multiple groups plt <- ggplot(data=vacc, aes(x=dose, y=slots, group=catgry))+ geom_line()+ geom_point(color="red", size=3)+ labs(x="Doses",y="Free Slots")+ ggtitle("Vaccine Details") plt # Adding legends plt+geom_line(aes(color=catgry)) Output: Method 2: Manual grouping R provides us with the function scale_color_manual( ) which helps to assign color manually. We can assign either the color name or the color code for the lines manually using this function. Syntax: scale_color_manual(..,values,aesthetics=”color”) Parameter: color : Color code which is written in the form of “#RRBBGG” or simply Color name. values : Forming a vector to assign colors to multiple lines. It is similar to the previous method but here users have the flexibility to assign color to the lines based on their choices. Example: R # Inserting data vacc <- data.frame(catgry=rep(c("Covishield", "Covaxin"), each=2), dose=rep(c("D1", "D2"),2), slots=c(33, 45, 66, 50)) library(ggplot2) # Plotting basic line with multiple groups plt <- ggplot(data=vacc, aes(x=dose, y=slots, group=catgry))+ geom_line()+ geom_point(color="black", size=3)+ labs(x="Doses",y="Free Slots")+ ggtitle("Vaccine Details") plt # Adding legends manually plt+geom_line(aes(color=catgry))+ scale_color_manual(values=c("#006000", "blue")) Output: Picked R-ggplot R Language 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 Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? Logistic Regression in R Programming How to import an Excel File into R ? How to filter R DataFrame by values in a column? 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": 25314, "s": 25283, "text": " \n24 Jun, 2021\n" }, { "code": null, "e": 25530, "s": 25314, "text": " In this article, we are going to see how to add legends for multiple line plots in R Programming Language using ggplot2. First, you need to install the ggplot2...
Insert NULL value into INT column in MySQL?
You can insert NULL value into an int column with a condition i.e. the column must not have NOT NULL constraints. The syntax is as follows. INSERT INTO yourTableName(yourColumnName) values(NULL); To understand the above syntax, let us first create a table. The query to create a table is as follows. mysql> create table InsertNullDemo -> ( -> StudentId int, -> StudentName varchar(100), -> StudentAge int -> ); Query OK, 0 rows affected (0.53 sec) Here is the query to insert NULL whenever you do not pass any value for column. Here this column is StudentAge. MySQL inserts null value by default. The query to insert records is as follows. mysql> insert into InsertNullDemo(StudentId,StudentName) values(101,'Mike'); Query OK, 1 row affected (0.19 sec) mysql> insert into InsertNullDemo values(101,'Mike',NULL); Query OK, 1 row affected (0.24 sec) Display all records from the table to check the NULL value is inserted or not into INT column. The query is as follows. mysql> select *from InsertNullDemo; The following is the output displaying NULL in INT column. +-----------+-------------+------------+ | StudentId | StudentName | StudentAge | +-----------+-------------+------------+ | 101 | Mike | NULL | | 101 | Mike | NULL | +-----------+-------------+------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1202, "s": 1062, "text": "You can insert NULL value into an int column with a condition i.e. the column must not have NOT NULL constraints. The syntax is as follows." }, { "code": null, "e": 1258, "s": 1202, "text": "INSERT INTO yourTableName(yourColumnName) ...
Printing Integer between Strings in Java - GeeksforGeeks
11 Dec, 2018 Try to figure out the output of this code: public class Test{ public static void main(String[] args) { System.out.println(45+5 + "=" +45+5); }} Output: 50=455 The reason behind this is – Initially the integers are added and we get the L.H.S. as 50. But, as soon as a string is encountered it is appended and we get “50=” . Now the integers after ‘=’ are also considered as a string and so are appended. To make the output 50=50, we need to add a bracket around the sum statement to overload the concatenation operation. This will enforce the sum to happen before string concatenation as bracket as the highest precedence. public class Test{ public static void main(String[] args) { System.out.println(45+5 + "=" +(45+5)); }} Output: 50=50 This article is contributed by Himanshi Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 Java-Integer Java-String-Programs Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java
[ { "code": null, "e": 26206, "s": 26178, "text": "\n11 Dec, 2018" }, { "code": null, "e": 26249, "s": 26206, "text": "Try to figure out the output of this code:" }, { "code": "public class Test{ public static void main(String[] args) { System.out.println(45+5 ...
Microservice Architecture - Hands-On MSA
In this chapter, we will build one microservice application that will consume different available services. We all know that microservice is not a cost-effective way to build an application as each and every service we build will be full stack in nature. Building a microservice in the local environment would need high-end system configuration, as you need to have four instances of a server to keep running such that it can be consumed at a point of time. To build our first ever microservice, we will use some of the available SOA endpoints and we will consume the same in our application. Before going further to the build phase, prepare your system accordingly. You would need some public web services. You can easily google for this. If you want to consume SOAP web service, then you will get one WSDL file and from there you need to consume the specific web service. For REST service, you will need only one link to consume the same. In this example, you will jam three different web services “SOAP”, “REST”, and “custom” in one application. You will create a Java application using microservice implementation plan. You will create a custom service and the output of this service will work as an input for other services. Following are the steps to follow to develop a microservice application. Step 1: Client creation for SOAP service − There are many free web APIs available to learn a web service. For the purpose of this tutorial, use the GeoIP service of “http://www.webservicex.net/.” The WSDL file is provided in the following link on their website “webservicex.net. To generate the client out of this WSDL file, all you need to do is run the following command in your terminal. wsimport http://www.webservicex.net/geoipservice.asmx?WSDL This command will generate all the required client files under one folder named “SEI”, which is named after service end point interface. Step 2: Create your custom web service − Follow the same process mentioned at an earlier stage in this tutorial and build a Maven-based REST api named “CustomRest”. Once complete, you will find a class named “MyResource.java”. Go ahead and update this class using the following code. package com.tutorialspoint.customrest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("myresource") public class MyResource { @GET @Produces(MediaType.TEXT_PLAIN) public String getIt() { return "IND|INDIA|27.7.65.215"; } } Once everything is complete, go ahead and run this application on the server. You should get the following output in the browser. This is the web server, which returns one string object once it is called. This is the input service that provides inputs that can be consumed by other application to generate records. Step 3: Configure another Rest API − In this step, consume another web service available at services.groupkt.com. This will return a JSON object when invoked. Step 4: Create JAVA application − Create one normal Java application by selecting “New Project” -> “JAVA project” and hit Finish as shown in the following screenshot. Step 5: Add the SOAP client − In step 1, you have created the client file for the SOAP web service. Go ahead and add these client files to your current project. After successful addition of the client files, your application directory will be look the following. Step 6: Create your main app − Create your main class where you will consume all of these three web services. Right-click on the source project and create a new class named “MicroServiceInAction.java”. Next task is to call different web services from this. Step 7: Call your custom web service − For this, go ahead and add the following set of codes to implement calling your own service. try { url = new URL("http://localhost:8080/CustomRest/webapi/myresource"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader( (conn.getInputStream()))); while ((output = br.readLine()) != null) { inputToOtherService = output; } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Step 8: Consume SOAP Services − You have generated your client file but you don't know which method should be called in that entire package? For this, you need to refer to the WSDL again, which you used to generate your client files. Every WSDL file should have one “wsdl:service” tag search for this tag. It should be your entry point of that web service. Following is the service endpoint of this application. Now you need to implement this service in your application. Following is the set of Java code you need to implement your SOAP web service. GeoIPService newGeoIPService = new GeoIPService(); GeoIPServiceSoap newGeoIPServiceSoap = newGeoIPService.getGeoIPServiceSoap(); GeoIP newGeoIP = newGeoIPServiceSoap.getGeoIP(Ipaddress); // Ipaddress is output of our own web service. System.out.println("Country Name from SOAP Webserivce ---"+newGeoIP.getCountryName()); Step 9: Consume REST web service − Two of the services have been consumed till now. In this step, another REST web service with customized URL will be consumed with the help of your custom web service. Use the following set of code to do so. String url1="http://services.groupkt.com/country/get/iso3code/";//customizing the Url url1 = url1.concat(countryCode); try { URL url = new URL(url1); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader( (conn.getInputStream()))); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Step 10: Consume all services − Considering your “CustomRest” web service is running and you are connected to Internet, if everything is completed successfully then following should be your consolidated main class. package microserviceinaction; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.StringTokenizer; import net.webservicex.GeoIP; import net.webservicex.GeoIPService; import net.webservicex.GeoIPServiceSoap; public class MicroServiceInAction { static URL url; static HttpURLConnection conn; static String output; static String inputToOtherService; static String countryCode; static String ipAddress; static String CountryName; public static void main(String[] args) { //consuming of your own web service try { url = new URL("http://localhost:8080/CustomRest/webapi/myresource"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader( (conn.getInputStream()))); while ((output = br.readLine()) != null) { inputToOtherService = output; } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //Fetching IP address from the String and other information StringTokenizer st = new StringTokenizer(inputToOtherService); countryCode = st.nextToken("|"); CountryName = st.nextToken("|"); ipAddress = st.nextToken("|"); // Call to SOAP web service with output of your web service--- // getting the location of our given IP address String Ipaddress = ipAddress; GeoIPService newGeoIPService = new GeoIPService(); GeoIPServiceSoap newGeoIPServiceSoap = newGeoIPService.getGeoIPServiceSoap(); GeoIP newGeoIP = newGeoIPServiceSoap.getGeoIP(Ipaddress); System.out.println("Country Name from SOAP Webservice ---"+newGeoIP.getCountryName()); // Call to REST API --to get all the details of our country String url1 = "http://services.groupkt.com/country/get/iso3code/"; //customizing the Url url1 = url1.concat(countryCode); try { URL url = new URL(url1); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader( (conn.getInputStream()))); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } Once you run this file, you will see the following output in the console. You have successfully developed your first microservice application. 73 Lectures 5.5 hours Senol Atac 75 Lectures 5 hours Senol Atac 76 Lectures 5 hours Senol Atac 164 Lectures 14 hours BINIT DATTA 53 Lectures 6.5 hours Timotius Pamungkas 12 Lectures 35 mins Lewis Prescott Print Add Notes Bookmark this page
[ { "code": null, "e": 2344, "s": 1751, "text": "In this chapter, we will build one microservice application that will consume different available services. We all know that microservice is not a cost-effective way to build an application as each and every service we build will be full stack in nature...
Given a linked list which is sorted, how will you insert in sorted way - GeeksforGeeks
18 Feb, 2022 Given a sorted linked list and a value to insert, write a function to insert the value in a sorted way.Initial Linked List Linked List after insertion of 9 Algorithm: Let input linked list is sorted in increasing order. 1) If Linked list is empty then make the node as head and return it. 2) If the value of the node to be inserted is smaller than the value of the head node, then insert the node at the start and make it head. 3) In a loop, find the appropriate node after which the input node (let 9) is to be inserted. To find the appropriate node start from the head, keep moving until you reach a node GN (10 in the below diagram) who's value is greater than the input node. The node just before GN is the appropriate node (7). 4) Insert the node (9) after the appropriate node (7) found in step 3. Implementation: C++ C Java Python C# Javascript /* Program to insert in a sorted list */#include <bits/stdc++.h>using namespace std; /* Link list node */class Node {public: int data; Node* next;}; /* function to insert a new_nodein a list. Note that thisfunction expects a pointer tohead_ref as this can modify thehead of the input linked list(similar to push())*/void sortedInsert(Node** head_ref, Node* new_node){ Node* current; /* Special case for the head end */ if (*head_ref == NULL || (*head_ref)->data >= new_node->data) { new_node->next = *head_ref; *head_ref = new_node; } else { /* Locate the node before the point of insertion */ current = *head_ref; while (current->next != NULL&& current->next->data< new_node->data) { current = current->next; } new_node->next = current->next; current->next = new_node; }} /* BELOW FUNCTIONS ARE JUSTUTILITY TO TEST sortedInsert */ /* A utility function tocreate a new node */Node* newNode(int new_data){ /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; new_node->next = NULL; return new_node;} /* Function to print linked list */void printList(Node* head){ Node* temp = head; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; }} /* Driver program to test count function*/int main(){ /* Start with the empty list */ Node* head = NULL; Node* new_node = newNode(5); sortedInsert(&head, new_node); new_node = newNode(10); sortedInsert(&head, new_node); new_node = newNode(7); sortedInsert(&head, new_node); new_node = newNode(3); sortedInsert(&head, new_node); new_node = newNode(1); sortedInsert(&head, new_node); new_node = newNode(9); sortedInsert(&head, new_node); cout << "Created Linked List\n"; printList(head); return 0;}// This is code is contributed by rathbhupendra /* Program to insert in a sorted list */#include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; /* function to insert a new_node in a list. Note that this function expects a pointerto head_ref as this can modify the head of the input linkedlist (similar to push())*/void sortedInsert(struct Node** head_ref, struct Node* new_node){ struct Node* current; /* Special case for the head end */ if (*head_ref == NULL || (*head_ref)->data >= new_node->data) { new_node->next = *head_ref; *head_ref = new_node; } else { /* Locate the node beforethe point of insertion */ current = *head_ref; while (current->next != NULL && current->next->data < new_node->data) { current = current->next; } new_node->next = current->next; current->next = new_node; }} /* BELOW FUNCTIONS ARE JUST UTILITY TO TEST sortedInsert */ /* A utility function to create a new node */struct Node* newNode(int new_data){ /* allocate node */ struct Node* new_node= (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; new_node->next = NULL; return new_node;} /* Function to print linked list */void printList(struct Node* head){ struct Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; }} /* Driver program to test count function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; struct Node* new_node = newNode(5); sortedInsert(&head, new_node); new_node = newNode(10); sortedInsert(&head, new_node); new_node = newNode(7); sortedInsert(&head, new_node); new_node = newNode(3); sortedInsert(&head, new_node); new_node = newNode(1); sortedInsert(&head, new_node); new_node = newNode(9); sortedInsert(&head, new_node); printf("\n Created Linked List\n"); printList(head); return 0;} // Java Program to insert in a sorted listclass LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* function to insert anew_node in a list. */ void sortedInsert(Node new_node) { Node current; /* Special case for head node */ if (head == null || head.data>= new_node.data) { new_node.next = head; head = new_node; } else { /* Locate the node before point of insertion. */ current = head; while (current.next != null&& current.next.data < new_node.data) current = current.next; new_node.next = current.next; current.next = new_node; } } /*Utility functions*/ /* Function to create a node */ Node newNode(int data) { Node x = new Node(data); return x; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } } /* Driver function to test above methods */ public static void main(String args[]) { LinkedList llist = new LinkedList(); Node new_node; new_node = llist.newNode(5); llist.sortedInsert(new_node); new_node = llist.newNode(10); llist.sortedInsert(new_node); new_node = llist.newNode(7); llist.sortedInsert(new_node); new_node = llist.newNode(3); llist.sortedInsert(new_node); new_node = llist.newNode(1); llist.sortedInsert(new_node); new_node = llist.newNode(9); llist.sortedInsert(new_node); System.out.println("Created Linked List"); llist.printList(); }}/* This code is contributed by Rajat Mishra */ # Python program to insert in a sorted list # Node classclass Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None def sortedInsert(self, new_node): # Special case for the empty linked list if self.head is None: new_node.next = self.head self.head = new_node # Special case for head at end elif self.head.data >= new_node.data: new_node.next = self.head self.head = new_node else : # Locate the node before the point of insertion current = self.head while(current.next is not None and current.next.data < new_node.data): current = current.next new_node.next = current.next current.next = new_node # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print it the LinkedList def printList(self): temp = self.head while(temp): print temp.data, temp = temp.next # Driver programllist = LinkedList()new_node = Node(5)llist.sortedInsert(new_node)new_node = Node(10)llist.sortedInsert(new_node)new_node = Node(7)llist.sortedInsert(new_node)new_node = Node(3)llist.sortedInsert(new_node)new_node = Node(1)llist.sortedInsert(new_node)new_node = Node(9)llist.sortedInsert(new_node)print "Create Linked List"llist.printList() # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# Program to insert in a sorted listusing System; public class LinkedList { Node head; // head of list /* Linked list Node*/ class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* function to insert a new_node in a list. */ void sortedInsert(Node new_node) { Node current; /* Special case for head node */ if (head == null || head.data >= new_node.data) { new_node.next = head; head = new_node; } else { /* Locate the node before point of insertion. */ current = head; while (current.next != null && current.next.data < new_node.data) current = current.next; new_node.next = current.next; current.next = new_node; } } /*Utility functions*/ /* Function to create a node */ Node newNode(int data) { Node x = new Node(data); return x; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } } /* Driver code */ public static void Main(String[] args) { LinkedList llist = new LinkedList(); Node new_node; new_node = llist.newNode(5); llist.sortedInsert(new_node); new_node = llist.newNode(10); llist.sortedInsert(new_node); new_node = llist.newNode(7); llist.sortedInsert(new_node); new_node = llist.newNode(3); llist.sortedInsert(new_node); new_node = llist.newNode(1); llist.sortedInsert(new_node); new_node = llist.newNode(9); llist.sortedInsert(new_node); Console.WriteLine("Created Linked List"); llist.printList(); }} /* This code is contributed by 29AjayKumar */ <script>// javascript Program to insert in a sorted listvar head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } /* * function to insert a new_node in a list. */ function sortedInsert( new_node) { var current; /* Special case for head node */ if (head == null || head.data >= new_node.data) { new_node.next = head; head = new_node; } else { /* Locate the node before point of insertion. */ current = head; while (current.next != null && current.next.data < new_node.data) current = current.next; new_node.next = current.next; current.next = new_node; } } /* Utility functions */ /* Function to create a node */ function newNode(data) { x = new Node(data); return x; } /* Function to print linked list */ function printList() { temp = head; while (temp != null) { document.write(temp.data + " "); temp = temp.next; } } /* Driver function to test above methods */ var new_node; new_node = newNode(5); sortedInsert(new_node); new_node = newNode(10); sortedInsert(new_node); new_node = newNode(7); sortedInsert(new_node); new_node = newNode(3); sortedInsert(new_node); new_node = newNode(1); sortedInsert(new_node); new_node = newNode(9); sortedInsert(new_node); document.write("Created Linked List<br/>"); printList(); // This code is contributed by aashish1995</script> Output: Created Linked List 1 3 5 7 9 10 Complexity Analysis: Time Complexity: O(n). Only one traversal of the list is needed. Auxiliary Space: O(1). No extra space is needed. Shorter Implementation using double pointers: Thanks to Murat M Ozturk for providing this solution. Please see Murat M Ozturk’s comment below for complete function. The code uses double-pointer to keep track of the next pointer of the previous node (after which new node is being inserted).Note that below line in code changes current to have address of next pointer in a node. current = &((*current)->next); Also, note below comments. /* Copies the value-at-address current to new_node's next pointer*/ new_node->next = *current; /* Fix next pointer of the node (using its address) after which new_node is being inserted */ *current = new_node; Time Complexity: O(n) References: http://cslibrary.stanford.edu/105/LinkedListProblems.pdf 29AjayKumar rathbhupendra Akanksha_Rai nidhi_biet andrew1234 aashish1995 arorakashish0911 simmytarika5 Amazon Insertion Sort SAP Labs Wipro Linked List Amazon Wipro SAP Labs Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments LinkedList in Java Linked List vs Array Queue - Linked List Implementation Merge two sorted linked lists Detect loop in a linked list Find the middle of a given linked list Implement a stack using singly linked list Implementing a Linked List in Java using Class Merge Sort for Linked Lists Circular Linked List | Set 1 (Introduction and Applications)
[ { "code": null, "e": 24267, "s": 24239, "text": "\n18 Feb, 2022" }, { "code": null, "e": 24392, "s": 24267, "text": "Given a sorted linked list and a value to insert, write a function to insert the value in a sorted way.Initial Linked List " }, { "code": null, "e": 2...
Designing algorithm to solve Ball Sort Puzzle - GeeksforGeeks
22 Nov, 2021 In Ball Sort Puzzle game, we have p balls of each colour and n different colours, for a total of p×n balls, arranged in n stacks. In addition, we have 2 empty stacks. A maximum of p balls can be in any stack at a given time. The goal of the game is to sort the balls by colour in each of the n stacks. Rules: Only the top ball of each stack can be moved. A ball can be moved on top of another ball of the same colour A ball can be moved in an empty stack. Refer to the following GIF for an example game play (Level-7): Level 7 Gameplay Approach I [Recursion and BackTrack]: From the given rules, a simple recursive algorithm could be generated as below:Start with the given initial position of all the ballsCreate an initial empty Queue.loop:If the current position is sorted:returnelseEnqueue all possible moves in a Queue.Dequeue the next move from the Queue.Go to loop. Start with the given initial position of all the balls Create an initial empty Queue. loop:If the current position is sorted:returnelseEnqueue all possible moves in a Queue.Dequeue the next move from the Queue.Go to loop. If the current position is sorted:return return elseEnqueue all possible moves in a Queue.Dequeue the next move from the Queue.Go to loop. Enqueue all possible moves in a Queue. Dequeue the next move from the Queue. Go to loop. However, the approach looks simple and correct, it has few caveats: Incorrect:We might end up in an infinite loop if there are >1 moves in the Queue which lead to the same position of balls. We might end up in an infinite loop if there are >1 moves in the Queue which lead to the same position of balls. Inefficient:We might end up visiting the same position multiple times. We might end up visiting the same position multiple times. Thus, eliminating the above-mentioned bottlenecks would solve the issue. Approach II [Memoization using HashMap]: Assumptions:We’ll represent ball positions as a vector of strings: {“gbbb”, “ybry”, “yggy”, “rrrg”} We’ll represent ball positions as a vector of strings: {“gbbb”, “ybry”, “yggy”, “rrrg”} Create a set called Visited of <String> which will contain the visited positions as one long string. Create an empty vector for Answer which will store positions<a, b> of the tubes to move the top ball from tube a to and put it in tube b. Initialise grid with the initial settings of the balls. func solver(grid):add grid to Visitedloop over all the stacks (i):loop over all the stacks (j):If move i->j is valid, create newGrid with that move.if the balls are sorted in newGrid,update Answer;return;if newGrid is NOT in Visitedsolver(newGrid)if solved:update Answer add grid to Visited loop over all the stacks (i):loop over all the stacks (j):If move i->j is valid, create newGrid with that move.if the balls are sorted in newGrid,update Answer;return;if newGrid is NOT in Visitedsolver(newGrid)if solved:update Answer loop over all the stacks (j):If move i->j is valid, create newGrid with that move.if the balls are sorted in newGrid,update Answer;return;if newGrid is NOT in Visitedsolver(newGrid)if solved:update Answer If move i->j is valid, create newGrid with that move.if the balls are sorted in newGrid,update Answer;return;if newGrid is NOT in Visitedsolver(newGrid)if solved:update Answer if the balls are sorted in newGrid,update Answer;return; update Answer; return; if newGrid is NOT in Visitedsolver(newGrid)if solved:update Answer solver(newGrid) if solved:update Answer update Answer Sample Game Input I: Level 3 Sample Input I: 5 ybrb byrr rbyy Sample Output I: Move 1 to 4 1 times Move 1 to 5 1 times Move 1 to 4 1 times Move 2 to 5 2 times Move 1 to 2 1 times Move 3 to 1 1 times Move 1 to 2 1 times Move 3 to 1 1 times Move 2 to 1 3 times Move 2 to 3 1 times Move 3 to 4 1 times Move 3 to 2 1 times Move 2 to 4 1 times Move 3 to 5 1 times Sample Game Input II: Level 5 Sample Input II: 6 gbbb ybry yggy rrrg Sample Output II: Move 1 to 5 3 times Move 2 to 6 1 times Move 3 to 6 1 times Move 1 to 3 1 times Move 2 to 1 1 times Move 2 to 5 1 times Move 2 to 6 1 times Move 3 to 2 3 times Move 3 to 6 1 times Move 4 to 2 1 times Move 1 to 4 1 times Refer to the below C++ implementation with the comments for the reference: C++ // C++ program for the above approach#include <bits/stdc++.h>using namespace std;using Grid = vector<string>; Grid configureGrid(string stacks[], int numberOfStacks){ Grid grid; for (int i = 0; i < numberOfStacks; i++) grid.push_back(stacks[i]); return grid;} // Function to find the maxint getStackHeight(Grid grid){ int max = 0; for (auto stack : grid) if (max < stack.size()) max = stack.size(); return max;} // Convert vector of strings to// canonicalRepresentation of stringsstring canonicalStringConversion(Grid grid){ string finalString; sort(grid.begin(), grid.end()); for (auto stack : grid) { finalString += (stack + ";"); } return finalString;} // Function to check if it is solved// or notbool isSolved(Grid grid, int stackHeight){ for (auto stack : grid) { if (!stack.size()) continue; else if (stack.size() < stackHeight) return false; else if (std::count(stack.begin(), stack.end(), stack[0]) != stackHeight) return false; } return true;} // Check if the move is validbool isValidMove(string sourceStack, string destinationStack, int height){ // Can't move from an empty stack // or to a FULL STACK if (sourceStack.size() == 0 || destinationStack.size() == height) return false; int colorFreqs = std::count(sourceStack.begin(), sourceStack.end(), sourceStack[0]); // If the source stack is same colored, // don't touch it if (colorFreqs == height) return false; if (destinationStack.size() == 0) { // If source stack has only // same colored balls, // don't touch it if (colorFreqs == sourceStack.size()) return false; return true; } return ( sourceStack[sourceStack.size() - 1] == destinationStack[destinationStack.size() - 1]);} // Function to solve the puzzlebool solvePuzzle(Grid grid, int stackHeight, unordered_set<string>& visited, vector<vector<int> >& answerMod){ if (stackHeight == -1) { stackHeight = getStackHeight(grid); } visited.insert( canonicalStringConversion(grid)); for (int i = 0; i < grid.size(); i++) { // Iterate over all the stacks string sourceStack = grid[i]; for (int j = 0; j < grid.size(); j++) { if (i == j) continue; string destinationStack = grid[j]; if (isValidMove(sourceStack, destinationStack, stackHeight)) { // Creating a new Grid // with the valid move Grid newGrid(grid); // Adding the ball newGrid[j].push_back(newGrid[i].back()); // Adding the ball newGrid[i].pop_back(); if (isSolved(newGrid, stackHeight)) { answerMod.push_back( vector<int>{ i, j, 1 }); return true; } if (visited.find( canonicalStringConversion(newGrid)) == visited.end()) { bool solveForTheRest = solvePuzzle(newGrid, stackHeight, visited, answerMod); if (solveForTheRest) { vector<int> lastMove = answerMod[answerMod.size() - 1]; // Optimisation - Concatenating // consecutive moves of the same // ball if (lastMove[0] == i && lastMove[1] == j) answerMod[answerMod.size() - 1] [2]++; else answerMod.push_back( vector<int>{ i, j, 1 }); return true; } } } } } return false;} // Checks whether the grid is valid or notbool checkGrid(Grid grid){ int numberOfStacks = grid.size(); int stackHeight = getStackHeight(grid); int numBallsExpected = ((numberOfStacks - 2) * stackHeight); // Cause 2 empty stacks int numBalls = 0; for (auto i : grid) numBalls += i.size(); if (numBalls != numBallsExpected) { cout << "Grid has incorrect # of balls" << endl; return false; } map<char, int> ballColorFrequency; for (auto stack : grid) for (auto ball : stack) if (ballColorFrequency.find(ball) != ballColorFrequency.end()) ballColorFrequency[ball] += 1; else ballColorFrequency[ball] = 1; for (auto ballColor : ballColorFrequency) { if (ballColor.second != getStackHeight(grid)) { cout << "Color " << ballColor.first << " is not " << getStackHeight(grid) << endl; return false; } } return true;} // Driver Codeint main(void){ // Including 2 empty stacks int numberOfStacks = 6; std::string stacks[] = { "gbbb", "ybry", "yggy", "rrrg", "", "" }; Grid grid = configureGrid( stacks, numberOfStacks); if (!checkGrid(grid)) { cout << "Invalid Grid" << endl; return 1; } if (isSolved(grid, getStackHeight(grid))) { cout << "Problem is already solved" << endl; return 0; } unordered_set<string> visited; vector<vector<int> > answerMod; // Solve the puzzle instance solvePuzzle(grid, getStackHeight(grid), visited, answerMod); // Since the values of Answers are appended // When the problem was completely // solved and backwards from there reverse(answerMod.begin(), answerMod.end()); for (auto v : answerMod) { cout << "Move " << v[0] + 1 << " to " << v[1] + 1 << " " << v[2] << " times" << endl; } return 0;} Move 1 to 5 3 times Move 2 to 6 1 times Move 3 to 6 1 times Move 1 to 3 1 times Move 2 to 1 1 times Move 2 to 5 1 times Move 2 to 6 1 times Move 3 to 2 3 times Move 3 to 6 1 times Move 4 to 2 1 times Move 1 to 4 1 times akshaysingh98088 Blogathon-2021 Puzzles Backtracking Blogathon Dynamic Programming Hash Puzzles Hash Dynamic Programming Backtracking Puzzles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Tug of War Difference between Backtracking and Branch-N-Bound technique Perfect Sum Problem N-Queen Problem | Local Search using Hill climbing with random neighbour Find shortest safe route in a path with landmines How to Call or Consume External API in Spring Boot? Re-rendering Components in ReactJS SQL Query to Insert Multiple Rows Python NOT EQUAL operator Difference Between Local Storage, Session Storage And Cookies
[ { "code": null, "e": 24593, "s": 24565, "text": "\n22 Nov, 2021" }, { "code": null, "e": 24895, "s": 24593, "text": "In Ball Sort Puzzle game, we have p balls of each colour and n different colours, for a total of p×n balls, arranged in n stacks. In addition, we have 2 empty stac...
How to sort an ArrayList in Java in ascending order?
You can sort an ArrayList using the sort() method of the Collections class this method accepts a list object as a parameter and sorts the contents of it in ascending order. Example: import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; public class ArrayListSample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("JavaFx"); list.add("Java"); list.add("WebGL"); list.add("OpenCV"); Set<String> set = new LinkedHashSet<String>(list); Collections.sort(list); System.out.println(list); } } Output: [Java, JavaFx, OpenCV, WebGL]
[ { "code": null, "e": 1235, "s": 1062, "text": "You can sort an ArrayList using the sort() method of the Collections class this method accepts a list object as a parameter and sorts the contents of it in ascending order." }, { "code": null, "e": 1244, "s": 1235, "text": "Example:"...
Multi-threaded chat Application in Java | Set 1 (Server Side Programming) - GeeksforGeeks
03 Sep, 2021 Prerequisites : Introducing threads in socket programmingIn the above article, a simple date time server was created which handled multiple user requests at the same time using threading. It explains the basic concepts of threading in network programming. The same concepts can be used with very slight modification to extend the above idea and create a chatting application similar to facebook messenger, whatsapp, etc. The following article covers the implementation of such an application with a detailed explanation, limitations, and their solutions. In this set, we will discuss Server side programming(Server.java), Client side programming(Client.java) is discussed in Set 2. Server Side Programming(Server.java) 1. Server class : The main server implementation is easy and similar to the previous article. The following points will help understand Server implementation : The server runs an infinite loop to keep accepting incoming requests.When a request comes, it assigns a new thread to handle the communication part.The server also stores the client name into a vector, to keep a track of connected devices. The vector stores the thread object corresponding to the current request. The helper class uses this vector to find the name of recipient to which message is to be delivered. As this vector holds all the streams, handler class can use it to successfully deliver messages to specific clients.Invoke the start() method. The server runs an infinite loop to keep accepting incoming requests. When a request comes, it assigns a new thread to handle the communication part. The server also stores the client name into a vector, to keep a track of connected devices. The vector stores the thread object corresponding to the current request. The helper class uses this vector to find the name of recipient to which message is to be delivered. As this vector holds all the streams, handler class can use it to successfully deliver messages to specific clients. Invoke the start() method. 2. ClientHandler class : Similar to previous article, we create a helper class for handling various requests. This time, along with the socket and streams, we introduce a name variable. This will hold the name of the client that is connected to the server. The following points will help understand ClientHandler implementation : Whenever the handler receives any string, it breaks it into the message and recipient part. It uses Stringtokenizer for this purpose with ‘#’ as the delimiter. Here it is assumed that the string is always of the format: message # recipient It then searches for the name of recipient in the connected clients list, stored as a vector in the server. If it finds the recipients name in the clients list, it forwards the message on its output stream with the name of the sender prefixed to the message. Java // Java implementation of Server side// It contains two classes : Server and ClientHandler// Save file as Server.java import java.io.*;import java.util.*;import java.net.*; // Server classpublic class Server{ // Vector to store active clients static Vector<ClientHandler> ar = new Vector<>(); // counter for clients static int i = 0; public static void main(String[] args) throws IOException { // server is listening on port 1234 ServerSocket ss = new ServerSocket(1234); Socket s; // running infinite loop for getting // client request while (true) { // Accept the incoming request s = ss.accept(); System.out.println("New client request received : " + s); // obtain input and output streams DataInputStream dis = new DataInputStream(s.getInputStream()); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); System.out.println("Creating a new handler for this client..."); // Create a new handler object for handling this request. ClientHandler mtch = new ClientHandler(s,"client " + i, dis, dos); // Create a new Thread with this object. Thread t = new Thread(mtch); System.out.println("Adding this client to active client list"); // add this client to active clients list ar.add(mtch); // start the thread. t.start(); // increment i for new client. // i is used for naming only, and can be replaced // by any naming scheme i++; } }} // ClientHandler classclass ClientHandler implements Runnable{ Scanner scn = new Scanner(System.in); private String name; final DataInputStream dis; final DataOutputStream dos; Socket s; boolean isloggedin; // constructor public ClientHandler(Socket s, String name, DataInputStream dis, DataOutputStream dos) { this.dis = dis; this.dos = dos; this.name = name; this.s = s; this.isloggedin=true; } @Override public void run() { String received; while (true) { try { // receive the string received = dis.readUTF(); System.out.println(received); if(received.equals("logout")){ this.isloggedin=false; this.s.close(); break; } // break the string into message and recipient part StringTokenizer st = new StringTokenizer(received, "#"); String MsgToSend = st.nextToken(); String recipient = st.nextToken(); // search for the recipient in the connected devices list. // ar is the vector storing client of active users for (ClientHandler mc : Server.ar) { // if the recipient is found, write on its // output stream if (mc.name.equals(recipient) && mc.isloggedin==true) { mc.dos.writeUTF(this.name+" : "+MsgToSend); break; } } } catch (IOException e) { e.printStackTrace(); } } try { // closing resources this.dis.close(); this.dos.close(); }catch(IOException e){ e.printStackTrace(); } }} Output: New client request received : Socket[addr=/127.0.0.1,port=61818,localport=1234] Creating a new handler for this client... Adding this client to active client list New client request received : Socket[addr=/127.0.0.1,port=61819,localport=1234] Creating a new handler for this client... Adding this client to active client list Limitations:Although the above implementation of server manages to handle most of the scenarios, there are some shortcomings in the approach defined above. One clear observation from above programs is that if the number of clients grew large, the searching time would increase in the handler class. To avoid this increase, two hash maps can be used. One with name as the key, and index in active list as the value. Another with index as key, and associated handler object as value. This way, we can quickly look up the two hashmaps for matching recipient. It is left to the readers to implement this hack to increase efficiency of the implementation. Another thing to notice is that this implementation doesn’t work well when users disconnect from the server. A lot of errors would be thrown because disconnection is not handled in this implementation. It can easily be implemented as in previous basic TCP examples. It is also left for the reader to implement this feature in the program. There is a huge difference in the client program(Client.java) than the previous articles, so it will be discussed in Set 2 of this series. Related Article : Multi-threaded chat Application | Set 2 This article is contributed by Rishabh Mahrsee. 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. gulshankumarar231 Java-Multithreading Java-Networking Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Stream In Java ArrayList in Java Stack Class in Java Singleton Class in Java Set in Java Multithreading in Java Collections in Java Queue Interface In Java LinkedList in Java
[ { "code": null, "e": 25761, "s": 25733, "text": "\n03 Sep, 2021" }, { "code": null, "e": 26443, "s": 25761, "text": "Prerequisites : Introducing threads in socket programmingIn the above article, a simple date time server was created which handled multiple user requests at the sa...
Orphan User in SQL Server - GeeksforGeeks
03 Sep, 2020 Orphan users are the users which are available in the database level but their mapped logins not available in the server level. Orphan users are created when a database is restored from backup from one server on another server. To get the Orphan users in any database in SQL Server use below : Syntax : USE DATABASENAME EXEC sp_change_users_login report GO Example –Let us assume we have restored GeeksDb from Server1 to Server2, using below command in Server2. USE GeeksDb EXEC sp_change_users_login report GO Output – Below methods could be used to fix Orphan users. USING WITH ORPHANED USER SID :To fix any orphaned users, use create login by using SID.Syntax :USE MASTER CREATE LOGIN [LoginName] WITH PASSWORD = 'Password', SID = 0x7A4X871C3EXX7C42X67B5F3CD2C35FXX Example –USE MASTER CREATE LOGIN [Geek1] WITH PASSWORD = 'Pa$$W0rd1', SID = 0x7A4X871C3EXX7C42X67B5F3CD2C35FXX USING UPDATE_ONE :UPDATE_ONE could be used to map even when Login name and User name are different or could be used to change user’s SID with Logins SID.First, create new login.USE MASTER CREATE LOGIN [LoginName] WITH PASSWORD = 'Password'Once login is created use UPDATE_ONE to fix orphan user.Syntax :USE DATABASENAME sp_change_users_login UPDATE_ONE, 'UserName', 'LoginName' GOExample –USE MASTER CREATE LOGIN [Geek2] WITH PASSWORD = 'Pa$$W0rd2' USE GeekDb sp_change_users_login UPDATE_ONE, 'Geek2', 'Geek2' GO USING AUTO_FIX –TYPE 1 : When Login Name and User Name are same.First create the login and then assign login SID to Orphan User.Syntax :USE master CREATE LOGIN [LoginName] WITH PASSWORD = 'Password' USE DATABASENAME sp_change_users_login AUTO_FIX, 'LoginName/UserName' GoExample :USE master CREATE LOGIN [Geek3] WITH PASSWORD = 'Pa$$W0rd3' USE GeekDB sp_change_users_login AUTO_FIX, 'Geek3/Geek3' Go TYPE 2 : Without creating the login.Syntax :USE DATABASENAME sp_change_users_login AUTO_FIX, 'UserName', NULL, 'Password' GOExample :USE GeekDb sp_change_users_login AUTO_FIX, 'Geek4', NULL, 'Pa$$W0rd4' GO To get the Orphan users in any database after using above methods :USE GeeksDb EXEC sp_change_users_login report GO Output –1. UserName2. UserSIDOnce the orphan users are fixed successfully, there will not be any orphan user (UserName and UserSID) as the result of above command. USING WITH ORPHANED USER SID :To fix any orphaned users, use create login by using SID.Syntax :USE MASTER CREATE LOGIN [LoginName] WITH PASSWORD = 'Password', SID = 0x7A4X871C3EXX7C42X67B5F3CD2C35FXX Example –USE MASTER CREATE LOGIN [Geek1] WITH PASSWORD = 'Pa$$W0rd1', SID = 0x7A4X871C3EXX7C42X67B5F3CD2C35FXX Syntax : USE MASTER CREATE LOGIN [LoginName] WITH PASSWORD = 'Password', SID = 0x7A4X871C3EXX7C42X67B5F3CD2C35FXX Example – USE MASTER CREATE LOGIN [Geek1] WITH PASSWORD = 'Pa$$W0rd1', SID = 0x7A4X871C3EXX7C42X67B5F3CD2C35FXX USING UPDATE_ONE :UPDATE_ONE could be used to map even when Login name and User name are different or could be used to change user’s SID with Logins SID.First, create new login.USE MASTER CREATE LOGIN [LoginName] WITH PASSWORD = 'Password'Once login is created use UPDATE_ONE to fix orphan user.Syntax :USE DATABASENAME sp_change_users_login UPDATE_ONE, 'UserName', 'LoginName' GOExample –USE MASTER CREATE LOGIN [Geek2] WITH PASSWORD = 'Pa$$W0rd2' USE GeekDb sp_change_users_login UPDATE_ONE, 'Geek2', 'Geek2' GO First, create new login. USE MASTER CREATE LOGIN [LoginName] WITH PASSWORD = 'Password' Once login is created use UPDATE_ONE to fix orphan user. Syntax : USE DATABASENAME sp_change_users_login UPDATE_ONE, 'UserName', 'LoginName' GO Example – USE MASTER CREATE LOGIN [Geek2] WITH PASSWORD = 'Pa$$W0rd2' USE GeekDb sp_change_users_login UPDATE_ONE, 'Geek2', 'Geek2' GO USING AUTO_FIX –TYPE 1 : When Login Name and User Name are same.First create the login and then assign login SID to Orphan User.Syntax :USE master CREATE LOGIN [LoginName] WITH PASSWORD = 'Password' USE DATABASENAME sp_change_users_login AUTO_FIX, 'LoginName/UserName' GoExample :USE master CREATE LOGIN [Geek3] WITH PASSWORD = 'Pa$$W0rd3' USE GeekDB sp_change_users_login AUTO_FIX, 'Geek3/Geek3' Go TYPE 2 : Without creating the login.Syntax :USE DATABASENAME sp_change_users_login AUTO_FIX, 'UserName', NULL, 'Password' GOExample :USE GeekDb sp_change_users_login AUTO_FIX, 'Geek4', NULL, 'Pa$$W0rd4' GO To get the Orphan users in any database after using above methods :USE GeeksDb EXEC sp_change_users_login report GO Output –1. UserName2. UserSIDOnce the orphan users are fixed successfully, there will not be any orphan user (UserName and UserSID) as the result of above command. First create the login and then assign login SID to Orphan User. Syntax : USE master CREATE LOGIN [LoginName] WITH PASSWORD = 'Password' USE DATABASENAME sp_change_users_login AUTO_FIX, 'LoginName/UserName' Go Example : USE master CREATE LOGIN [Geek3] WITH PASSWORD = 'Pa$$W0rd3' USE GeekDB sp_change_users_login AUTO_FIX, 'Geek3/Geek3' Go TYPE 2 : Without creating the login. Syntax : USE DATABASENAME sp_change_users_login AUTO_FIX, 'UserName', NULL, 'Password' GO Example : USE GeekDb sp_change_users_login AUTO_FIX, 'Geek4', NULL, 'Pa$$W0rd4' GO To get the Orphan users in any database after using above methods : USE GeeksDb EXEC sp_change_users_login report GO Output – Once the orphan users are fixed successfully, there will not be any orphan user (UserName and UserSID) as the result of above command. DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL Query to Convert VARCHAR to INT How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25513, "s": 25485, "text": "\n03 Sep, 2020" }, { "code": null, "e": 25741, "s": 25513, "text": "Orphan users are the users which are available in the database level but their mapped logins not available in the server level. Orphan users are created when a dat...
How to Execute Shell Commands in a Remote Machine in Python? - GeeksforGeeks
16 Jul, 2021 Running shell commands on a Remote machine is nothing but executing shell commands on another machine and as another user across a computer network. There will be a master machine from which command can be sent and one or more slave machines that execute the received commands. We will be using Websocket protocol to send shell commands to the slave machine and receive the output of commands. Websocket offers full-duplex communication over a single TCP connection in real-time. The Python provides a subprocess library an in-built library, that allows a new process to start and connect to their input, output, and error pipes. getoutput method in the subprocess library executes the command and returns the output, if an error occurs it also returns the errors. You will easily understand its working with approach and implementation. So let’s begin. Approach: Create Mater machine script. Create a socket connection and listen for the slave machine socket. Accept the connection once the connection request is made. Use the input method to get a command from the user and encode it. Then use the socket connection to send the shell command. Then receive the output of the command. Create a Slave machine script. Create a Socket and connect it to the Master machine socket. Receive the command from the master. Execute the command with the get output method from the subprocess module. getoutput method returns the output of the executed command. Encode the output and send it to the master machine. Master machine script: Python3 import socket # Create socket with socket class.master = socket.socket() # Host is the IP address of master# machine.host = "0.0.0.0" # This will be the port that the# socket is bind.port = 8080 # binding the host and port to the# socket we created.master.bind((host, port)) # listen method listens on the socket# to accept socket connection.master.listen(1) # This method accept socket connection# from the slave machineslave, address = master.accept() # When the slave is accepted, we can send# and receive data in real timewhile True: # input the command from the user print(">", end=" ") command = input() # encode the command and send it to the # slave machine then slave machine can # executes the command slave.send(command.encode()) # If the command is exit, close the connection if command == "exit": break # Receive the output of command, sent by the # slave machine.recv method accepts integer as # argument and it denotes no.of bytes to be # received from the sender. output = slave.recv(5000) print(output.decode()) # close method closes the socket connection between# master and slave.master.close() Output: Slave machine script: Python3 import socketimport subprocess # Create socket with socket class.master = socket.socket() # Host is the IP address of master machine.host = "192.168.43.160" # This will be the port that master# machine listens.port = 8080 # connect to the master machine with connect# command.slave.connect((host, port)) while True: # receive the command from the master machine. # recv 1024 bytes from the master machine. command = slave.recv(1024).decode() print(command) # If the command is exit, close the connection. if command == "exit": break output = "output:\n" # getoutput method executes the command and # returns the output. output += subprocess.getoutput(command) # Encode and send the output of the command to # the master machine. slave.send(output.encode()) # close method closes the connection.slave.close() Output: rajeev0719singh Picked python-utility 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": 26195, "s": 26167, "text": "\n16 Jul, 2021" }, { "code": null, "e": 26474, "s": 26195, "text": "Running shell commands on a Remote machine is nothing but executing shell commands on another machine and as another user across a computer network. There will be ...
How to use Box Component in ReactJS? - GeeksforGeeks
18 Jan, 2021 The Box component serves as a wrapper component for most of the CSS utility needs. Material UI for React has this component available for us and it is very easy to integrate. We can use the Box component in ReactJS using the following approach. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command: npm install @material-ui/core Project Structure: It will look like the following. Project Structure App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React from 'react'import Box from '@material-ui/core/Box'; const App = () => { return ( <div style={{ marginLeft: '40%', marginTop: '60px', width: '30%' }}> <Box color="white" bgcolor="palevioletred" p={1}> Greetings from GeeksforGeeks! </Box> </div> );} export default App Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Box Component Output JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? Create a Responsive Navbar using ReactJS
[ { "code": null, "e": 25927, "s": 25899, "text": "\n18 Jan, 2021" }, { "code": null, "e": 26172, "s": 25927, "text": "The Box component serves as a wrapper component for most of the CSS utility needs. Material UI for React has this component available for us and it is very easy to...
Shared Preferences in Android with Example - GeeksforGeeks
29 Oct, 2021 One of the most Interesting Data Storage options Android provides its users is Shared Preferences. Shared Preferences is the way in which one can store and retrieve small amounts of primitive data as key/value pairs to a file on the device storage such as String, int, float, Boolean that make up your preferences in an XML file inside the app on the device storage. Shared Preferences can be thought of as a dictionary or a key/value pair. For example, you might have a key being “username” and for the value, you might store the user’s username. And then you could retrieve that by its key (here username). You can have a simple shared preference API that you can use to store preferences and pull them back as and when needed. Shared Preferences class provides APIs for reading, writing, and managing this data. A sample GIF 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. Shared Preferences are suitable in different situations. For example, when the user’s settings need to be saved or to store data that can be used in different activities within the app. As you know, onPause() will always be called before your activity is placed in the background or destroyed, So for the data to be saved persistently, it’s preferred to save it in onPause(), which could be restored in onCreate() of the activity. The data stored using shared preferences are kept private within the scope of the application. However, shared preferences are different from that activity’s instance state. Shared Preferences Saved Instance State The first thing we need to do is to create one shared preferences file per app. So name it with the package name of your app- unique and easy to associate with the app. When you want to get the values, call the getSharedPreferences() method. Shared Preferences provide modes of storing the data (private mode and public mode). It is for backward compatibility- use only MODE_PRIVATE to be secure. public abstract SharedPreferences getSharedPreferences (String name, int mode) This method takes two arguments, the first being the name of the SharedPreference(SP) file and the other is the context mode that we want to store our file in. MODE_PUBLIC will make the file public which could be accessible by other applications on the device MODE_PRIVATE keeps the files private and secures the user’s data. MODE_APPEND is used while reading the data from the SP file. SharedPreferences.Editor: Interface used to write(edit) data in the SP file. Once editing has been done, one must commit() or apply() the changes made to the file.SharedPreferences.OnSharedPreferenceChangeListener(): Called when a shared preference is changed, added, or removed. This may be called even if a preference is set to its existing value. This callback will be run on your main thread. SharedPreferences.Editor: Interface used to write(edit) data in the SP file. Once editing has been done, one must commit() or apply() the changes made to the file. SharedPreferences.OnSharedPreferenceChangeListener(): Called when a shared preference is changed, added, or removed. This may be called even if a preference is set to its existing value. This callback will be run on your main thread. contains(String key): This method is used to check whether the preferences contain a preference. edit(): This method is used to create a new Editor for these preferences, through which you can make modifications to the data in the preferences and atomically commit those changes back to the SharedPreferences object. getAll(): This method is used to retrieve all values from the preferences. getBoolean(String key, boolean defValue): This method is used to retrieve a boolean value from the preferences. getFloat(String key, float defValue): This method is used to retrieve a float value from the preferences. getInt(String key, int defValue): This method is used to retrieve an int value from the preferences. getLong(String key, long defValue): This method is used to retrieve a long value from the preferences. getString(String key, String defValue): This method is used to retrieve a String value from the preferences. getStringSet(String key, Set defValues): This method is used to retrieve a set of String values from the preferences. registerOnSharedPreferencechangeListener(SharedPreferences.OnSharedPreferencechangeListener listener): This method is used to registers a callback to be invoked when a change happens to a preference. unregisterOnSharedPreferencechangeListener(SharedPreferences.OnSharedPreferencechangeListener listener): This method is used to unregisters a previous callback. contains(String key): This method is used to check whether the preferences contain a preference. edit(): This method is used to create a new Editor for these preferences, through which you can make modifications to the data in the preferences and atomically commit those changes back to the SharedPreferences object. getAll(): This method is used to retrieve all values from the preferences. getBoolean(String key, boolean defValue): This method is used to retrieve a boolean value from the preferences. getFloat(String key, float defValue): This method is used to retrieve a float value from the preferences. getInt(String key, int defValue): This method is used to retrieve an int value from the preferences. getLong(String key, long defValue): This method is used to retrieve a long value from the preferences. getString(String key, String defValue): This method is used to retrieve a String value from the preferences. getStringSet(String key, Set defValues): This method is used to retrieve a set of String values from the preferences. registerOnSharedPreferencechangeListener(SharedPreferences.OnSharedPreferencechangeListener listener): This method is used to registers a callback to be invoked when a change happens to a preference. unregisterOnSharedPreferencechangeListener(SharedPreferences.OnSharedPreferencechangeListener listener): This method is used to unregisters a previous callback. Following is sample byte code on how to write Data in Shared Preferences: Java // Storing data into SharedPreferencesSharedPreferences sharedPreferences = getSharedPreferences("MySharedPref",MODE_PRIVATE); // Creating an Editor object to edit(write to the file)SharedPreferences.Editor myEdit = sharedPreferences.edit(); // Storing the key and its value as the data fetched from edittextmyEdit.putString("name", name.getText().toString());myEdit.putInt("age", Integer.parseInt(age.getText().toString())); // Once the changes have been made,// we need to commit to apply those changes made,// otherwise, it will throw an errormyEdit.commit(); Following is the sample byte code on how to read Data in Shared Preferences: Java // Retrieving the value using its keys the file name// must be same in both saving and retrieving the dataSharedPreferences sh = getSharedPreferences("MySharedPref", MODE_APPEND); // The value will be default as empty string because for// the very first time when the app is opened, there is nothing to showString s1 = sh.getString("name", "");int a = sh.getInt("age", 0); // We can then use the dataname.setText(s1);age.setText(String.valueOf(a)); Below is the small demo for Shared Preferences. In this particular demo, there are two EditTexts, which save and retain the data entered earlier in them. This type of feature can be seen in applications with forms. Using Shared Preferences, the user will not have to fill in details again and again. Invoke the following code inside the activity_main.xml file to implement the UI: 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" tools:ignore="HardcodedText"> <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="32dp" android:text="Shared Preferences Demo" android:textColor="@android:color/black" android:textSize="24sp" /> <!--EditText to take the data from the user and save the data in SharedPreferences--> <EditText android:id="@+id/edit1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/textview" android:layout_marginStart="16dp" android:layout_marginTop="8dp" android:layout_marginEnd="16dp" android:hint="Enter your Name" android:padding="10dp" /> <!--EditText to take the data from the user and save the data in SharedPreferences--> <EditText android:id="@+id/edit2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/edit1" android:layout_marginStart="16dp" android:layout_marginTop="8dp" android:layout_marginEnd="16dp" android:hint="Enter your Age" android:padding="10dp" android:inputType="number" /> </RelativeLayout> Output UI: Working with the MainActivity.java file to handle the two of the EditText to save the data entered by the user inside the SharedPreferences. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import androidx.appcompat.app.AppCompatActivity; import android.content.SharedPreferences;import android.os.Bundle;import android.widget.EditText; public class MainActivity extends AppCompatActivity { private EditText name, age; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); name = findViewById(R.id.edit1); age = findViewById(R.id.edit2); } // Fetch the stored data in onResume() // Because this is what will be called // when the app opens again @Override protected void onResume() { super.onResume(); // Fetching the stored data // from the SharedPreference SharedPreferences sh = getSharedPreferences("MySharedPref", MODE_PRIVATE); String s1 = sh.getString("name", ""); int a = sh.getInt("age", 0); // Setting the fetched data // in the EditTexts name.setText(s1); age.setText(String.valueOf(a)); } // Store the data in the SharedPreference // in the onPause() method // When the user closes the application // onPause() will be called // and data will be stored @Override protected void onPause() { super.onPause(); // Creating a shared pref object // with a file name "MySharedPref" // in private mode SharedPreferences sharedPreferences = getSharedPreferences("MySharedPref", MODE_PRIVATE); SharedPreferences.Editor myEdit = sharedPreferences.edit(); // write all the data entered by the user in SharedPreference and apply myEdit.putString("name", name.getText().toString()); myEdit.putInt("age", Integer.parseInt(age.getText().toString())); myEdit.apply(); }} Reference: Shared Preferences | Android adityamshidlyali jemikp2000 android Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java
[ { "code": null, "e": 25925, "s": 25897, "text": "\n29 Oct, 2021" }, { "code": null, "e": 26905, "s": 25925, "text": "One of the most Interesting Data Storage options Android provides its users is Shared Preferences. Shared Preferences is the way in which one can store and retriev...
Difference between next() and nextLine() methods in Java - GeeksforGeeks
27 Dec, 2021 The Scanner class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings. It is the easiest way to read input in a Java program, though not very efficient if you want an input method for scenarios where time is a constraint like in competitive programming. The scanner class consists next() and nextLine() methods. In this article, the difference between these two methods is discussed. next() Method: The next() method in java is present in the Scanner class and is used to get the input from the user. In order to use this method, a Scanner object needs to be created. This method can read the input only until a space(” “) is encountered. In other words, it finds and returns the next complete token from the scanner. The following is an example of how the next() method is implemented in Java: Java // Java program to demonstrate// the next() method import java.util.Scanner; class GFG { public static void main(String[] args) { // Creating the Scanner object Scanner sc = new Scanner(System.in); // Use of the next() method String Input = sc.next(); System.out.println(Input); }} Input: Geeks for geeks Output: Geeks nextLine() Method: The nextLine() method in java is present in the Scanner class and is used to get the input from the user. In order to use this method, a Scanner object needs to be created. This method can read the input till the end of line. In other words, it can take input until the line change or new line and ends input of getting ‘\n’ or press enter. The following is an example of how the nextLine() method is implemented in Java: Java // Java program to demonstrate// the nextLine() method import java.util.Scanner; class GFG { public static void main(String[] args) { // Creating the object of the // Scanner class Scanner sc = new Scanner(System.in); // Use of nextLine() method String Input = sc.nextLine(); System.out.println(Input); }} Input: Geeks for geeks Output: Geeks for The following table describes the difference between the next() and the nextLine() method: gulshankumarar231 Input and Output Java-Scanner Difference Between Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Difference between Compile-time and Run-time Polymorphism in Java Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 26129, "s": 26101, "text": "\n27 Dec, 2021" }, { "code": null, "e": 26570, "s": 26129, "text": "The Scanner class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings. It is the easiest way to read input ...
C# | Convert.ToBoolean(String, IFormatProvider) Method - GeeksforGeeks
02 Sep, 2021 This method is used to convert the specified string representation of a logical value to its Boolean equivalent, using the specified culture-specific formatting information.Syntax: public static bool ToBoolean (string value, IFormatProvider provider); Parameters: value: It is a string that contains the value of either TrueString or FalseString. provider: It is an object that supplies culture-specific formatting information. This parameter is ignored. Return Value: This method returns true if value equals TrueString, or false if value equals FalseString or null.Exceptions: This method will throw FormatException if the value is not equal to TrueString or FalseString.Below programs illustrate the use of Convert.ToBoolean(String, IFormatProvider) Method:Example 1: csharp // C# program to demonstrate the// Convert.ToBoolean() Methodusing System;using System.Globalization; class GFG { // Main Methodpublic static void Main(){ try { // creating object of CultureInfo CultureInfo cultures = new CultureInfo("en-US"); // declaring and initializing String array String[] values = { null, "true", "False", " false " }; // calling get() Method Console.WriteLine("Converted bool value "+ "of specified strings: "); for (int j = 0; j < values.Length; j++) { get(values[j], cultures); } } catch (FormatException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(string s, CultureInfo cultures){ // converting string to specified bool bool val = Convert.ToBoolean(s, cultures); // display the converted string Console.Write(" {0}, ", val);}} Converted bool value of specified strings: False, True, False, False, Example 2:For FormatException csharp // C# program to demonstrate the// Convert.ToBoolean() Methodusing System;using System.Globalization;class GFG { // Main Methodpublic static void Main(){ try { // creating object of CultureInfo CultureInfo cultures = new CultureInfo("en-US"); // declaring and initializing String array String[] values = { null, "true", "False", " false ", "" }; // calling get() Method Console.WriteLine("Converted bool value"+ " of specified strings: "); for (int j = 0; j < values.Length; j++) { get(values[j], cultures); } } catch (FormatException e) { Console.WriteLine("\n"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(string s, CultureInfo cultures){ // converting string to specified bool bool val = Convert.ToBoolean(s, cultures); // display the converted string Console.Write(" {0}, ", val);}} Converted bool value of specified strings: False, True, False, False, Exception Thrown: System.FormatException Reference: https://docs.microsoft.com/en-us/dotnet/api/system.convert.toboolean?view=netframework-4.7.2#System_Convert_ToBoolean_System_String_System_IFormatProvider_ sweetyty CSharp Convert Class CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method
[ { "code": null, "e": 25755, "s": 25727, "text": "\n02 Sep, 2021" }, { "code": null, "e": 25936, "s": 25755, "text": "This method is used to convert the specified string representation of a logical value to its Boolean equivalent, using the specified culture-specific formatting in...
Output of C programs | Set 41 - GeeksforGeeks
23 Aug, 2017 QUE.1 What will be output if you will compile and execute the following c code? #include <stdio.h>int main(){ int a = 5; float b; printf("%d ", sizeof(++a + b)); printf("%d ", a); return 0;} (a)2 6(b)4 6(c)2 5(d)4 5 Answer : d Explanation: ++a +b = 6 + Garbage floating point number = Garbage floating point number // From the rule of automatic type conversion Hence sizeof operator will return 4 because size of float data type in c is 4 byte. Value of any variable doesn’t modify inside sizeof operator. Hence value of variable a will remain 5. QUE.2 What will be output if you will compile and execute the following c code? #include <stdio.h> int main(){ int array[3] = { 5 }; int i; for (i = 0; i <= 2; i++) printf("%d ", array[i]); return 0;} (a)5 garbage garbage(b)5 0 0(c)5 null null(d)Compiler error(e)None of above Answer : b Explanation: Storage class of an array which initializes the element of the array at the time of declaration is static. Default initial value of static integer is zero.QUE.3 What will be output if you will compile and execute the following c code? #include <stdio.h>int main(){ register int i, x; scanf("%d", &i); x = ++i + ++i + ++i; printf("%d", x); return 0;} (a)17(b)18(c)21(d)22(e)Compiler error Answer : e Explanation: In C, register variable stores in CPU it doesn’t store in RAM. So register variable do nor have any memory address. So it is illegal to write &a. QUE.4 What will be output if you will compile and execute the following c code? #include <stdio.h>int main(){ int a = 5; int b = 10; { int a = 2; a++; b++; } printf("%d %d", a, b); return 0;} OPTION(a)5 10(b)6 11(c)5 11(d)6 10(e)Compiler error Answer : c Explanation: Default storage class of local variable is auto. Scope and visibility of auto variable is within the block in which it has declared. In C, if there are two variables of the same name, thenwe can access only local variable. Hence inside the inner block variable a is local variable which has declared and defined inside that block.When control comes out of the inner block local variable a became dead. QUE.5 What will be output if you will compile and execute the following C code? #include <stdio.h>int main(){ float f = 3.4e39; printf("%f", f); return 0;} OPTION(a)3.4e39(b)3.40000...(c)inf(d)Compiler error(e)Run time error Answer: c Explanation: If you will assign value beyond the range of float data type to the float variable it will not show any compiler error. It will store infinity. This article is contributed by Ajay Puri(ajay0007). 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. C-Output Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Output of C++ programs | Set 34 (File Handling) Result of sizeof operator Program to reverse columns in given 2D Array (Matrix) Output of C++ Program | Set 1 Output of Java program | Set 26 Output of C++ programs | Set 22 unsigned specifier (%u) in C with Examples Output of C Programs | Set 7 Output of C Programs | Set 6 Output of C programs | Set 8
[ { "code": null, "e": 25575, "s": 25547, "text": "\n23 Aug, 2017" }, { "code": null, "e": 25655, "s": 25575, "text": "QUE.1 What will be output if you will compile and execute the following c code?" }, { "code": "#include <stdio.h>int main(){ int a = 5; float b; p...
sdiff command in Linux with Examples - GeeksforGeeks
27 May, 2019 sdiff command in linux is used to compare two files and then writes the results to standard output in a side-by-side format. It displays each line of the two files with a series of spaces between them if the lines are identical. It displays greater than sign if the line only exists in the file specified by the File2 parameter, and a | (vertical bar) for lines that are different. Syntax: sdiff [ -l | -s ] [ -o OutFile ] [ -w Number ] File1 File2 Example:Text File 1: Geeks For Geeks A Computer Science Portal For Geeks Text File 2: Geeks For Geeks Technical Scripter 2018 Options of sdiff command: sdiff -l file1 file2 : It displays only the left side when lines are identical. sdiff -s file1 file2 : It does not display the identical identical lines. sdiff -w Number file1 file2 : It sets the width of the output line. The default value of the Number variable is 130 characters. The maximum width of the Number variable is 2048. The minimum width of the Number variable is 20. The sdiff command uses 2048 if a value greater than 2048 is specified. sdiff -o OutFile file1 file2 : Creates a third file, specified by the OutFile variable, by a controlled line-by-line merging of the two files specified by the File1 and the File2 parameters. The following subcommands govern the creation of this file:Output File:Geeks For Geeks --- geek1.txt 5, 10 A Computer Science Portal For Geeks +++ geek2.txt 5, 8 Technical Scripter 2018 Geeks For Geeks --- geek1.txt 5, 10 A Computer Science Portal For Geeks +++ geek2.txt 5, 8 Technical Scripter 2018 Reference: https://www.tecmint.com/linux-sdiff-command-examples/ linux-command Linux-file-commands Picked Technical Scripter 2018 Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples Docker - COPY Instruction mv command in Linux with examples SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25677, "s": 25649, "text": "\n27 May, 2019" }, { "code": null, "e": 26059, "s": 25677, "text": "sdiff command in linux is used to compare two files and then writes the results to standard output in a side-by-side format. It displays each line of the two files...
How to add a new class to an element that already has a class using jQuery ? - GeeksforGeeks
31 Dec, 2020 In this article, we will learn to add a new class to an element that already has a class using jQuery. To add a new class, we use jQuery addClass() method. The addClass() method is used to add more classes and their attributes to each selected element. It can also be used to change the property of the selected element. Syntax: $(selector).addClass(className); Parameters: It accepts a parameter “className”, the name of the new class that is to be added. Example: HTML <!DOCTYPE html><html lang="en"> <head> <style> .GFG1 { color: green; font-weight: bold; } .GFG2 { font-size: 24px; } </style> <!-- Import jQuery cdn library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function () { $("button").click(function () { $("p").addClass("GFG2"); }); }); </script></head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksforGeeks </h1> <h3> How to add a new class to an element that <br>already has a class using jQuery? </h3> <p class="GFG1"> GeeksforGeeks computer science portal </p> <button>Click Here!</button></body> </html> Output: Before Click the Button: After Click Button: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc jQuery-Misc CSS HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 26564, "s": 26536, "text": "\n31 Dec, 2020" }, { "code": null, "e": 26885, "s": 26564, "text": "In this article, we will learn to add a new class to an element that already has a class using jQuery. To add a new class, we use jQuery addClass() method. The add...
K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time) - GeeksforGeeks
25 Aug, 2021 We recommend to read following post as a prerequisite of this post.K’th Smallest/Largest Element in Unsorted Array | Set 1Given an array and a number k where k is smaller than size of array, we need to find the k’th largest element in the given array. It is given that all array elements are distinct. Examples: Input: arr[] = {7, 10, 4, 3, 20, 15} k = 3 Output: 7 Input: arr[] = {7, 10, 4, 3, 20, 15} k = 4 Output: 10 We have discussed three different solutions here.In this post method 4 is discussed which is mainly an extension of method 3 (QuickSelect) discussed in the previous post. C++ Java Python3 C# Javascript // C++ program of above implementation#include<bits/stdc++.h>using namespace std; // Standard partition process of QuickSort().// It considers the last element as pivot and// oves all smaller element to left of it// and greater elements to rightint partition(int *arr, int l, int r){ int x = arr[r], i = l; for (int j = l; j <= r - 1; j++) { if (arr[j] <= x) { swap(arr[i], arr[j]); i++; } } swap(arr[i], arr[r]); return i;} int randomPartition(int *arr, int l, int r){ int n = r - l + 1; int pivot = (rand() % 100 + 1) % n; swap(arr[l + pivot], arr[r]); return partition(arr, l, r);} // This function returns k'th smallest// element in arr[l..r] using// QuickSort based method. ASSUMPTION:// ALL ELEMENTS IN ARR[] ARE DISTINCTint kthSmallest(int *arr, int l, int r, int k){ // If k is smaller than number // of elements in array if (k > 0 && k <= r - l + 1) { // Partition the array around last // element and get position of pivot // element in sorted array int pos = randomPartition(arr, l, r); // If position is same as k if (pos - l == k - 1) { return arr[pos]; } // If position is more, recur // for left subarray if (pos - l > k - 1) { return kthSmallest(arr, l, pos - 1, k); } // Else recur for right subarray return kthSmallest(arr, pos + 1, r, k - pos + l - 1); } // If k is more than number of // elements in array return INT_MAX;} // Driver Codeint main(){ int arr[] = {12, 3, 5, 7, 4, 19, 26}; int n = sizeof(arr) / sizeof(arr[0]), k = 3; cout << "K'th smallest element is " << kthSmallest(arr, 0, n - 1, k);} // This code is contributed by Surbhi Tyagi. // Java program of above implementationimport java.util.Random; public class GFG { // This function returns k'th smallest element in arr[l..r] using// QuickSort based method. ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCT static int kthSmallest(int arr[], int l, int r, int k) { // If k is smaller than number of elements in array if (k > 0 && k <= r - l + 1) { // Partition the array around last element and get // position of pivot element in sorted array int pos = randomPartition(arr, l, r); // If position is same as k if (pos - l == k - 1) { return arr[pos]; } if (pos - l > k - 1) // If position is more, recur for left subarray { return kthSmallest(arr, l, pos - 1, k); } // Else recur for right subarray return kthSmallest(arr, pos + 1, r, k - pos + l - 1); } // If k is more than number of elements in array return Integer.MAX_VALUE; } static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Standard partition process of QuickSort(). It considers the last// element as pivot and moves all smaller element to left of it// and greater elements to right static int partition(int arr[], int l, int r) { int x = arr[r], i = l; for (int j = l; j <= r - 1; j++) { if (arr[j] <= x) { swap(arr, i, j); i++; } } swap(arr, i, r); return i; } static int randomPartition(int arr[], int l, int r) { int n = r - l + 1; int pivot = new Random().nextInt(n); swap(arr, l + pivot, r); return partition(arr, l, r); } // Driver program to test above methods public static void main(String args[]) { int arr[] = {12, 3, 5, 7, 4, 19, 26}; int n = arr.length, k = 3; System.out.println("K'th smallest element is " + kthSmallest(arr, 0, n - 1, k)); }} /*This code is contributed by 29AjayKumar*/ # Python3 implementation of above implementation # This function returns k'th smallest element# in arr[l..r] using QuickSort based method.# ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCTfrom random import randint def randomPartition(arr, l, r): n = r - l + 1 pivot = randint(1, 100) % n arr[l + pivot], arr[r] = arr[l + pivot], arr[r] return partition(arr, l, r) def kthSmallest(arr, l, r, k): # If k is smaller than # number of elements in array if (k > 0 and k <= r - l + 1): # Partition the array around last element and # get position of pivot element in sorted array pos = randomPartition(arr, l, r) # If position is same as k if (pos - l == k - 1): return arr[pos] # If position is more, recur for left subarray if (pos - l > k - 1): return kthSmallest(arr, l, pos - 1, k) # Else recur for right subarray return kthSmallest(arr, pos + 1, r, k - pos + l - 1) # If k is more than number of elements in array return 10**9 # Standard partition process of QuickSort().# It considers the last element as pivot and# moves all smaller element to left of it# and greater elements to rightdef partition(arr, l, r): x = arr[r] i = l for j in range(l, r): if (arr[j] <= x): arr[i], arr[j] = arr[j], arr[i] i += 1 arr[i], arr[r] = arr[r], arr[i] return i # Driver Codearr = [12, 3, 5, 7, 4, 19, 26]n = len(arr)k = 3print("K'th smallest element is", kthSmallest(arr, 0, n - 1, k)) # This code is contributed by Mohit Kumar // C# program of above implementationusing System; class GFG{ // This function returns k'th smallest// element in arr[l..r] using// QuickSort based method. ASSUMPTION:// ALL ELEMENTS IN ARR[] ARE DISTINCTstatic int kthSmallest(int []arr, int l, int r, int k){ // If k is smaller than number // of elements in array if (k > 0 && k <= r - l + 1) { // Partition the array around last // element and get position of pivot // element in sorted array int pos = randomPartition(arr, l, r); // If position is same as k if (pos - l == k - 1) { return arr[pos]; } // If position is more, recur // for left subarray if (pos - l > k - 1) { return kthSmallest(arr, l, pos - 1, k); } // Else recur for right subarray return kthSmallest(arr, pos + 1, r, k - pos + l - 1); } // If k is more than number of // elements in array return int.MaxValue;} static void swap(int[] arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;} // Standard partition process of QuickSort().// It considers the last element as pivot and// oves all smaller element to left of it// and greater elements to rightstatic int partition(int []arr, int l, int r){ int x = arr[r], i = l; for (int j = l; j <= r - 1; j++) { if (arr[j] <= x) { swap(arr, i, j); i++; } } swap(arr, i, r); return i;} static int randomPartition(int []arr, int l, int r){ int n = r - l + 1; int pivot = new Random().Next(1); swap(arr, l + pivot, r); return partition(arr, l, r);} // Driver Codepublic static void Main(){ int []arr = {12, 3, 5, 7, 4, 19, 26}; int n = arr.Length, k = 3; Console.WriteLine("K'th smallest element is " + kthSmallest(arr, 0, n - 1, k));}} // his code is contributed by 29AjayKumar <script> // Javascript program of above implementation // This function returns k'th smallest element// in arr[l..r] using QuickSort based method.// ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCTfunction kthSmallest(arr, l, r, k){ // If k is smaller than number of // elements in array if (k > 0 && k <= r - l + 1) { // Partition the array around last // element and get position of pivot // element in sorted array let pos = randomPartition(arr, l, r); // If position is same as k if (pos - l == k - 1) { return arr[pos]; } // If position is more, // recur for left subarray if (pos - l > k - 1) { return kthSmallest(arr, l, pos - 1, k); } // Else recur for right subarray return kthSmallest(arr, pos + 1, r, k - pos + l - 1); } // If k is more than number // of elements in array return Number.MAX_VALUE;} function swap(arr, i, j){ let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;} // Standard partition process of QuickSort().// It considers the last element as pivot and// moves all smaller element to left of it// and greater elements to rightfunction partition(arr, l, r){ let x = arr[r], i = l; for(let j = l; j <= r - 1; j++) { if (arr[j] <= x) { swap(arr, i, j); i++; } } swap(arr, i, r); return i;} function randomPartition(arr, l, r){ let n = r - l + 1; let pivot = (Math.floor(Math.random() * 101)) % n; swap(arr, l + pivot, r); return partition(arr, l, r);} // Driver codelet arr = [ 12, 3, 5, 7, 4, 19, 26 ];let n = arr.length, k = 3; document.write("K'th smallest element is " + kthSmallest(arr, 0, n - 1, k)); // This code is contributed by unknown2108 </script> K'th smallest element is 5 References: https://www.geeksforgeeks.org/kth-smallestlargest-element-unsorted-array/Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 29AjayKumar mohit kumar 29 saipavanbhanu unknown2108 surbhityagi15 lakshayjawa15 Order-Statistics Quick Sort Searching Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Best First Search (Informed Search) 3 Different ways to print Fibonacci series in Java Find whether an array is subset of another array | Added Method 5 Given a sorted and rotated array, find if there is a pair with a given sum Find closest number in array Program to remove vowels from a String Interpolation search vs Binary search Find common elements in three sorted arrays Recursive Programs to find Minimum and Maximum elements of array Find a pair with the given difference
[ { "code": null, "e": 26215, "s": 26187, "text": "\n25 Aug, 2021" }, { "code": null, "e": 26517, "s": 26215, "text": "We recommend to read following post as a prerequisite of this post.K’th Smallest/Largest Element in Unsorted Array | Set 1Given an array and a number k where k is ...
Python - Elements with same index - GeeksforGeeks
11 Oct, 2020 Given a List, get all elements which are at its index value. Input : test_list = [3, 1, 8, 5, 4, 10, 6, 9] Output : [1, 4, 6] Explanation : These elements are at same position as its number. Input : test_list = [3, 10, 8, 5, 14, 10, 16, 9] Output : [] Explanation : No number at its index. Method #1: Using loop In this, we check for each element, if it equates to its index, it’s added to result list. Python3 # Python3 code to demonstrate working of # Elements with same index# Using loop # initializing listtest_list = [3, 1, 2, 5, 4, 10, 6, 9] # printing original listprint("The original list is : " + str(test_list)) # enumerate to get index and elementres = []for idx, ele in enumerate(test_list): if idx == ele: res.append(ele) # printing result print("Filtered elements : " + str(res)) The original list is : [3, 1, 2, 5, 4, 10, 6, 9] Filtered elements : [1, 2, 4, 6] Method #2 : Using list comprehension + enumerate() In this, we perform a similar function as the above method, change being we use list comprehension to make the solution compact. Python3 # Python3 code to demonstrate working of # Elements with same index# Using list comprehension + enumerate() # initializing listtest_list = [3, 1, 2, 5, 4, 10, 6, 9] # printing original listprint("The original list is : " + str(test_list)) # enumerate to get index and elementres = [ele for idx, ele in enumerate(test_list) if idx == ele] # printing result print("Filtered elements : " + str(res)) The original list is : [3, 1, 2, 5, 4, 10, 6, 9] Filtered elements : [1, 2, 4, 6] Python list-programs Python Python Programs 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 Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25555, "s": 25527, "text": "\n11 Oct, 2020" }, { "code": null, "e": 25616, "s": 25555, "text": "Given a List, get all elements which are at its index value." }, { "code": null, "e": 25746, "s": 25616, "text": "Input : test_list = [3, 1, 8,...
Print all subarrays with 0 sum - GeeksforGeeks
07 Dec, 2021 Given an array, print all subarrays in the array which has sum 0.Examples: Input: arr = [6, 3, -1, -3, 4, -2, 2, 4, 6, -12, -7] Output: Subarray found from Index 2 to 4 Subarray found from Index 2 to 6 Subarray found from Index 5 to 6 Subarray found from Index 6 to 9 Subarray found from Index 0 to 10 Related posts: Find if there is a subarray with 0 sum A simple solution is to consider all subarrays one by one and check if sum of every subarray is equal to 0 or not. The complexity of this solution would be O(n^2).A better approach is to use Hashing.Do following for each element in the array Maintain sum of elements encountered so far in a variable (say sum).If current sum is 0, we found a subarray starting from index 0 and ending at index current indexCheck if current sum exists in the hash table or not.If current sum already exists in the hash table then it indicates that this sum was the sum of some sub-array elements arr[0]...arr[i] and now the same sum is obtained for the current sub-array arr[0]...arr[j] which means that the sum of the sub-array arr[i+1]...arr[j] must be 0.Insert current sum into the hash table Maintain sum of elements encountered so far in a variable (say sum). If current sum is 0, we found a subarray starting from index 0 and ending at index current index Check if current sum exists in the hash table or not. If current sum already exists in the hash table then it indicates that this sum was the sum of some sub-array elements arr[0]...arr[i] and now the same sum is obtained for the current sub-array arr[0]...arr[j] which means that the sum of the sub-array arr[i+1]...arr[j] must be 0. Insert current sum into the hash table Below is a dry run of the above approach: Below is the implementation of the above approach: C++ Java Python3 C# // C++ program to print all subarrays// in the array which has sum 0#include <bits/stdc++.h>using namespace std; // Function to print all subarrays in the array which// has sum 0vector< pair<int, int> > findSubArrays(int arr[], int n){ // create an empty map unordered_map<int, vector<int> > map; // create an empty vector of pairs to store // subarray starting and ending index vector <pair<int, int>> out; // Maintains sum of elements so far int sum = 0; for (int i = 0; i < n; i++) { // add current element to sum sum += arr[i]; // if sum is 0, we found a subarray starting // from index 0 and ending at index i if (sum == 0) out.push_back(make_pair(0, i)); // If sum already exists in the map there exists // at-least one subarray ending at index i with // 0 sum if (map.find(sum) != map.end()) { // map[sum] stores starting index of all subarrays vector<int> vc = map[sum]; for (auto it = vc.begin(); it != vc.end(); it++) out.push_back(make_pair(*it + 1, i)); } // Important - no else map[sum].push_back(i); } // return output vector return out;} // Utility function to print all subarrays with sum 0void print(vector<pair<int, int>> out){ for (auto it = out.begin(); it != out.end(); it++) cout << "Subarray found from Index " << it->first << " to " << it->second << endl;} // Driver codeint main(){ int arr[] = {6, 3, -1, -3, 4, -2, 2, 4, 6, -12, -7}; int n = sizeof(arr)/sizeof(arr[0]); vector<pair<int, int> > out = findSubArrays(arr, n); // if we didn’t find any subarray with 0 sum, // then subarray doesn’t exists if (out.size() == 0) cout << "No subarray exists"; else print(out); return 0;} // Java program to print all subarrays// in the array which has sum 0import java.io.*;import java.util.*; // User defined pair classclass Pair{ int first, second; Pair(int a, int b) { first = a; second = b; }} public class GFG{ // Function to print all subarrays in the array which // has sum 0 static ArrayList<Pair> findSubArrays(int[] arr, int n) { // create an empty map HashMap<Integer,ArrayList<Integer>> map = new HashMap<>(); // create an empty vector of pairs to store // subarray starting and ending index ArrayList<Pair> out = new ArrayList<>(); // Maintains sum of elements so far int sum = 0; for (int i = 0; i < n; i++) { // add current element to sum sum += arr[i]; // if sum is 0, we found a subarray starting // from index 0 and ending at index i if (sum == 0) out.add(new Pair(0, i)); ArrayList<Integer> al = new ArrayList<>(); // If sum already exists in the map there exists // at-least one subarray ending at index i with // 0 sum if (map.containsKey(sum)) { // map[sum] stores starting index of all subarrays al = map.get(sum); for (int it = 0; it < al.size(); it++) { out.add(new Pair(al.get(it) + 1, i)); } } al.add(i); map.put(sum, al); } return out; } // Utility function to print all subarrays with sum 0 static void print(ArrayList<Pair> out) { for (int i = 0; i < out.size(); i++) { Pair p = out.get(i); System.out.println("Subarray found from Index " + p.first + " to " + p.second); } } // Driver code public static void main(String args[]) { int[] arr = {6, 3, -1, -3, 4, -2, 2, 4, 6, -12, -7}; int n = arr.length; ArrayList<Pair> out = findSubArrays(arr, n); // if we did not find any subarray with 0 sum, // then subarray does not exists if (out.size() == 0) System.out.println("No subarray exists"); else print(out); }} // This code is contributed by rachana soma # Python3 program to print all subarrays# in the array which has sum 0 # Function to get all subarrays# in the array which has sum 0def findSubArrays(arr,n): # create a python dict hashMap = {} # create a python list # equivalent to ArrayList out = [] # tracker for sum of elements sum1 = 0 for i in range(n): # increment sum by element of array sum1 += arr[i] # if sum is 0, we found a subarray starting # from index 0 and ending at index i if sum1 == 0: out.append((0, i)) al = [] # If sum already exists in the map # there exists at-least one subarray # ending at index i with 0 sum if sum1 in hashMap: # map[sum] stores starting index # of all subarrays al = hashMap.get(sum1) for it in range(len(al)): out.append((al[it] + 1, i)) al.append(i) hashMap[sum1] = al return out # Utility function to print# all subarrays with sum 0def printOutput(output): for i in output: print ("Subarray found from Index " + str(i[0]) + " to " + str(i[1])) # Driver Codeif __name__ == '__main__': arr = [6, 3, -1, -3, 4, -2, 2, 4, 6, -12, -7] n = len(arr) out = findSubArrays(arr, n) # if we did not find any subarray with 0 sum, # then subarray does not exists if (len(out) == 0): print ("No subarray exists") else: printOutput (out) # This code is contributed by Vikas Chitturi // C# program to print all subarrays// in the array which has sum 0using System;using System.Collections.Generic; // User defined pair classclass Pair{ public int first, second; public Pair(int a, int b) { first = a; second = b; }} class GFG{ // Function to print all subarrays // in the array which has sum 0 static List<Pair> findSubArrays(int[] arr, int n) { // create an empty map Dictionary<int, List<int>> map = new Dictionary<int, List<int>>(); // create an empty vector of pairs to store // subarray starting and ending index List<Pair> outt = new List<Pair>(); // Maintains sum of elements so far int sum = 0; for (int i = 0; i < n; i++) { // add current element to sum sum += arr[i]; // if sum is 0, we found a subarray starting // from index 0 and ending at index i if (sum == 0) outt.Add(new Pair(0, i)); List<int> al = new List<int>(); // If sum already exists in the map there exists // at-least one subarray ending at index i with // 0 sum if (map.ContainsKey(sum)) { // map[sum] stores starting index // of all subarrays al = map[sum]; for (int it = 0; it < al.Count; it++) { outt.Add(new Pair(al[it] + 1, i)); } } al.Add(i); if(map.ContainsKey(sum)) map[sum] = al; else map.Add(sum, al); } return outt; } // Utility function to print all subarrays with sum 0 static void print(List<Pair> outt) { for (int i = 0; i < outt.Count; i++) { Pair p = outt[i]; Console.WriteLine("Subarray found from Index " + p.first + " to " + p.second); } } // Driver code public static void Main(String []args) { int[] arr = {6, 3, -1, -3, 4, -2, 2, 4, 6, -12, -7}; int n = arr.Length; List<Pair> outt = findSubArrays(arr, n); // if we did not find any subarray with 0 sum, // then subarray does not exists if (outt.Count == 0) Console.WriteLine("No subarray exists"); else print(outt); }} // This code is contributed by Rajput-Ji Output: Subarray found from Index 2 to 4 Subarray found from Index 2 to 6 Subarray found from Index 5 to 6 Subarray found from Index 6 to 9 Subarray found from Index 0 to 10 Time Complexity: O(N)Auxiliary Space: O(N) This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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. rachana soma veerravi Vikas Chitturi Rajput-Ji 06vaibhavtyagi arun211 Amazon Microsoft subarray subarray-sum Arrays Hash Amazon Microsoft Arrays Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Count pairs with given sum Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing)
[ { "code": null, "e": 25781, "s": 25753, "text": "\n07 Dec, 2021" }, { "code": null, "e": 25858, "s": 25781, "text": "Given an array, print all subarrays in the array which has sum 0.Examples: " }, { "code": null, "e": 26111, "s": 25858, "text": "Input: arr =...
Comparison of Python with Other Programming Languages - GeeksforGeeks
10 May, 2020 Python is an easily adaptable programming language that offers a lot of features. Its concise syntax and open-source nature promote readability and implementation of programs which makes it the fastest-growing programming language in current times. Python has various other advantages which give it an edge over other popular programming languages such as Java and C++. In Python there is no need for semicolon and curly braces in the program as compared to Java which will show syntax error if one forgot to add curly braces or semicolon in the program. Python code requires fewer lines of code as compare to Java to write the same program. For Example, Here is a code in Javapublic class PythonandJava { public static void main(String[] args) { System.out.println("Python and Java!"); }}Output:Python and Java! Same code written in Pythonprint("Python and Java !")Output:Python and Java! public class PythonandJava { public static void main(String[] args) { System.out.println("Python and Java!"); }} Output: Python and Java! Same code written in Python print("Python and Java !") Output: Python and Java! Python is dynamically typed that means one has to only assign a value to a variable at runtime, Python interpreter will detect the data type on itself as compare to Java where one has to explicitly mention the data type. Python supports various type of programming models such as imperative, object-oriented and procedural programming as compare to Java which is completely based on the object and class-based programming models. Python is easy to read and learn which is beneficial for beginners who are looking forward to understanding the fundamentals of programming quickly as compare to Java which has a steep learning curve due to its predefined complex syntaxes. Python concise syntax makes it a much better option for people of other disciplines who want to use programming language for data mining, neural processing, Machine Learning or statistical analysis as compare to Java syntax which is long and hard to read. Python is free and open-source means its code is available to the public on repositories and it is free for commercial purposes as compare to Java which may require a paid license to be used for large scale application development. Python code requires fewer resources to run since it directly gets compiled into machine code as compare to Java which first compiles to byte code, then needs to be compiled to machine code by the Java Virtual Machine(JVM). Python is more memory efficient because of its automatic garbage collection as compared to C++ which does not support garbage collection. Python code is easy to learn, use and write as compare to C++ which is hard to understand and use because of its complex syntax. Python uses an interpreter to execute the code which makes it easy to run on almost every computer or operating system. as compare to C++ code which does not run on other computers until it is compiled on that computer. Python can be easily used for rapid application development because of its smaller code size as compare to C++ which is impossible to use for rapid application development because of it large code fragments. Readability of Python code is more since it resembles actual English as compared to C++ code which contains hard to read structures and syntaxes. Variables defined in Python are easily accessible outside the loop as compare to C++ in which scope of variables is limited within the loop. C++ Difference Between Java Python Java CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Bitwise Operators in C/C++ Virtual Function in C++ Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between var, let and const keywords in JavaScript Differences between IPv4 and IPv6
[ { "code": null, "e": 25905, "s": 25877, "text": "\n10 May, 2020" }, { "code": null, "e": 26275, "s": 25905, "text": "Python is an easily adaptable programming language that offers a lot of features. Its concise syntax and open-source nature promote readability and implementation ...
HiPlot: Interactive Visualization Tool by Facebook | by Soner Yıldırım | Towards Data Science
Data visualization techniques are highly useful for exploring a dataset. There is wide variety of visualization types used in data science ecosystem. What best fits a given task depends on the characteristics of the data and variables. In this article, we will cover an interactive visualization tool created by Facebook. It is essentially a parallel coordinates plot. Thus, each row (i.e. data point) is represented with a line. The coordinates on the line are the variables (i.e. columns). Parallel coordinates plot provides a graphical representation of possible groups (or clusters) within a dataset. They also reveal certain patterns that can help distinguish data points. Parallel coordinates plot is also a convenient way of exploring high dimensional data for which traditional visualization techniques might fail to provide a decent solution. Facebook created HiPlot for hyperparameter tuning of neural networks. However, we can implement it on pretty much any dataset. The ultimate goal is the same: Explore the data well. We will use the famous iris dataset to demonstrate how HiPlot is used. The first step is to install HiPlot. The documentation provides a detailed explanation for how to install it in various environments. I’m using pip to install it. pip install -U hiplot We can now import all the dependencies and read the dataset into a pandas dataframe. import hiplot as hipimport pandas as pdfrom sklearn.datasets import load_irisiris = load_iris(as_frame=True)['frame']iris.head() It is extremely simple to create an interactive visualization with Hiplot. The following one line of code will create what we will be experimenting throughout the article. hip.Experiment.from_dataframe(iris).display() Hiplot also accepts an iterable (e.g. dictionary) as input data. In such cases, we use the from_iterable function instead of the from_dataframe function. Here is a screenshot of the generated plot. We notice some patterns just by looking at it. The iris dataset contains 4 independent variables and a target variable. The target takes one of three values depending on the independent variable values. What makes Hiplot exceptional is the interactive interface. For instance, we can select a value range on any of the variables on the graph. We select a value range on the petal width column. Only the data points that have a petal width in the selected range are displayed. We immediately notice that the selected range is distinctive for target value 0. It is possible to select a value range on multiple columns so we can create more specific patterns. We can also select a value from the target variable and see the pattern of data points that belong to that class. Hiplot allows for rearranging the columns on the graph. For instance, we can move the target variable and place it on far left. This feature comes in handy if you want to put categorical variable on one side and the numerical variables on the other. Hiplot also generates a table as part of the interactive interface. We can use this table to select data points and view them on the graph. We have covered a simple case to demonstrate how Hiplot can be used for exploratory data analysis. As the dimensionaly of the data increases (i.e. high number of columns), it becomes harder to use data visualization to explore the data. In such cases, Hiplot serves as a convenient tool. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 408, "s": 172, "text": "Data visualization techniques are highly useful for exploring a dataset. There is wide variety of visualization types used in data science ecosystem. What best fits a given task depends on the characteristics of the data and variables." }, { "code...
Player with max score | Practice | GeeksforGeeks
Given an array arr of non-negative integers of size N, 2 players are playing a game. In each move, a player chooses an element from either end of the array, and the size of the array shrinks by one. Both players take alternate chances and the game continues until the size of the array becomes 0. Every time a player chooses an array element the array value is added to the player's score. At the end player with maximum score wins. If player 1 starts the game, you have to predict whether player 1 will win the game or not. Both players will play optimally. Example 1: Input: N = 3 arr[] = {2,6,3} Output: 0 Explanation: Initially, player 1 can choose between 2 and 3. If he chooses 3 (or 2), then player 2 can choose from 2 (or 3) and 6. If player 2 chooses 6, then player 1 will be left with 2 (or 3). So, final score of player 1 is 2 + 3 = 5, and player 2 is 6. Hence, player 1 will never be the winner and output is 0. Your Task: You don't need to read input or print anything. Your task is to complete the function is1winner() which takes the array arr[], its size N and returns true if player 1 is the winner and false otherwise. The driver code itself prints 1 if returned value is true and 0 otherwise. Expected Time Complexity: O(N*N) Expected Auxiliary Space: O(N) Constraints: 1 <= N <= 1000 0<= arr[i] <= 105 0 prajjwalfire3 weeks ago int help(vector<int>& prefix,int lo,int hi,int arr[],vector<vector<int>>& dp) { if(hi-lo+1==1) return arr[lo]; if(dp[lo][hi]!=-1) return dp[lo][hi]; int total=prefix[hi]-prefix[lo]+arr[lo]; int one=total-help(prefix,lo+1,hi,arr,dp) int sec=total-help(prefix,lo,hi-1,arr,dp); return dp[lo][hi]=max(one,sec); } bool is1winner(int N,int arr[]) { vector<vector<int>> dp(N,vector<int>(N,-1)); vector<int> prefix(N); prefix[0]=arr[0]; for(int i=1;i<N;i++) { prefix[i]=prefix[i-1]+arr[i]; } auto player_one_score=help(prefix,0,N-1,arr,dp); int total=prefix.back(); return player_one_score>total-player_one_score; } 0 hamidnourashraf1 month ago class Solution: def rec_pick(self, arr, i, j, mem): if i > j: return 0 if mem[i][j] != -1: return mem[i][j] case1 = arr[i] + min(self.rec_pick(arr, i+2, j, mem), self.rec_pick(arr, i+1, j-1, mem)) case2 = arr[j] + min(self.rec_pick(arr, i, j-2, mem), self.rec_pick(arr, i+1, j-1, mem)) mem[i][j] = max(case1, case2) return mem[i][j] def is1winner (self, N, arr): mem = [[-1] * N for i in range(N)] p1 = self.rec_pick(arr, 0, N-1, mem) if p1 > (sum(arr) - p1): return True return False 0 pj63371 month ago Why wont the greedy solution work? +1 abhishekguptaaa3 months ago OPTIMAL STRATEGY FOR A GAME TOP DOWN APPROACH: class Solution{ public: int dp[1002][1002]; int solve(int i, int j, int arr[]) { if(i>j) { return 0; } if(dp[i][j]!=-1) { return dp[i][j]; } int x=arr[i]+min(solve(i+2,j,arr),solve(i+1,j-1,arr)); int y=arr[j]+min(solve(i+1,j-1,arr),solve(i,j-2,arr)); return dp[i][j]=max(x,y); } bool is1winner(int N,int arr[]) { // code here dp[N][N]; memset(dp,-1,sizeof(dp)); int sum=0; for(int i=0;i<N;i++) { sum+=arr[i]; } int res=solve(0,N-1,arr); if(res>(sum-res)) { return true; } else { return false; } } 0 2001shivank4 months ago 4 test cases, N=396,47,1000,100 there was some issue with my code. can someone explain? +17 rainx6 months ago EXPLAINATION As a respectable player1 , our task is to make player2 have the taste of defeat, Now how we gonna make it sure. Of-course, when will dynamic chance help us. Since the question says both player play optimally, we will write code so to make sure player1 our friend wins the game. Now, lets think how can our friend win against the opponent. I think if we can beforehand know, if the array element we are picking can help us in making sure the opponent always gets the minimum number, so we used our mind and write the recurrence function based on this idea. Let's see some cases to make our dumb friend clear. CASE 1: PICK FROM FRONT So Mr.Player1, if you pick from front, its fine, put the front element number in your bag and now, recursively make sure that the next number your opponent gets is minimum, So now the enemy will have two choice if you pick the first element, he will either pick the last element OR will pick the now front element and we want this kid to have the least possible value for himself. So we will take the minimum of the two. CASE 2: PICK FROM END So Mr.Player1, if you pick from END, its fine, put the end element number in your bag and now, recursively make sure that the next number your opponent gets is minimum, So now the enemy will have two choice ,if you pick the end element, he will either pick the now last element OR will pick the front element and we want this kid to have the least possible value for himself. So we will take the minimum of the two. Now, after we are done, we will save the maximum of two choices as obviously player1 will choose the max of the two choices. So player1 will choose max(CHOICE1 , CHOICE2). SO, THE RECURRENCE RELATION BOILS DOWN TO---- Choice1=arr[front]+min(func(arr,start+2,end),func(arr,start+1,end-1); Choice2=arr[end]+min(func(arr,start+1,end-1),func(arr,start,end-2); return max(Choice1,Choice2); CODE IMPLEMENTATION IS DOWN BELOW- int dp[1001][1001]; int helper(int arr[], int start, int end){ if(start>end){ return dp[start][end]=0; } if(start==end){ return dp[start][end]=arr[end]; } if(dp[start][end]!=-1){ return dp[start][end]; } int firstPick=arr[start]+min(helper(arr,start+2,end),helper(arr,start+1,end-1)); int endPick=arr[end]+min(helper(arr,start,end-2),helper(arr,start+1,end-1)); return dp[start][end]=max(firstPick,endPick); } bool is1winner(int N,int arr[]){ memset(dp,-1,sizeof(dp)); int sum=0; for(int i=0;i<N;i++){ sum+=arr[i]; } int player1=helper(arr,0,N-1); int player2=sum-player1; return player1>player2; } Upvote if you like and happy coding -1 chirags_307 months ago class Solution{ public: int dp[1001][1001]; int solve(int arr[], int s, int e) { if(s == e) return arr[s]; if(dp[s][e] != -1) return dp[s][e]; return dp[s][e] = max(arr[s] - solve(arr, s+1, e), arr[e] - solve(arr, s, e-1)); } bool is1winner(int N,int arr[]) { // code here memset(dp, -1, sizeof(dp)); return solve(arr, 0, N-1) > 0; } }; 0 Mike8 months ago Mike ACCECPTED!!https://uploads.disquscdn.c... D 0 Vikas079 months ago Vikas07 int dp[1002][1002];class Solution{ public:int solve(int arr[],int i,int j,bool isPlayer1){ if(i>j) return 0; if(dp[i][j]!=-1) return dp[i][j]; if(isPlayer1){//his job is to maximize the sum return dp[i][j]= max(arr[i]+solve(arr,i+1,j,0),arr[j]+solve(arr,i,j-1,0)); } else { return dp[i][j]= min(arr[i]*(-1)+solve(arr,i+1,j,1),arr[j]*(-1)+solve(arr,i,j-1,1)); } } bool is1winner(int N,int arr[]) { memset(dp,-1,sizeof(dp)); return (solve(arr,0,N-1,1)>0 ? true:false); }}; 0 Vikas079 months ago Vikas07 This question can be solved using Minimax Algorithm.Add values for player1 and for player2 take arr[i] as arr[i]*(-1) in addition.at last check if addition is negative or positive... thats where the ans lies. 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": 787, "s": 226, "text": "Given an array arr of non-negative integers of size N, 2 players are playing a game. In each move, a player chooses an element from either end of the array, and the size of the array shrinks by one. Both players take alternate chances and the game continu...
How to pass arguments to anonymous functions in JavaScript?
Following is the code for passing arguments to anonymous functions in JavaScript − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-weight: 500; font-size: 20px; color: blueviolet; } </style> </head> <body> <h1>Pass arguments to anonymous functions</h1> <div class="result"></div> <br /> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to call an anonymous function and pass parameters to it</h3> <script> let BtnEle = document.querySelector(".Btn"); let resEle = document.querySelector(".result"); let add = function (a, b) { return a + b; }; BtnEle.addEventListener("click", (event) => { resEle.innerHTML = "The sum of 22 and 19 = " + add(22, 19); }); </script> </body> </html> On clicking the ‘CLICK HERE’ button −
[ { "code": null, "e": 1145, "s": 1062, "text": "Following is the code for passing arguments to anonymous functions in JavaScript −" }, { "code": null, "e": 1156, "s": 1145, "text": " Live Demo" }, { "code": null, "e": 2048, "s": 1156, "text": "<!DOCTYPE html>\n...
Get the substring after the first occurrence of a separator in Java
We have the following string with a separator. String str = "Tom-Hanks"; We want the substring after the first occurrence of the separator i.e. Hanks For that, first you need to get the index of the separator and then using the substring() method get, the substring after the separator. String separator ="-"; int sepPos = str.indexOf(separator); System.out.println("Substring after separator = "+str.substring(sepPos + separator.length())); The following is an example. Live Demo public class Demo { public static void main(String[] args) { String str = "Tom-Hanks"; String separator ="-"; int sepPos = str.indexOf(separator); if (sepPos == -1) { System.out.println(""); } System.out.println("Substring after separator = "+str.substring(sepPos + separator.length())); } } Substring after separator = Hanks
[ { "code": null, "e": 1109, "s": 1062, "text": "We have the following string with a separator." }, { "code": null, "e": 1135, "s": 1109, "text": "String str = \"Tom-Hanks\";" }, { "code": null, "e": 1206, "s": 1135, "text": "We want the substring after the firs...
Program to convert integer to roman numeral in Python
Suppose we have a number num. We have to convert it into its equivalent roman numeral. Roman numerals contain the symbols and values like below − "I" = 1 "V" = 5 "X" = 10 "L" = 50 "C" = 100 "D" = 500 "M" = 1000 These symbols are typically written largest to smallest, and from left to right order, and can be computed by summing the values of all the symbols. But there are some special cases, where a symbol of lower value is to the left of a symbol of higher value, his indicates the lower value is subtracted from the higher one. These are examples of such cases − "I" is before "V", value 4. "I" is before "X", value 9. "X" is before "L", value 40. "X" is before "C", value 90. "C" is before "D", value 400. "C" is before "M", value 900. In Roman numerals there are also few rules − No symbol is repeated more than 3 times. The symbols "V", "L", and "D" are not repeated. So, if the input is like n = 1520, then the output will be "MDXX", because "MDXX" indicates 1000 + 500 + 10 + 10 = 1520. To solve this, we will follow these steps − res := blank string table = a list containing pairs (val, symbol) in this format, where val is the value and symbol is the associated symbol [(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I")] for each pair (cap, roman) in table, dod := floor of num/capm := num mod capres := res + roman * dnum := m d := floor of num/cap m := num mod cap res := res + roman * d num := m return res Let us see the following implementation to get better understanding − def solve(num): res = "" table = [ (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ] for cap, roman in table: d, m = divmod(num, cap) res += roman * d num = m return res num = 1520 print(solve(num)) 1520 MDXX
[ { "code": null, "e": 1208, "s": 1062, "text": "Suppose we have a number num. We have to convert it into its equivalent roman numeral. Roman numerals contain the symbols and values like below −" }, { "code": null, "e": 1216, "s": 1208, "text": "\"I\" = 1" }, { "code": null...
Coding a Web App to Simulate the Gambler’s Ruin Problem | by Claudia Ng | Towards Data Science
I find that simulations are a useful way to understand mathematical concepts, so I recently coded one to illustrate the gambler’s ruin problem. I made a web app to simulate a series of games and their outcomes in Python. In this web app, users define a set of parameters (probability of success per round (p), initial amount (i), goal amount (N) and number of games), and it will return the probability of winning as well as the balance at the end of every round for each game, as shown below. In this article, I will walk through how to code a gambler’s ruin simulation web app broken down into 3 steps: I) coding the simulation in Python, II) visualizing results using Plotly Dash, and III) deploying the web app on Heroku. The gambler’s ruin is a famous statistical concept that has practical applications in modern finance, such as pricing of stock options and insurance premiums. The concept is as follows: You walk into a casino with an initial amount of $i, with the hope of increasing your fortune to $N. You pick a gambling game where your probability of success is p per round, and we assume that each round is independent and identically distributed (i.i.d.). If you are successful that round, one unit is added to your balance. If you lose that round, one unit is removed from your balance. The game ends when either your balance is $0 or reaches $N. What is your probability of winning/ reaching your goal of $N? I wrote a GamblersRuin class for simulation purposes. When initializing the object, it takes probability p, initial amount i and goal amount N as arguments. After initializing the class, you would call the n_simulations function, where you can specify the number of games for the simulation, if not it would default to 100. This function is essentially a for loop that plays the predefined number of games and calls the gamble function. It returns a dataframe with the balance per round for every game, which is later used for plotting out the results. As for the gamble function mentioned above, it generates a random floating point number between 0 and 1 if the balance is between 0 and N. If the random number is less than probability p, then one unit is added to your balance, otherwise one unit is subtracted from your balance. This function returns a dataframe with the generated random float and the balance at each round. After coding the gambler’s ruin class method in Python, we can now call it and visualize the results using Plotly Dash. This can be broken down into three parts: a) initiating the Dash app, b) setting up the layout of the app, c) specifying callback functions, in other words, inputs and information to display. II.a.) Initiating the Dash app The Plotly Dash app uses Flask as the web framework. While you can pass your own flask app instance into Dash, I kept it simple and called the underlying Flask app with app.server. external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) server = app.server III.b.) Setting Up the Layout To compose the layout for my Dash app, I used the dash-html-components library that abstracts writing a web framework into Python code. These components are converted into HTML for the web app behind the scenes, and you can also add HTML elements to the Python Dash classes likestyle to customize your layout. In addition to using dash-html-components to customize my app layout, it is easy to add different components using the dash-core-components (dcc)library. I used dcc.Markdown to format text, dcc.Input to take user-specified inputs as arguments for my GamblersRuin class, and dcc.Graph to display the outcome. III.c.) Callback Functions As a last step, I specified the necessary callbacks based on user-submitted inputs. I also wrote the update_graph function to update the probability of win calculations and graph to be displayed, a Plotly line graph. You can now test the Dash app on your local machine! If you run the app.py file, the Dash app should now run on your localhost. The last step is deploying the app to a server. The deployment process using Heroku is relatively easy. Check out this guide for deploying to Heroku. To begin, you need to create a Heroku account. Define a requirements.txt file with the packages to run your Dash app and python files. Define a Procfile (a text file in the root directory of your repo) to specify the command to start your app. web: gunicorn app:server Specify your github repo and branch for deployment. You can do this using the heroku CLI or their web interface. Deploy! In this tutorial, I walked through how to code, visualize and deploy a gambler’s ruin simulation web app. Here is a brief summary of the steps: Code the simulation in Python as a class method that takes p, i, N as arguments and has functions to run a predefined number of simulations.Visualizing the results and outcome of the simuations using Plotly Dash.Deploying the Dash app on Heroku. Code the simulation in Python as a class method that takes p, i, N as arguments and has functions to run a predefined number of simulations. Visualizing the results and outcome of the simuations using Plotly Dash. Deploying the Dash app on Heroku. This web app took me roughly 5 hours from start to finish. I hope this article has inspired you to think about simulations that you could code, please feel free to comment below with your ideas! Gambler’s Ruin Dash App Github Repo Deploying on Heroku with Python Gambler’s Ruin Problem (Notes by Karl Sigman)
[ { "code": null, "e": 666, "s": 172, "text": "I find that simulations are a useful way to understand mathematical concepts, so I recently coded one to illustrate the gambler’s ruin problem. I made a web app to simulate a series of games and their outcomes in Python. In this web app, users define a se...
AngularJS HttpRequest
AngularJS provides $https: control which works as a service to read data from the server. Server can make a database call to get the records. AngularJS needs data in JSON format. Once data is ready, $https: can be used to get the data from server in the following manner. function studentController($scope,$https:) { var url="data.txt"; $https:.get(url).success( function(response) { $scope.students = response; }); } Here data.txt contains the student records. $https: service makes an ajax call and set response to its property students. "students" model can be used to be used to draw tables in the html. [ { "Name" : "Mahesh Parashar", "RollNo" : 101, "Percentage" : "80%" }, { "Name" : "Dinkar Kad", "RollNo" : 201, "Percentage" : "70%" }, { "Name" : "Robert", "RollNo" : 191, "Percentage" : "75%" }, { "Name" : "Julian Joe", "RollNo" : 111, "Percentage" : "77%" } ] <html> <head> <title>Angular JS Includes</title> <style> table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f2f2f2; } table tr:nth-child(even) { background-color: #ffffff; } </style> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app="" ng-controller="studentController"> <table> <tr> <th>Name</th> <th>Roll No</th> <th>Percentage</th> </tr> <tr ng-repeat="student in students"> <td>{{ student.Name }}</td> <td>{{ student.RollNo }}</td> <td>{{ student.Percentage }}</td> </tr> </table> </div> <script> function studentController($scope,$https:) { var url="data.txt"; $https:.get(url).success( function(response) { $scope.students = response; }); } </script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> </body> </html> To run this example, you need to deploy textAngularJS.htm, data.txt to a webserver. Open textAngularJS.htm using url of your server in a web browser. See the result. 16 Lectures 1.5 hours Anadi Sharma 40 Lectures 2.5 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2971, "s": 2699, "text": "AngularJS provides $https: control which works as a service to read data from the server. Server can make a database call to get the records. AngularJS needs data in JSON format. Once data is ready, $https: can be used to get the data from server in the...
Add PHP variable inside echo statement as href link address?
echo "<a href='".$link_address."'>Link</a>"; or echo "<a href='$link_address'>Link</a>"; <a href="<?php echo $link_address;?>"> Link </a>
[ { "code": null, "e": 1107, "s": 1062, "text": "echo \"<a href='\".$link_address.\"'>Link</a>\";" }, { "code": null, "e": 1110, "s": 1107, "text": "or" }, { "code": null, "e": 1151, "s": 1110, "text": "echo \"<a href='$link_address'>Link</a>\";" }, { "c...
JavaMail API - Quick Guide
The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. The JavaMail API provides a set of abstract classes defining objects that comprise a mail system. It is an optional package (standard extension) for reading, composing, and sending electronic messages. JavaMail provides elements that are used to construct an interface to a messaging system, including system components and interfaces. While this specification does not define any specific implementation, JavaMail does include several classes that implement RFC822 and MIME Internet messaging standards. These classes are delivered as part of the JavaMail class package. Following are some of the protocols supported in JavaMail API: SMTP: Acronym for Simple Mail Transfer Protocol. It provides a mechanism to deliver email. SMTP: Acronym for Simple Mail Transfer Protocol. It provides a mechanism to deliver email. POP: Acronym for Post Office Protocol. POP is the mechanism most people on the Internet use to get their mail. It defines support for a single mailbox for each user. RFC 1939 defines this protocol. POP: Acronym for Post Office Protocol. POP is the mechanism most people on the Internet use to get their mail. It defines support for a single mailbox for each user. RFC 1939 defines this protocol. IMAP: Acronym for Internet Message Access Protocol. It is an advanced protocol for receiving messages. It provides support for multiple mailbox for each user, in addition to, mailbox can be shared by multiple users. It is defined in RFC 2060. IMAP: Acronym for Internet Message Access Protocol. It is an advanced protocol for receiving messages. It provides support for multiple mailbox for each user, in addition to, mailbox can be shared by multiple users. It is defined in RFC 2060. MIME: Acronym for Multipurpose Internet Mail Extensions. . It is not a mail transfer protocol. Instead, it defines the content of what is transferred: the format of the messages, attachments, and so on. There are many different documents that take effect here: RFC 822, RFC 2045, RFC 2046, and RFC 2047. As a user of the JavaMail API, you usually don't need to worry about these formats. However, these formats do exist and are used by your programs. MIME: Acronym for Multipurpose Internet Mail Extensions. . It is not a mail transfer protocol. Instead, it defines the content of what is transferred: the format of the messages, attachments, and so on. There are many different documents that take effect here: RFC 822, RFC 2045, RFC 2046, and RFC 2047. As a user of the JavaMail API, you usually don't need to worry about these formats. However, these formats do exist and are used by your programs. NNTP and Others:There are many protocols that are provided by third-party providers. Some of them are Network News Transfer Protocol (NNTP), Secure Multipurpose Internet Mail Extensions (S/MIME) etc. NNTP and Others:There are many protocols that are provided by third-party providers. Some of them are Network News Transfer Protocol (NNTP), Secure Multipurpose Internet Mail Extensions (S/MIME) etc. Details of these will be covered in the subsequent chapters. As said above the java application uses JavaMail API to compose, send and receive emails.The following figure illustrates the architecture of JavaMail: The abstract mechanism of JavaMail API is similar to other J2EE APIs, such as JDBC, JNDI, and JMS. As seen the architecture diagram above, JavaMail API is divided into two main parts: An application-independent part: An application-programming interface (API) is used by the application components to send and receive mail messages, independent of the underlying provider or protocol used. An application-independent part: An application-programming interface (API) is used by the application components to send and receive mail messages, independent of the underlying provider or protocol used. A service-dependent part: A service provider interface (SPI) speaks the protocol-specific languages, such as SMTP, POP, IMAP, and Network News Transfer Protocol (NNTP). It is used to plug in a provider of an e-mail service to the J2EE platform. A service-dependent part: A service provider interface (SPI) speaks the protocol-specific languages, such as SMTP, POP, IMAP, and Network News Transfer Protocol (NNTP). It is used to plug in a provider of an e-mail service to the J2EE platform. To send an e-mail using your Java Application is simple enough but to start with you should have JavaMail API and Java Activation Framework (JAF) installed on your machine. You can download latest version of JavaMail (Version 1.5.0) from Java's standard website. You can download latest version of JavaMail (Version 1.5.0) from Java's standard website. You can download latest version of JAF (Version 1.1.1) from Java's standard website. You can download latest version of JAF (Version 1.1.1) from Java's standard website. Download and unzip these files, in the newly created top level directories you will find a number of jar files for both the applications. You need to add mail.jar and activation.jar files in your CLASSPATH. To send emails, you must have SMTP server that is responsible to send mails. You can use one of the following techniques to get the SMTP server: Install and use any SMTP server such as Postfix server (for Ubuntu), Apache James server (Java Apache Mail Enterprise Server)etc. (or) Install and use any SMTP server such as Postfix server (for Ubuntu), Apache James server (Java Apache Mail Enterprise Server)etc. (or) Use the SMTP server provided by the host provider for eg: free SMTP provide by JangoSMTP site is relay.jangosmtp.net (or) Use the SMTP server provided by the host provider for eg: free SMTP provide by JangoSMTP site is relay.jangosmtp.net (or) Use the SMTP Server provided by companies e.g. gmail, yahoo, etc. Use the SMTP Server provided by companies e.g. gmail, yahoo, etc. The JavaMail API consists of some interfaces and classes used to send, read, and delete e-mail messages. Though there are many packages in the JavaMail API, will cover the main two packages that are used in Java Mail API frequently: javax.mail and javax.mail.internet package. These packages contain all the JavaMail core classes. They are: Here is an example to send a simple email. Here we have used JangoSMTP server via which emails are sent to our destination email address. The setup is explained in the Environment Setup chapter. To send a simple email steps followed are: Get a Session Get a Session Create a default MimeMessage object and set From, To, Subject in the message. Create a default MimeMessage object and set From, To, Subject in the message. Set the actual message as: message.setText("your text goes here"); Set the actual message as: message.setText("your text goes here"); Send the message using the Transport object. Send the message using the Transport object. Create a java class file SendEmail, the contents of which are as follows: package com.tutorialspoint; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendEmail { public static void main(String[] args) { // Recipient's email ID needs to be mentioned. String to = "destinationemail@gmail.com"; // Sender's email ID needs to be mentioned String from = "fromemail@gmail.com"; final String username = "manishaspatil";//change accordingly final String password = "******";//change accordingly // Assuming you are sending email through relay.jangosmtp.net String host = "relay.jangosmtp.net"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", "25"); // Get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. Message message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set Subject: header field message.setSubject("Testing Subject"); // Now set the actual message message.setText("Hello, this is sample for to check send " + "email using JavaMailAPI "); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException e) { throw new RuntimeException(e); } } } As we are using the SMTP server provided by the host provider JangoSMTP, we need to authenticate the username and password. The javax.mail.PasswordAuthentication class is used to authenticate the password. Now that our class is ready, let us compile the above class. I've saved the class SendEmail.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmail.java Now that the class is compiled, execute the below command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmail You should see the following message on the command console: Sent message successfully.... As I'm sending an email to my gmail address through JangoSMTP, the following mail would be received in my gmail account inbox: Here is an example to send an email with attachment from your machine. The file on local machine is file.txt placed at /home/manisha/. Here we have used JangoSMTP server via which emails are sent to our destination email address. The setup is explained in the Environment Setup chapter. To send a email with an inline image, the steps followed are: Get a Session Get a Session Create a default MimeMessage object and set From, To, Subject in the message. Create a default MimeMessage object and set From, To, Subject in the message. Set the actual message as below: messageBodyPart.setText("This is message body"); Set the actual message as below: messageBodyPart.setText("This is message body"); Create a MimeMultipart object. Add the above messageBodyPart with actual message set in it, to this multipart object. Create a MimeMultipart object. Add the above messageBodyPart with actual message set in it, to this multipart object. Next add the attachment by creating a Datahandler as follows: messageBodyPart = new MimeBodyPart(); String filename = "/home/manisha/file.txt"; DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); Next add the attachment by creating a Datahandler as follows: messageBodyPart = new MimeBodyPart(); String filename = "/home/manisha/file.txt"; DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); Next set the multipart in the message as follows: message.setContent(multipart); Next set the multipart in the message as follows: message.setContent(multipart); Send the message using the Transport object. Send the message using the Transport object. Create a java class file SendAttachmentInEmail, the contents of which are as follows: package com.tutorialspoint; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class SendAttachmentInEmail { public static void main(String[] args) { // Recipient's email ID needs to be mentioned. String to = "destinationemail@gmail.com"; // Sender's email ID needs to be mentioned String from = "fromemail@gmail.com"; final String username = "manishaspatil";//change accordingly final String password = "******";//change accordingly // Assuming you are sending email through relay.jangosmtp.net String host = "relay.jangosmtp.net"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", "25"); // Get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. Message message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set Subject: header field message.setSubject("Testing Subject"); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Now set the actual message messageBodyPart.setText("This is message body"); // Create a multipar message Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new MimeBodyPart(); String filename = "/home/manisha/file.txt"; DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); // Send the complete message parts message.setContent(multipart); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException e) { throw new RuntimeException(e); } } } As we are using the SMTP server provided by the host provider JangoSMTP, we need to authenticate the username and password. The javax.mail.PasswordAuthentication class is used to authenticate the password. Now that our class is ready, let us compile the above class. I've saved the class SendAttachmentInEmail.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendAttachmentInEmail.java Now that the class is compiled, execute the below command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendAttachmentInEmail You should see the following message on the command console: Sent message successfully.... As I'm sending an email to my gmail address through JangoSMTP, the following mail would be received in my gmail account inbox: Here is an example to send an HTML email from your machine. Here we have used JangoSMTP server via which emails are sent to our destination email address. The setup is explained in the Environment Setup chapter. This example is very similar to sending simple email, except that, here we are using setContent() method to set content whose second argument is "text/html" to specify that the HTML content is included in the message. Using this example, you can send as big as HTML content you like. To send a email with HTML content, the steps followed are: Get a Session Get a Session Create a default MimeMessage object and set From, To, Subject in the message. Create a default MimeMessage object and set From, To, Subject in the message. Set the actual message using setContent() method as below: message.setContent("<h1>This is actual message embedded in HTML tags</h1>", "text/html"); Set the actual message using setContent() method as below: message.setContent("<h1>This is actual message embedded in HTML tags</h1>", "text/html"); Send the message using the Transport object. Send the message using the Transport object. Create a java class file SendHTMLEmail, the contents of which are as follows: package com.tutorialspoint; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendHTMLEmail { public static void main(String[] args) { // Recipient's email ID needs to be mentioned. String to = "destinationemail@gmail.com"; // Sender's email ID needs to be mentioned String from = "fromemail@gmail.com"; final String username = "manishaspatil";//change accordingly final String password = "******";//change accordingly // Assuming you are sending email through relay.jangosmtp.net String host = "relay.jangosmtp.net"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", "25"); // Get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. Message message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set Subject: header field message.setSubject("Testing Subject"); // Send the actual HTML message, as big as you like message.setContent( "<h1>This is actual message embedded in HTML tags</h1>", "text/html"); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException e) { e.printStackTrace(); throw new RuntimeException(e); } } } As we are using the SMTP server provided by the host provider JangoSMTP, we need to authenticate the username and password. The javax.mail.PasswordAuthentication class is used to authenticate the password. Now that our class is ready, let us compile the above class. I've saved the class SendHTMLEmail.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendHTMLEmail.java Now that the class is compiled, execute the below command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendHTMLEmail You should see the following message on the command console: Sent message successfully.... As I'm sending an email to my gmail address through JangoSMTP, the following mail would be received in my gmail account inbox: Here is an example to send an HTML email from your machine with inline image. Here we have used JangoSMTP server via which emails are sent to our destination email address. The setup is explained in the Environment Setup chapter. To send a email with an inline image, the steps followed are: Get a Session Get a Session Create a default MimeMessage object and set From, To, Subject in the message. Create a default MimeMessage object and set From, To, Subject in the message. Create a MimeMultipart object. Create a MimeMultipart object. In our example we will have an HTML part and an Image in the email. So first create the HTML content and set it in the multipart object as: // first part (the html) BodyPart messageBodyPart = new MimeBodyPart(); String htmlText = "<H1>Hello</H1><img src=\"cid:image\">"; messageBodyPart.setContent(htmlText, "text/html"); // add it multipart.addBodyPart(messageBodyPart); In our example we will have an HTML part and an Image in the email. So first create the HTML content and set it in the multipart object as: // first part (the html) BodyPart messageBodyPart = new MimeBodyPart(); String htmlText = "<H1>Hello</H1><img src=\"cid:image\">"; messageBodyPart.setContent(htmlText, "text/html"); // add it multipart.addBodyPart(messageBodyPart); Next add the image by creating a Datahandler as follows: // second part (the image) messageBodyPart = new MimeBodyPart(); DataSource fds = new FileDataSource( "/home/manisha/javamail-mini-logo.png"); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader("Content-ID", "<image>"); Next add the image by creating a Datahandler as follows: // second part (the image) messageBodyPart = new MimeBodyPart(); DataSource fds = new FileDataSource( "/home/manisha/javamail-mini-logo.png"); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader("Content-ID", "<image>"); Next set the multipart in the message as follows: message.setContent(multipart); Next set the multipart in the message as follows: message.setContent(multipart); Send the message using the Transport object. Send the message using the Transport object. Create a java class file SendInlineImagesInEmail, the contents of which are as follows: package com.tutorialspoint; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class SendInlineImagesInEmail { public static void main(String[] args) { // Recipient's email ID needs to be mentioned. String to = "destinationemail@gmail.com"; // Sender's email ID needs to be mentioned String from = "fromemail@gmail.com"; final String username = "manishaspatil";//change accordingly final String password = "******";//change accordingly // Assuming you are sending email through relay.jangosmtp.net String host = "relay.jangosmtp.net"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", "25"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. Message message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set Subject: header field message.setSubject("Testing Subject"); // This mail has 2 part, the BODY and the embedded image MimeMultipart multipart = new MimeMultipart("related"); // first part (the html) BodyPart messageBodyPart = new MimeBodyPart(); String htmlText = "<H1>Hello</H1><img src=\"cid:image\">"; messageBodyPart.setContent(htmlText, "text/html"); // add it multipart.addBodyPart(messageBodyPart); // second part (the image) messageBodyPart = new MimeBodyPart(); DataSource fds = new FileDataSource( "/home/manisha/javamail-mini-logo.png"); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader("Content-ID", "<image>"); // add image to the multipart multipart.addBodyPart(messageBodyPart); // put everything together message.setContent(multipart); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException e) { throw new RuntimeException(e); } } } As we are using the SMTP server provided by the host provider JangoSMTP, we need to authenticate the username and password. The javax.mail.PasswordAuthentication class is used to authenticate the password. Now that our class is ready, let us compile the above class. I've saved the class SendInlineImagesInEmail.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendInlineImagesInEmail.java Now that the class is compiled, execute the below command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendInlineImagesInEmail You should see the following message on the command console: Sent message successfully.... As I'm sending an email to my gmail address through JangoSMTP, the following mail would be received in my gmail account inbox: There are two aspects to which needs to understood before proceeding with this chapter. They are Check and Fetch. Checking an email in JavaMail is a process where we open the respective folder in the mailbox and get each message. Here we only check the header of each message i.e the From, To, subject. Content is not read. Checking an email in JavaMail is a process where we open the respective folder in the mailbox and get each message. Here we only check the header of each message i.e the From, To, subject. Content is not read. Fetching an email in JavaMail is a process where we open the respective folder in the mailbox and get each message. Alongwith the header we also read the content by recognizing the content-type. Fetching an email in JavaMail is a process where we open the respective folder in the mailbox and get each message. Alongwith the header we also read the content by recognizing the content-type. To check or fetch an email using JavaMail API, we would need POP or IMAP servers. To check and fetch the emails, Folder and Store classes are needed. Here we have used GMAIL's POP3 server (pop.gmail.com). In this chapter will learn how to check emails using JavaMail API. Fetching shall be covered in the subsequent chapters. To check emails: Get a Session Get a Session Create pop3 Store object and connect with pop server. Create pop3 Store object and connect with pop server. Create folder object. Open the appropriate folder in your mailbox. Create folder object. Open the appropriate folder in your mailbox. Get your messages. Get your messages. Close the Store and Folder objects. Close the Store and Folder objects. Create a java class file CheckingMails, the contents of which are as follows: package com.tutorialspoint; import java.util.Properties; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import javax.mail.Session; import javax.mail.Store; public class CheckingMails { public static void check(String host, String storeType, String user, String password) { try { //create properties field Properties properties = new Properties(); properties.put("mail.pop3.host", host); properties.put("mail.pop3.port", "995"); properties.put("mail.pop3.starttls.enable", "true"); Session emailSession = Session.getDefaultInstance(properties); //create the POP3 store object and connect with the pop server Store store = emailSession.getStore("pop3s"); store.connect(host, user, password); //create the folder object and open it Folder emailFolder = store.getFolder("INBOX"); emailFolder.open(Folder.READ_ONLY); // retrieve the messages from the folder in an array and print it Message[] messages = emailFolder.getMessages(); System.out.println("messages.length---" + messages.length); for (int i = 0, n = messages.length; i < n; i++) { Message message = messages[i]; System.out.println("---------------------------------"); System.out.println("Email Number " + (i + 1)); System.out.println("Subject: " + message.getSubject()); System.out.println("From: " + message.getFrom()[0]); System.out.println("Text: " + message.getContent().toString()); } //close the store and folder objects emailFolder.close(false); store.close(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { String host = "pop.gmail.com";// change accordingly String mailStoreType = "pop3"; String username = "yourmail@gmail.com";// change accordingly String password = "*****";// change accordingly check(host, mailStoreType, username, password); } } Now that our class is ready, let us compile the above class. I've saved the class CheckingMails.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: CheckingMails.java Now that the class is compiled, execute the below command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: CheckingMails You should see the following message on the command console: messages.length---4 --------------------------------- Email Number 1 Subject: Test Mail--Fetch From: <abcd@gmail.com> Text: javax.mail.internet.MimeMultipart@327a5b7f --------------------------------- Email Number 2 Subject: testing ----checking simple email From: <abcd@gmail.com> Text: javax.mail.internet.MimeMultipart@7f0d08bc --------------------------------- Email Number 3 Subject: Email with attachment From: <abcd@gmail.com> Text: javax.mail.internet.MimeMultipart@30b8afce --------------------------------- Email Number 4 Subject: Email with Inline image From: <abcd@gmail.com> Text: javax.mail.internet.MimeMultipart@2d1e165f Here we have printed the number of messages in the INBOX which is 4 in this case. We have also printed Subject, From address and Text for each email message. In the previous chapter we learnt how to check emails. Now let us see how to fetch each email and read its content. Let us write a Java class FetchingEmail which will read following types of emails: Simple email Simple email Email with attachment Email with attachment Email with inline image Email with inline image Basic steps followed in the code are as below: Get the Session object. Get the Session object. Create POP3 store object and connect to the store. Create POP3 store object and connect to the store. Create Folder object and open the appropriate folder in your mailbox. Create Folder object and open the appropriate folder in your mailbox. Retrieve messages. Retrieve messages. Close the folder and store objects respectively. Close the folder and store objects respectively. Create a java class file FetchingEmail, contents of which are as below: package com.tutorialspoint; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Date; import java.util.Properties; import javax.mail.Address; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.NoSuchProviderException; import javax.mail.Part; import javax.mail.Session; import javax.mail.Store; public class FetchingEmail { public static void fetch(String pop3Host, String storeType, String user, String password) { try { // create properties field Properties properties = new Properties(); properties.put("mail.store.protocol", "pop3"); properties.put("mail.pop3.host", pop3Host); properties.put("mail.pop3.port", "995"); properties.put("mail.pop3.starttls.enable", "true"); Session emailSession = Session.getDefaultInstance(properties); // emailSession.setDebug(true); // create the POP3 store object and connect with the pop server Store store = emailSession.getStore("pop3s"); store.connect(pop3Host, user, password); // create the folder object and open it Folder emailFolder = store.getFolder("INBOX"); emailFolder.open(Folder.READ_ONLY); BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); // retrieve the messages from the folder in an array and print it Message[] messages = emailFolder.getMessages(); System.out.println("messages.length---" + messages.length); for (int i = 0; i < messages.length; i++) { Message message = messages[i]; System.out.println("---------------------------------"); writePart(message); String line = reader.readLine(); if ("YES".equals(line)) { message.writeTo(System.out); } else if ("QUIT".equals(line)) { break; } } // close the store and folder objects emailFolder.close(false); store.close(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { String host = "pop.gmail.com";// change accordingly String mailStoreType = "pop3"; String username = "abc@gmail.com";// change accordingly String password = "*****";// change accordingly //Call method fetch fetch(host, mailStoreType, username, password); } /* * This method checks for content-type * based on which, it processes and * fetches the content of the message */ public static void writePart(Part p) throws Exception { if (p instanceof Message) //Call methos writeEnvelope writeEnvelope((Message) p); System.out.println("----------------------------"); System.out.println("CONTENT-TYPE: " + p.getContentType()); //check if the content is plain text if (p.isMimeType("text/plain")) { System.out.println("This is plain text"); System.out.println("---------------------------"); System.out.println((String) p.getContent()); } //check if the content has attachment else if (p.isMimeType("multipart/*")) { System.out.println("This is a Multipart"); System.out.println("---------------------------"); Multipart mp = (Multipart) p.getContent(); int count = mp.getCount(); for (int i = 0; i < count; i++) writePart(mp.getBodyPart(i)); } //check if the content is a nested message else if (p.isMimeType("message/rfc822")) { System.out.println("This is a Nested Message"); System.out.println("---------------------------"); writePart((Part) p.getContent()); } //check if the content is an inline image else if (p.isMimeType("image/jpeg")) { System.out.println("--------> image/jpeg"); Object o = p.getContent(); InputStream x = (InputStream) o; // Construct the required byte array System.out.println("x.length = " + x.available()); int i = 0; byte[] bArray = new byte[x.available()]; while ((i = (int) ((InputStream) x).available()) > 0) { int result = (int) (((InputStream) x).read(bArray)); if (result == -1) break; } FileOutputStream f2 = new FileOutputStream("/tmp/image.jpg"); f2.write(bArray); } else if (p.getContentType().contains("image/")) { System.out.println("content type" + p.getContentType()); File f = new File("image" + new Date().getTime() + ".jpg"); DataOutputStream output = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(f))); com.sun.mail.util.BASE64DecoderStream test = (com.sun.mail.util.BASE64DecoderStream) p .getContent(); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = test.read(buffer)) != -1) { output.write(buffer, 0, bytesRead); } } else { Object o = p.getContent(); if (o instanceof String) { System.out.println("This is a string"); System.out.println("---------------------------"); System.out.println((String) o); } else if (o instanceof InputStream) { System.out.println("This is just an input stream"); System.out.println("---------------------------"); InputStream is = (InputStream) o; is = (InputStream) o; int c; while ((c = is.read()) != -1) System.out.write(c); } else { System.out.println("This is an unknown type"); System.out.println("---------------------------"); System.out.println(o.toString()); } } } /* * This method would print FROM,TO and SUBJECT of the message */ public static void writeEnvelope(Message m) throws Exception { System.out.println("This is the message envelope"); System.out.println("---------------------------"); Address[] a; // FROM if ((a = m.getFrom()) != null) { for (int j = 0; j < a.length; j++) System.out.println("FROM: " + a[j].toString()); } // TO if ((a = m.getRecipients(Message.RecipientType.TO)) != null) { for (int j = 0; j < a.length; j++) System.out.println("TO: " + a[j].toString()); } // SUBJECT if (m.getSubject() != null) System.out.println("SUBJECT: " + m.getSubject()); } } Now that our class is ready, let us compile the above class. I've saved the class FetchingEmail.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: FetchingEmail.java Now that the class is compiled, execute the below command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: FetchingEmail You should see the following message on the command console: messages.length---3 --------------------------------- This is the message envelope --------------------------- FROM: XYZ <xyz@gmail.com> TO: ABC <abc@gmail.com> SUBJECT: Simple Message ---------------------------- CONTENT-TYPE: multipart/alternative; boundary=047d7b343d6ad3e4ea04e8ec6579 This is a Multipart --------------------------- ---------------------------- CONTENT-TYPE: text/plain; charset=ISO-8859-1 This is plain text --------------------------- Hi am a simple message string.... -- Regards xyz This is the message envelope --------------------------- FROM: XYZ <xyz@gmail.com> TO: ABC <abc@gmail.com> SUBJECT: Attachement ---------------------------- CONTENT-TYPE: multipart/mixed; boundary=047d7b343d6a99180904e8ec6751 This is a Multipart --------------------------- ---------------------------- CONTENT-TYPE: text/plain; charset=ISO-8859-1 This is plain text --------------------------- Hi I've an attachment.Please check -- Regards XYZ ---------------------------- CONTENT-TYPE: application/octet-stream; name=sample_attachement This is just an input stream --------------------------- Submit your Tutorials, White Papers and Articles into our Tutorials Directory. This is a tutorials database where we are keeping all the tutorials shared by the internet community for the benefit of others. This is the message envelope --------------------------- FROM: XYZ <xyz@gmail.com> TO: ABC <abc@gmail.com> SUBJECT: Inline Image ---------------------------- CONTENT-TYPE: multipart/related; boundary=f46d04182582be803504e8ece94b This is a Multipart --------------------------- ---------------------------- CONTENT-TYPE: text/plain; charset=ISO-8859-1 This is plain text --------------------------- Hi I've an inline image [image: Inline image 3] -- Regards XYZ ---------------------------- CONTENT-TYPE: image/png; name="javamail-mini-logo.png" content typeimage/png; name="javamail-mini-logo.png" Here you can see there are three emails in our mailbox. First a simple mail with message "Hi am a simple message string....". The second mail has an attachment. The contents of the attachment are also printed as seen above. The third mail has an inline image. We will modify our CheckingMails.java from the chapter Checking Emails. Its contents are as below: package com.tutorialspoint; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Store; public class CheckingMails { public static void check(String host, String storeType, String user, String password) { try { // create properties field Properties properties = new Properties(); properties.put("mail.pop3s.host", host); properties.put("mail.pop3s.port", "995"); properties.put("mail.pop3s.starttls.enable", "true"); // Setup authentication, get session Session emailSession = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( "manishapatil3may@gmail.com", "manisha123"); } }); // emailSession.setDebug(true); // create the POP3 store object and connect with the pop server Store store = emailSession.getStore("pop3s"); store.connect(); // create the folder object and open it Folder emailFolder = store.getFolder("INBOX"); emailFolder.open(Folder.READ_ONLY); // retrieve the messages from the folder in an array and print it Message[] messages = emailFolder.getMessages(); System.out.println("messages.length---" + messages.length); for (int i = 0, n = messages.length; i < n; i++) { Message message = messages[i]; System.out.println("---------------------------------"); System.out.println("Email Number " + (i + 1)); System.out.println("Subject: " + message.getSubject()); System.out.println("From: " + message.getFrom()[0]); System.out.println("Text: " + message.getContent().toString()); } // close the store and folder objects emailFolder.close(false); store.close(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { String host = "pop.gmail.com";// change accordingly String mailStoreType = "pop3"; String username = "abc@gmail.com";// change accordingly String password = "*****";// change accordingly check(host, mailStoreType, username, password); } } Now that our class is ready, let us compile the above class. I've saved the class CheckingMails.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: CheckingMails.java Now that the class is compiled, execute the below command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: CheckingMails You can see a similar message as below on the command console: messages.length---3 --------------------------------- Email Number 1 Subject: Today is a nice day From: XYZ <xyz@gmail.com> Text: javax.mail.internet.MimeMultipart@45f676cb --------------------------------- Email Number 2 Subject: hiiii.... From: XYZ <xyz@gmail.com> Text: javax.mail.internet.MimeMultipart@37f12d4f --------------------------------- Email Number 3 Subject: helloo From: XYZ <xyz@gmail.com> Text: javax.mail.internet.MimeMultipart@3ad5ba3a In this chapter we will see how to reply to an email using JavaMail API. Basic steps followed in the program below are: Get the Session object with POP and SMTP server details in the properties. We would need POP details to retrieve messages and SMTP details to send messages. Get the Session object with POP and SMTP server details in the properties. We would need POP details to retrieve messages and SMTP details to send messages. Create POP3 store object and connect to the store. Create POP3 store object and connect to the store. Create Folder object and open the appropriate folder in your mailbox. Create Folder object and open the appropriate folder in your mailbox. Retrieve messages. Retrieve messages. Iterate through the messages and type "Y" or "y" if you want to reply. Iterate through the messages and type "Y" or "y" if you want to reply. Get all information (To,From,Subject, Content) of the message. Get all information (To,From,Subject, Content) of the message. Build the reply message, using Message.reply() method. This method configures a new Message with the proper recipient and subject. The method takes a boolean parameter indicating whether to reply to only the sender (false) or reply to all (true). Build the reply message, using Message.reply() method. This method configures a new Message with the proper recipient and subject. The method takes a boolean parameter indicating whether to reply to only the sender (false) or reply to all (true). Set From,Text and Reply-to in the message and send it through the instance of Transport object. Set From,Text and Reply-to in the message and send it through the instance of Transport object. Close the Transport, folder and store objects respectively. Close the Transport, folder and store objects respectively. Create a java class file ReplyToEmail, the contents of which are as follows: package com.tutorialspoint; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Date; import java.util.Properties; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Session; import javax.mail.Store; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class ReplyToEmail { public static void main(String args[]) { Date date = null; Properties properties = new Properties(); properties.put("mail.store.protocol", "pop3"); properties.put("mail.pop3s.host", "pop.gmail.com"); properties.put("mail.pop3s.port", "995"); properties.put("mail.pop3.starttls.enable", "true"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.host", "relay.jangosmtp.net"); properties.put("mail.smtp.port", "25"); Session session = Session.getDefaultInstance(properties); // session.setDebug(true); try { // Get a Store object and connect to the current host Store store = session.getStore("pop3s"); store.connect("pop.gmail.com", "xyz@gmail.com", "*****");//change the user and password accordingly Folder folder = store.getFolder("inbox"); if (!folder.exists()) { System.out.println("inbox not found"); System.exit(0); } folder.open(Folder.READ_ONLY); BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); Message[] messages = folder.getMessages(); if (messages.length != 0) { for (int i = 0, n = messages.length; i < n; i++) { Message message = messages[i]; date = message.getSentDate(); // Get all the information from the message String from = InternetAddress.toString(message.getFrom()); if (from != null) { System.out.println("From: " + from); } String replyTo = InternetAddress.toString(message .getReplyTo()); if (replyTo != null) { System.out.println("Reply-to: " + replyTo); } String to = InternetAddress.toString(message .getRecipients(Message.RecipientType.TO)); if (to != null) { System.out.println("To: " + to); } String subject = message.getSubject(); if (subject != null) { System.out.println("Subject: " + subject); } Date sent = message.getSentDate(); if (sent != null) { System.out.println("Sent: " + sent); } System.out.print("Do you want to reply [y/n] : "); String ans = reader.readLine(); if ("Y".equals(ans) || "y".equals(ans)) { Message replyMessage = new MimeMessage(session); replyMessage = (MimeMessage) message.reply(false); replyMessage.setFrom(new InternetAddress(to)); replyMessage.setText("Thanks"); replyMessage.setReplyTo(message.getReplyTo()); // Send the message by authenticating the SMTP server // Create a Transport instance and call the sendMessage Transport t = session.getTransport("smtp"); try { //connect to the SMTP server using transport instance //change the user and password accordingly t.connect("abc", "****"); t.sendMessage(replyMessage, replyMessage.getAllRecipients()); } finally { t.close(); } System.out.println("message replied successfully ...."); // close the store and folder objects folder.close(false); store.close(); } else if ("n".equals(ans)) { break; } }//end of for loop } else { System.out.println("There is no msg...."); } } catch (Exception e) { e.printStackTrace(); } } } Now that our class is ready, let us compile the above class. I've saved the class ReplyToEmail.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: ReplyToEmail.java Now that the class is compiled, execute the following command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: ReplyToEmail You should see the following message on the command console: From: ABC <abc@gmail.com> Reply-to: abc@trioteksolutions.com To: XYZ <xyz@gmail.com> Subject: Hi today is a nice day Sent: Thu Oct 17 15:58:37 IST 2013 Do you want to reply [y/n] : y message replied successfully .... Check the inbox to which the mail was sent. In our case the message received looks as below: In this chapter we will see how to forward an email using JavaMail API. Basic steps followed in the program below are: Get the Session object with POP and SMTP server details in the properties. We would need POP details to retrieve messages and SMTP details to send messages. Get the Session object with POP and SMTP server details in the properties. We would need POP details to retrieve messages and SMTP details to send messages. Create POP3 store object and connect to the store. Create POP3 store object and connect to the store. Create Folder object and open the appropriate folder in your mailbox. Create Folder object and open the appropriate folder in your mailbox. Retrieve messages. Retrieve messages. Iterate through the messages and type "Y" or "y" if you want to forward. Iterate through the messages and type "Y" or "y" if you want to forward. Get all information (To,From,Subject, Content) of the message. Get all information (To,From,Subject, Content) of the message. Build the forward message by working with the parts that make up a message. First part would be the text of the message and a second part would be the message to forward. Combine the two into a multipart. Then you add the multipart to a properly addressed message and send it. Build the forward message by working with the parts that make up a message. First part would be the text of the message and a second part would be the message to forward. Combine the two into a multipart. Then you add the multipart to a properly addressed message and send it. Close the Transport, folder and store objects respectively. Close the Transport, folder and store objects respectively. Create a java class file ForwardEmail, the contents of which are as follows: package com.tutorialspoint; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Date; import java.util.Properties; import javax.mail.BodyPart; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Store; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class ForwardEmail { public static void main(String[] args) { Properties properties = new Properties(); properties.put("mail.store.protocol", "pop3"); properties.put("mail.pop3s.host", "pop.gmail.com"); properties.put("mail.pop3s.port", "995"); properties.put("mail.pop3.starttls.enable", "true"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.host", "relay.jangosmtp.net"); properties.put("mail.smtp.port", "25"); Session session = Session.getDefaultInstance(properties); try { // session.setDebug(true); // Get a Store object and connect to the current host Store store = session.getStore("pop3s"); store.connect("pop.gmail.com", "xyz@gmail.com", "*****");//change the user and password accordingly // Create a Folder object and open the folder Folder folder = store.getFolder("inbox"); folder.open(Folder.READ_ONLY); BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); Message[] messages = folder.getMessages(); if (messages.length != 0) { for (int i = 0, n = messages.length; i < n; i++) { Message message = messages[i]; // Get all the information from the message String from = InternetAddress.toString(message.getFrom()); if (from != null) { System.out.println("From: " + from); } String replyTo = InternetAddress.toString(message .getReplyTo()); if (replyTo != null) { System.out.println("Reply-to: " + replyTo); } String to = InternetAddress.toString(message .getRecipients(Message.RecipientType.TO)); if (to != null) { System.out.println("To: " + to); } String subject = message.getSubject(); if (subject != null) { System.out.println("Subject: " + subject); } Date sent = message.getSentDate(); if (sent != null) { System.out.println("Sent: " + sent); } System.out.print("Do you want to reply [y/n] : "); String ans = reader.readLine(); if ("Y".equals(ans) || "y".equals(ans)) { Message forward = new MimeMessage(session); // Fill in header forward.setRecipients(Message.RecipientType.TO, InternetAddress.parse(from)); forward.setSubject("Fwd: " + message.getSubject()); forward.setFrom(new InternetAddress(to)); // Create the message part MimeBodyPart messageBodyPart = new MimeBodyPart(); // Create a multipart message Multipart multipart = new MimeMultipart(); // set content messageBodyPart.setContent(message, "message/rfc822"); // Add part to multi part multipart.addBodyPart(messageBodyPart); // Associate multi-part with message forward.setContent(multipart); forward.saveChanges(); // Send the message by authenticating the SMTP server // Create a Transport instance and call the sendMessage Transport t = session.getTransport("smtp"); try { //connect to the SMTP server using transport instance //change the user and password accordingly t.connect("abc", "*****"); t.sendMessage(forward, forward.getAllRecipients()); } finally { t.close(); } System.out.println("message forwarded successfully...."); // close the store and folder objects folder.close(false); store.close(); }// end if }// end for }// end if } catch (Exception e) { e.printStackTrace(); } } } Now that our class is ready, let us compile the above class. I've saved the class ForwardEmail.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: ForwardEmail.java Now that the class is compiled, execute the following command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: ForwardEmail You should see the following message on the command console: From: ABC <abc@gmail.com> Reply-to: abc@trioteksolutions.com To: XYZ <xyz@gmail.com> Subject: Hi today is a nice day Sent: Thu Oct 17 15:58:37 IST 2013 Do you want to reply [y/n] : y message forwarded successfully.... Check the inbox to which the mail was sent. In our case the forwarded message would look as below: In this chapter we will see how to delete an email using JavaMail API. Deleting messages involves working with the Flags associated with the messages. There are different flags for different states, some system-defined and some user-defined. The predefined flags are defined in the inner class Flags.Flag and are listed below: Flags.Flag.ANSWERED Flags.Flag.ANSWERED Flags.Flag.DELETED Flags.Flag.DELETED Flags.Flag.DRAFT Flags.Flag.DRAFT Flags.Flag.FLAGGED Flags.Flag.FLAGGED Flags.Flag.RECENT Flags.Flag.RECENT Flags.Flag.SEEN Flags.Flag.SEEN Flags.Flag.USER Flags.Flag.USER POP protocol supports only deleting of the messages. Basic steps followed in the delete program are: Get the Session object with POP and SMTP server details in the properties. We would need POP details to retrieve messages and SMTP details to send messages. Get the Session object with POP and SMTP server details in the properties. We would need POP details to retrieve messages and SMTP details to send messages. Create POP3 store object and connect to the store. Create POP3 store object and connect to the store. Create Folder object and open the appropriate folder in your mailbox in READ_WRITE mode. Create Folder object and open the appropriate folder in your mailbox in READ_WRITE mode. Retrieves messages from inbox folder. Retrieves messages from inbox folder. Iterate through the messages and type "Y" or "y" if you want to delete the message by invoking the method setFlag(Flags.Flag.DELETED, true) on the Message object. Iterate through the messages and type "Y" or "y" if you want to delete the message by invoking the method setFlag(Flags.Flag.DELETED, true) on the Message object. The messages marked DELETED are not actually deleted, until we call the expunge() method on the Folder object, or close the folder with expunge set to true. The messages marked DELETED are not actually deleted, until we call the expunge() method on the Folder object, or close the folder with expunge set to true. Close the store object. Close the store object. Create a java class file ForwardEmail, the contents of which are as follows: package com.tutorialspoint; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Properties; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import javax.mail.Session; import javax.mail.Store; public class DeleteEmail { public static void delete(String pop3Host, String storeType, String user, String password) { try { // get the session object Properties properties = new Properties(); properties.put("mail.store.protocol", "pop3"); properties.put("mail.pop3s.host", pop3Host); properties.put("mail.pop3s.port", "995"); properties.put("mail.pop3.starttls.enable", "true"); Session emailSession = Session.getDefaultInstance(properties); // emailSession.setDebug(true); // create the POP3 store object and connect with the pop server Store store = emailSession.getStore("pop3s"); store.connect(pop3Host, user, password); // create the folder object and open it Folder emailFolder = store.getFolder("INBOX"); emailFolder.open(Folder.READ_WRITE); BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); // retrieve the messages from the folder in an array and print it Message[] messages = emailFolder.getMessages(); System.out.println("messages.length---" + messages.length); for (int i = 0; i < messages.length; i++) { Message message = messages[i]; System.out.println("---------------------------------"); System.out.println("Email Number " + (i + 1)); System.out.println("Subject: " + message.getSubject()); System.out.println("From: " + message.getFrom()[0]); String subject = message.getSubject(); System.out.print("Do you want to delete this message [y/n] ? "); String ans = reader.readLine(); if ("Y".equals(ans) || "y".equals(ans)) { // set the DELETE flag to true message.setFlag(Flags.Flag.DELETED, true); System.out.println("Marked DELETE for message: " + subject); } else if ("n".equals(ans)) { break; } } // expunges the folder to remove messages which are marked deleted emailFolder.close(true); store.close(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } catch (IOException io) { io.printStackTrace(); } } public static void main(String[] args) { String host = "pop.gmail.com";// change accordingly String mailStoreType = "pop3"; String username = "abc@gmail.com";// change accordingly String password = "*****";// change accordingly delete(host, mailStoreType, username, password); } } Now that our class is ready, let us compile the above class. I've saved the class DeleteEmail.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: DeleteEmail.java Now that the class is compiled, execute the following command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: DeleteEmail You should see the following message on the command console: messages.length---1 --------------------------------- Email Number 1 Subject: Testing From: ABC <abc@gmail.com> Do you want to delete this message [y/n] ? y Marked DELETE for message: Testing In all previous chapters we used JangoSMTP server to send emails. In this chapter we will learn about SMTP server provided by Gmail. Gmail (among others) offers use of their public SMTP server free of charge. Gmail SMTP server details can be found here. As you can see in the details, we can use either TLS or SSL connection to send email via Gmail SMTP server. The procedure to send email using Gmail SMTP server is similar as explained in chapter Sending Emails, except that we would change the host server. As a pre-requisite the sender email address should be an active gmail account. Let us try an example. Create a Java file SendEmailUsingGMailSMTP, contents of which are as below: package com.tutorialspoint; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendEmailUsingGMailSMTP { public static void main(String[] args) { // Recipient's email ID needs to be mentioned. String to = "xyz@gmail.com";//change accordingly // Sender's email ID needs to be mentioned String from = "abc@gmail.com";//change accordingly final String username = "abc";//change accordingly final String password = "*****";//change accordingly // Assuming you are sending email through relay.jangosmtp.net String host = "smtp.gmail.com"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", "587"); // Get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { // Create a default MimeMessage object. Message message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set Subject: header field message.setSubject("Testing Subject"); // Now set the actual message message.setText("Hello, this is sample for to check send " + "email using JavaMailAPI "); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException e) { throw new RuntimeException(e); } } } Here the host is set as smtp.gmail.com and port is set as 587. Here we have enabled TLS connection. Now that our class is ready, let us compile the above class. I've saved the class SendEmailUsingGMailSMTP.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmailUsingGMailSMTP.java Now that the class is compiled, execute the below command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmailUsingGMailSMTP You should see the following message on the command console: Sent message successfully.... So far, we’ve worked in our previous chapters mostly with the INBOX folder. This is the default folder in which most mail resides. Some systems might call it as INBOX and some other might call it by some other name. But,you can always access it from the JavaMail API using the name INBOX. The JavaMail API represents folders as instances of the abstract Folder class: public abstract class Folder extends Object This class declares methods for requesting named folders from servers, deleting messages from folders, searching for particular messages in folders, listing the messages in a folder, and so forth. We can't create a folder directly as the only constructor in the Folder class is protected. We can get a Folder from: a Session a Session a Store a Store or another Folder or another Folder All the above classes have a similar getFolder() method with similar signature: public abstract Folder getFolder(String name) throws MessagingException Some of the methods which help in getting the Folder object are: Following are some of the methods in Folder class which return basic information about a folder: Following are some of the methods which help manage the Folder: Following are some of the methods that help manage the messages in Folder: There are four methods to list the folders that a folder contains: The Folder class provides four methods for retrieving messages from open folders: If the server supports searching (as many IMAP servers do and most POP servers don’t), it’s easy to search a folder for the messages meeting certain criteria. The criteria are encoded in SearchTerm objects. Following are the two search methods: Flag modification is useful when you need to change flags for the entire set of messages in a Folder. Following are the methods provided in the Folder class: A quota in JavaMail is a limited or fixed number or amount of messages in a email store. Each Mail service request counts toward the JavaMail API Calls quota. An email service can apply following quota criterion: Maximum size of outgoing mail messages, including attachments. Maximum size of outgoing mail messages, including attachments. Maximum size of incoming mail messages, including attachments. Maximum size of incoming mail messages, including attachments. Maximum size of message when an administrator is a recipient Maximum size of message when an administrator is a recipient For Quota management JavaMail has following classes: Let us see and example in the following sections which checks for mail storage name, limit and its usage. Create a java class file QuotaExample, the contents of which are as follows: package com.tutorialspoint; import java.util.Properties; import javax.mail.Quota; import javax.mail.Session; import javax.mail.Store; import com.sun.mail.imap.IMAPStore; public class QuotaExample { public static void main(String[] args) { try { Properties properties = new Properties(); properties.put("mail.store.protocol", "imaps"); properties.put("mail.imaps.port", "993"); properties.put("mail.imaps.starttls.enable", "true"); Session emailSession = Session.getDefaultInstance(properties); // emailSession.setDebug(true); // create the IMAP3 store object and connect with the pop server Store store = emailSession.getStore("imaps"); //change the user and password accordingly store.connect("imap.gmail.com", "abc@gmail.com", "*****"); IMAPStore imapStore = (IMAPStore) store; System.out.println("imapStore ---" + imapStore); //get quota Quota[] quotas = imapStore.getQuota("INBOX"); //Iterate through the Quotas for (Quota quota : quotas) { System.out.println(String.format("quotaRoot:'%s'", quota.quotaRoot)); //Iterate through the Quota Resource for (Quota.Resource resource : quota.resources) { System.out.println(String.format( "name:'%s', limit:'%s', usage:'%s'", resource.name, resource.limit, resource.usage)); } } } catch (Exception e) { e.printStackTrace(); } } } Here are connection to the gmail service via IMAP (imap.gmail.com) server, as IMAPStore implements the QuotaAwareStore. Once you get the Store object, fetch the Quota array and iterate through it and print the relevant information. Now that our class is ready, let us compile the above class. I've saved the class QuotaExample.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: QuotaExample.java Now that the class is compiled, execute the below command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: QuotaExample You should see a similar message on the command console: imapStore ---imaps://abc%40gmail.com@imap.gmail.com quotaRoot:'' name:'STORAGE', limit:'15728640', usage:'513' A message can be bounced for several reasons. This problem is discussed in depth at rfc1211. Only a server can determine the existence of a particular mailbox or user name. When the server detects an error, it will return a message indicating the reason for the failure to the sender of the original message. There are many Internet standards covering Delivery Status Notifications but a large number of servers don't support these new standards, instead using ad hoc techniques for returning such failure messages. Hence it get very difficult to correlate the bounced message with the original message that caused the problem. JavaMail includes support for parsing Delivery Status Notifications. There are a number of techniques and heuristics for dealing with this problem. One of the techniques being Variable Envelope Return Paths. You can set the return path in the enveloper as shown in the example below. This is the address where bounce mails are sent to. You may want to set this to a generic address, different than the From: header, so you can process remote bounces. This done by setting mail.smtp.from property in JavaMail. Create a java class file SendEmail, the contents of which are as follows: import java.util.Properties; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendEmail { public static void main(String[] args) throws Exception { String smtpServer = "smtp.gmail.com"; int port = 587; final String userid = "youraddress";//change accordingly final String password = "*****";//change accordingly String contentType = "text/html"; String subject = "test: bounce an email to a different address " + "from the sender"; String from = "youraddress@gmail.com"; String to = "bouncer@fauxmail.com";//some invalid address String bounceAddr = "toaddress@gmail.com";//change accordingly String body = "Test: get message to bounce to a separate email address"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", smtpServer); props.put("mail.smtp.port", "587"); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.from", bounceAddr); Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userid, password); } }); MimeMessage message = new MimeMessage(mailSession); message.addFrom(InternetAddress.parse(from)); message.setRecipients(Message.RecipientType.TO, to); message.setSubject(subject); message.setContent(body, contentType); Transport transport = mailSession.getTransport(); try { System.out.println("Sending ...."); transport.connect(smtpServer, port, userid, password); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); System.out.println("Sending done ..."); } catch (Exception e) { System.err.println("Error Sending: "); e.printStackTrace(); } transport.close(); }// end function main() } Here we can see that the property mail.smtp.from is set different from the from address. Now that our class is ready, let us compile the above class. I've saved the class SendEmail.java to directory : /home/manisha/JavaMailAPIExercise. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class (both the jars are placed in /home/manisha/ directory) from command prompt: javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmail.java Now that the class is compiled, execute the below command to run: java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmail You should see the following message on the command console: Sending .... Sending done ... SMTP is an acronym for Simple Mail Transfer Protocol. It is an Internet standard for electronic mail (e-mail) transmission across Internet Protocol (IP) networks. SMTP uses TCP port 25. SMTP connections secured by SSL are known by the shorthand SMTPS, though SMTPS is not a protocol in its own right. JavaMail API has package com.sun.mail.smtp which act as SMTP protocol provider to access an SMTP server. Following table lists the classes included in this package: The following table lists the exceptions thrown: The com.sun.mail.smtp provider use SMTP Authentication optionally. To use SMTP authentication you'll need to set the mail.smtp.auth property or provide the SMTP Transport with a username and password when connecting to the SMTP server. You can do this using one of the following approaches: Provide an Authenticator object when creating your mail Session and provide the username and password information during the Authenticator callback. mail.smtp.user property can be set to provide a default username for the callback, but the password will still need to be supplied explicitly. This approach allows you to use the static Transport send method to send messages. For example: Provide an Authenticator object when creating your mail Session and provide the username and password information during the Authenticator callback. mail.smtp.user property can be set to provide a default username for the callback, but the password will still need to be supplied explicitly. This approach allows you to use the static Transport send method to send messages. For example: Transport.send(message); Call the Transport connect method explicitly with username and password arguments. For example: Transport tr = session.getTransport("smtp"); tr.connect(smtphost, username, password); msg.saveChanges(); tr.sendMessage(msg, msg.getAllRecipients()); tr.close(); Call the Transport connect method explicitly with username and password arguments. For example: Transport tr = session.getTransport("smtp"); tr.connect(smtphost, username, password); msg.saveChanges(); tr.sendMessage(msg, msg.getAllRecipients()); tr.close(); The SMTP protocol provider supports the following properties, which may be set in the JavaMail Session object. The properties are always set as strings. For example: props.put("mail.smtp.port", "587"); IMAP is Acronym for Internet Message Access Protocol. It is an Application Layer Internet protocol that allows an e-mail client to access e-mail on a remote mail server. An IMAP server typically listens on well-known port 143. IMAP over SSL (IMAPS) is assigned to port number 993. IMAP supports both on-line and off-line modes of operation. E-mail clients using IMAP generally leave messages on the server until the user explicitly deletes them. Package com.sun.mail.imap is an IMAP protocol provider for the JavaMail API that provides access to an IMAP message store. The table below lists the interface and classes of this provider: Some points to be noted above this provider: This provider supports both the IMAP4 and IMAP4rev1 protocols. This provider supports both the IMAP4 and IMAP4rev1 protocols. A connected IMAPStore maintains a pool of IMAP protocol objects for use in communicating with the IMAP server. As folders are opened and new IMAP protocol objects are needed, the IMAPStore will provide them from the connection pool, or create them if none are available. When a folder is closed, its IMAP protocol object is returned to the connection pool if the pool . A connected IMAPStore maintains a pool of IMAP protocol objects for use in communicating with the IMAP server. As folders are opened and new IMAP protocol objects are needed, the IMAPStore will provide them from the connection pool, or create them if none are available. When a folder is closed, its IMAP protocol object is returned to the connection pool if the pool . The connected IMAPStore object may or may not maintain a separate IMAP protocol object that provides the store a dedicated connection to the IMAP server. The connected IMAPStore object may or may not maintain a separate IMAP protocol object that provides the store a dedicated connection to the IMAP server. Post Office Protocol (POP) is an application-layer Internet standard protocol used by local e-mail clients to retrieve e-mail from a remote server over a TCP/IP connection. POP supports simple download-and-delete requirements for access to remote mailboxes. A POP3 server listens on well-known port 110. Package com.sun.mail.pop3 is a POP3 protocol provider for the JavaMail API that provides access to a POP3 message store. The table below lists the classes in this package: Some points to be noted above this provider: POP3 provider supports only a single folder named INBOX. Due to the limitations of the POP3 protocol, many of the JavaMail API capabilities like event notification, folder management, flag management, etc. are not allowed. POP3 provider supports only a single folder named INBOX. Due to the limitations of the POP3 protocol, many of the JavaMail API capabilities like event notification, folder management, flag management, etc. are not allowed. The POP3 provider is accessed through the JavaMail APIs by using the protocol name pop3 or a URL of the form pop3://user:password@host:port/INBOX". The POP3 provider is accessed through the JavaMail APIs by using the protocol name pop3 or a URL of the form pop3://user:password@host:port/INBOX". POP3 supports no permanent flags. For example the Flags.Flag.RECENT flag will never be set for POP3 messages. It's up to the application to determine which messages in a POP3 mailbox are new. POP3 supports no permanent flags. For example the Flags.Flag.RECENT flag will never be set for POP3 messages. It's up to the application to determine which messages in a POP3 mailbox are new. POP3 does not support the Folder.expunge() method. To delete and expunge messages, set the Flags.Flag.DELETED flag on the messages and close the folder using the Folder.close(true) method. POP3 does not support the Folder.expunge() method. To delete and expunge messages, set the Flags.Flag.DELETED flag on the messages and close the folder using the Folder.close(true) method. POP3 does not provide a received date, so the getReceivedDate method will return null. POP3 does not provide a received date, so the getReceivedDate method will return null. When the headers of a POP3 message are accessed, the POP3 provider uses the TOP command to fetch all headers, which are then cached. When the headers of a POP3 message are accessed, the POP3 provider uses the TOP command to fetch all headers, which are then cached. When the content of a POP3 message is accessed, the POP3 provider uses the RETR command to fetch the entire message. When the content of a POP3 message is accessed, the POP3 provider uses the RETR command to fetch the entire message. The POP3Message.invalidate method can be used to invalidate cached data without closing the folder. The POP3Message.invalidate method can be used to invalidate cached data without closing the folder. Print Add Notes Bookmark this page
[ { "code": null, "e": 2400, "s": 2071, "text": "The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. The JavaMail API provides a set of abstract classes defining objects that comprise a mail system. It is an optional package (st...
How to use an alias() for the parameter in PowerShell?
PowerShell alias is a good way to use the shortcut name for the Parameter instead of writing the full name of the parameter. For example, you can refer to Server as ServerName, AppID as the ApplicationID. So you don’t have to use the whole name of the parameter and it is easy to remember as well. function Aliastest{ param( [parameter(Mandatory=$true)] [Alias("Server")] [string]$ServerName ) Write-Output "Server name is $ServerName" } Now we can use the Server instead of ServerName while passing the arguments. PS C:\> Aliastest -server "Test1-Win2k16" Server name is Test1-Win2k16
[ { "code": null, "e": 1267, "s": 1062, "text": "PowerShell alias is a good way to use the shortcut name for the Parameter instead of writing the full name of the parameter. For example, you can refer to Server as ServerName, AppID as the ApplicationID." }, { "code": null, "e": 1360, "...
HTML Geolocation watchPosition() Method - GeeksforGeeks
20 Dec, 2021 In this article, we will discuss the Geolocation watchPosition() method. Geolocation in HTML is used to register a handler function that will be called automatically each time the position of the device changes. Syntax: navigator.geolocation.watchPosition(showLoc, error, options); Parameter: showLoc: It is also a function for success message that will display latitude, longitude, timestamp, etc error: It will return the error messages and warnings of the position if applicable options: It is used to set enableHighAccuracy, timeout, and maximumAge Where showLoc success message includes the following: latitude: This property will return the latitude of the given location longitude: This property will return the longitude of the given location timestamp: This property will return the timestamp of the given location speed: This property will return the speed of the given location altitude: This property will return the altitude above the sea level of the given location accuracy: This property will return the accuracy above the sea level of the given location Example: This example display the latitude and longitude of the watchPosition() method. HTML <!DOCTYPE html><html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1" /></head> <body> <h2 style="color: green">GeeksforGeeks</h2> <p><b> Displaying Latitude and Longitude</b></p> <button onclick="getlocation()">Click Me</button> <p id="paraID"></p> <p id="paraID1"></p> <script> var variable1 = document.getElementById("paraID"); var variable2 = document.getElementById("paraID1"); // This function will get your current location function getlocation() { navigator.geolocation.watchPosition(showLoc); } // This function will show your current location function showLoc(pos) { variable1.innerHTML = "Latitude: " + pos.coords.latitude; variable2.innerHTML = "Longitude: " + pos.coords.longitude; } </script></body> </html> Output: Example 2: Display Timestamp HTML <!DOCTYPE html><html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1" /></head> <body> <h2 style="color: green">GeeksforGeeks</h2> <p><b> Displaying Timestamp</b></p> <button onclick="getlocation()">Click Me</button> <p id="paraID"></p> <script> var variable1 = document.getElementById("paraID"); // This function will get your current location function getlocation() { navigator.geolocation.watchPosition(showLoc); } // This function will show your current location function showLoc(pos) { variable1.innerHTML = "Timestamp: " + pos.timestamp; } </script></body> </html> Output: Example 3: Display Speed HTML <!DOCTYPE html><html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1" /></head> <body> <h2 style="color: green">GeeksforGeeks</h2> <p><b> Displaying Timestamp</b></p> <button onclick="getlocation()">Click Me</button> <p id="paraID"></p> <script> var variable1 = document.getElementById("paraID"); // This function will get your current location function getlocation() { navigator.geolocation.watchPosition(showLoc); } // This function will show your current location function showLoc(pos) { variable1.innerHTML = "Timestamp: " + pos.timestamp; } </script></body> </html> Output: Example 4: Display Altitude HTML <!DOCTYPE html><html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1" /></head> <body> <h2 style="color: green">GeeksforGeeks</h2> <p><b> Displaying Altitude</b></p> <button onclick="getlocation()">Click Me</button> <p id="paraID"></p> <script> var variable1 = document.getElementById("paraID"); // This function will get your current location function getlocation() { navigator.geolocation.watchPosition(showLoc); } // This function will show your current location function showLoc(pos) { variable1.innerHTML = "Altitude: " + pos.coords.altitude; } </script></body> </html> Output: Example 5: Display Accuracy HTML <!DOCTYPE html><html> <body> <h2 style="color: green">GeeksforGeeks</h2> <p><b> Displaying Accuracy</b></p> <button onclick="getlocation()">Click Me</button> <p id="paraID"></p> <script> var variable1 = document.getElementById("paraID"); // This function will get your current location function getlocation() { navigator.geolocation.watchPosition(showLoc); } // This function will show your current location function showLoc(pos) { variable1.innerHTML = "Accuracy: " + pos.coords.accuracy; } </script></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. anikaseth98 HTML-Methods Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments REST API (Introduction) Design a web page using HTML and CSS Form validation using jQuery How to place text on image using HTML and CSS? How to auto-resize an image to fit a div container using CSS? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 24503, "s": 24475, "text": "\n20 Dec, 2021" }, { "code": null, "e": 24715, "s": 24503, "text": "In this article, we will discuss the Geolocation watchPosition() method. Geolocation in HTML is used to register a handler function that will be called automatical...
Bar Plots: Best Practices and Issues | by Elena Kosourova | Towards Data Science
Being one of the most common visualization types, a bar plot is technically very easy to create: we need to write just one short line of code. However, if we want to create a really informative, easily readable graph efficiently revealing the story behind the data, we have to keep in mind several important things, which we’re going to discuss in this article. Some of these suggestions are only specific to bar plots, the others apply to any kind of visualizations. To practice our bar plots, we’ll use a very bar-related dataset from Kaggle — Alcohol Consumption around the World 🤪🍾 The table is dated by 2010, so let’s travel a bit back in time. import pandas as pdimport numpy as npimport matplotlibimport matplotlib.pyplot as pltimport seaborn as snsdf = pd.read_csv('drinks.csv')print('Number of all the countries:', len(df), '\n')# Removing the countries with 0 alcohol consumptiondf = df[df['total_litres_of_pure_alcohol'] > 0]\ .reset_index(drop=True)print(df.head(3), '\n')print('Number of all the drinking countries:', len(df))Output:Number of all the countries: 193 country beer_servings spirit_servings wine_servings \0 Albania 89 132 54 1 Algeria 25 0 14 2 Andorra 245 138 312 total_litres_of_pure_alcohol 0 4.9 1 0.7 2 12.4 Number of all the drinking countries: 180 As a general rule, we should maximize the data-ink ratio of the graph and, hence, exclude everything that doesn’t provide any additional information for our storytelling through the data. To start with, we should avoid any features on the plot that could potentially distract the reader’s attention: unnecessary spines and ticks, the grid, if it’s redundant, decimal numbers where possible, especially those with many decimal points, putting the exact numbers (decimal or not) on top of each bar: if we really need them, we can supplement our graph with a corresponding table. Alternatively, we can use only these direct labels on top of the bars and remove the numeric axis, for not to duplicate the same information. A seemingly obvious, but sometimes neglected or misused aspect of storytelling when creating bar plots is related to labeling and sizing: sufficient width and height of the figure, an easily readable font size of the graph title, axes labels, ticks, and annotations (if present), the title as laconic as possible while still exhaustively descriptive, divided into no more than 2–3 rows (if long), clear axes labels, rotating tick labels (if necessary), the units for the measured value (%, fractions, or whatever absolute values) included in the axis label or directly in the title, if the values of the categorical axis are self-explanatory, we can omit this axis label. The following features should be always avoided when creating bar plots: 3D bar plots: they severely deform the reality creating an optical illusion and making it more difficult to identify the real height (length) of each bar. Moreover, the bars in the back can be completely covered by the bars in the front and hence just invisible to the reader. Interactivity (except for very rare cases). Decorations or color effects. Let’s compare the 2 bar plots below, which are identical in terms of the data, but different in their style. Also, we’ll find out what countries consumed alcohol most of all in 2010: top5_alcohol = df.sort_values('total_litres_of_pure_alcohol', ascending=False)[:5]\ .reset_index(drop=True)fig, ax = plt.subplots(figsize=(16,7))fig.tight_layout(pad=2)plt.subplot(1,2,1)sns.set_style('whitegrid')ax = sns.barplot(x='country', y='total_litres_of_pure_alcohol', data=top5_alcohol)for p in ax.patches: ax.annotate(format(p.get_height(), '.1f'), (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center', xytext=(0, 7), textcoords='offset points')plt.title('TOP5 countries by pure alcohol consumption')plt.xlabel('Countries')plt.ylabel('Litres per person')ax.grid(True)plt.subplot(1,2,2)sns.set_style('ticks')ax = sns.barplot(x='country', y='total_litres_of_pure_alcohol', data=top5_alcohol)plt.title('TOP5 countries by pure alcohol consumption', fontsize=30)plt.xlabel(None)plt.xticks(fontsize=22, rotation=30)plt.ylabel('Litres per person', fontsize=25)plt.yticks(fontsize=22)sns.despine(bottom=True)ax.grid(False)ax.tick_params(bottom=False, left=True)for _,s in ax.spines.items(): s.set_color('black')plt.show() The second bar plot, even if still not ideal, is definitely much cleaner and better readable than the first one. We removed unnecessary spines, the ticks from the categorical axis, the grid, the bar values denotations, increased font size, rotated x-tick labels, omitted the categorical axis label. And yes, we clearly see what countries drank more alcohol in 2010. Most probably, though, they were consuming different kinds of drinks. We’ll investigate this question soon. We’ve already mentioned that using additional color effects, like background or font color, isn’t a good practice. There are a couple of other things to consider when selecting colors for a bar plot. When applying different colors doesn’t communicate anything about the data, it should be avoided. By default, each bar in a seaborn bar plot is colored differently, as we saw earlier. We can override it by introducing the color parameter and assigning the same color to all the bars. However, we still can emphasize some bars in particular and display the other ones in grey color. For example, of our TOP5 countries above, let’s highlight the leader in drinking exactly spirit. Besides color emphasizing, we’ll add also a corresponding annotation: spirit_top = top5_alcohol['spirit_servings']colors = ['grey' if (s < max(spirit_top)) else 'red' for s in spirit_top]fig, ax = plt.subplots(figsize=(10,5))sns.set_style('white')ax=sns.barplot(x='country', y='total_litres_of_pure_alcohol', data=top5_alcohol, palette=colors)plt.title('TOP5 countries by pure alcohol consumption', fontsize=25)plt.xlabel(None)plt.xticks(fontsize=16)plt.ylabel('Litres per person', fontsize=20)plt.yticks(fontsize=15)ax.text(x=2.5, y=12.3, s='the highest \nspirit servings', color='red', size=17, weight='bold')sns.despine(bottom=True)ax.grid(False)ax.tick_params(bottom=False, left=True)plt.show() A small island Caribbean country Grenada is in 4th place by pure alcohol consumption, and among the TOP5 countries, it’s the one with the highest number of strong spirit servings. For our bar plots to reach a wider audience, we should consider using colorblind-friendly colors. There are various online tools (e.g. Stark or Colblindor) for testing how an image looks for different types of color blindness. However, the most common form of it involves differentiating between red and green, so a good approach would be to avoid palettes with both of them. Another way is to use the Color Blind 10 palette of Tableau. The drawback is that it offers quite a limited choice of colors. Some colors have strong associations with certain categories of phenomena or qualities for the majority of people. For example, fuchsia is widely considered to be a feminine color, traffic light palette is commonly used to distinguish between danger, neutral, and safe zones, the red-blue palette is related to the temperature, etc. Even if you are a convinced nonconformist, who is always against any stereotypes, you’d better follow these unwritten conventions when creating a grouped bar plot, as not to mislead the reader. If there are no particular conventions for our groups in question, a good practice is to try to come up (if possible) with some contextual, but still easy-to-understand decisions. Say, we’re going to create a grouped bar plot of the worldwide population of koalas and foxes in the last 10 years. In this case, we can think of using orange color for foxes and grey for koala, and not vice versa. Let’s return to our TOP5 countries by pure alcohol consumption and check the proportions of drinking beer and wine in each of them. Of course, some types of beer have dark red color (e.g. the cherry’s one) and some wines — golden color (white or plum wine). Despite that, the most intuitively comprehensible color associations for these drink types are dark red for wine and golden for beer: fig, ax = plt.subplots(figsize=(10,5))x = np.arange(len(top5_alcohol))width = 0.4plt.bar(x-0.2, top5_alcohol['wine_servings'], width, color='tab:red', label='wine') plt.bar(x+0.2, top5_alcohol['beer_servings'], width, color='gold', label='beer')plt.title('TOP5 countries by pure alcohol consumption', fontsize=25)plt.xlabel(None)plt.xticks(top5_alcohol.index, top5_alcohol['country'], fontsize=17)plt.ylabel('Servings per person', fontsize=20)plt.yticks(fontsize=17)sns.despine(bottom=True)ax.grid(False)ax.tick_params(bottom=False, left=True)plt.legend(frameon=False, fontsize=15)plt.show() Now we can easily capture that in France people drink much more wine than beer, while in Lithuania and Grenada — vice versa. In Andorra, both drinks are rather popular, with wine slightly dominating. Even though a vertical bar plot is usually a default one, sometimes a horizontal version is preferred: for plotting nominal variables, when x-tick labels are too long, and rotating them would help to avoid overlapping, but decrease readability, when we have a large number of categories (bars). In the last case, horizontal bar plots are especially advantageous for viewing the graph from a narrow screen of a mobile phone. A vertical bar plot, instead, is more suitable for plotting ordinal variables or time series. For example, we can use it to plot the overall biomass on Earth by geological period, or the number of UFO sightings by month, etc. Since the country column represents a nominal variable, and the names of some countries are rather long, let's select many categories (the TOP20 countries by beer consumption per person) and see the horizontal bar plot in action: top20_beer = df.sort_values('beer_servings', ascending=False)[:20]fig, ax = plt.subplots(figsize=(40,18))fig.tight_layout(pad=5)# Creating a case-specific function to avoid code repetitiondef plot_hor_vs_vert(subplot, x, y, xlabel, ylabel, rotation, tick_bottom, tick_left): ax=plt.subplot(1,2,subplot) sns.barplot(x, y, data=top20_beer, color='slateblue') plt.title('TOP20 countries \nby beer consumption', fontsize=85) plt.xlabel(xlabel, fontsize=60) plt.xticks(fontsize=45, rotation=rotation) plt.ylabel(ylabel, fontsize=60) plt.yticks(fontsize=45) sns.despine(bottom=False, left=True) ax.grid(False) ax.tick_params(bottom=tick_bottom, left=tick_left) return Noneplot_hor_vs_vert(1, x='country', y='beer_servings', xlabel=None, ylabel='Servings per person', rotation=90, tick_bottom=False, tick_left=True)plot_hor_vs_vert(2, x='beer_servings', y='country', xlabel='Servings per person', ylabel=None, rotation=None, tick_bottom=True, tick_left=False) plt.show() Having all the words flipped horizontally (including the label of the measured value axis) makes the second graph significantly more readable. This list is opened by Namibia, followed by the Czech Republic. We don’t see anymore the countries with the highest alcohol consumption except for Lithuania, which has dropped to 5th place. It seems that their high positions in the previous rating were explained by drinking spirit and wine rather than beer. If we extract all the countries where people drink wine more than average and then visualize this data as a bar plot, the resulting bars will be ordered by the underlying categories (countries) in alphabetical order. Most probably, though, in this case, we’re more interested in seeing this data ordered by the number of wine servings per person. Let’s compare both approaches: wine_more_than_mean = (df[df['wine_servings'] > df['wine_servings']\ .mean()])sort_wine_more_than_mean = wine_more_than_mean\ .sort_values('wine_servings', ascending=False)fig, ax = plt.subplots(figsize=(30,30))fig.tight_layout(pad=5)# Creating a case-specific function to avoid code repetitiondef plot_hor_bar(subplot, data): plt.subplot(1,2,subplot) ax = sns.barplot(y='country', x='wine_servings', data=data, color='slateblue') plt.title('Countries drinking wine \nmore than average', fontsize=70) plt.xlabel('Servings per person', fontsize=50) plt.xticks(fontsize=40) plt.ylabel(None) plt.yticks(fontsize=40) sns.despine(left=True) ax.grid(False) ax.tick_params(bottom=True, left=False) return Noneplot_hor_bar(1, wine_more_than_mean)plot_hor_bar(2, sort_wine_more_than_mean)plt.show() In the first plot, we can somehow distinguish the first and the last 3 countries by wine servings per person (referring only to those where people drink wine more than average), then the things become excessively complicated. In the second plot, we can easily trace the whole country rating. For obtaining a more realistic picture, we should take into account the population of each country (certainly, it’s not exactly correct to compare Russian Federation with the Cook Islands and St. Lucia) and, probably, exclude abstainers. However, the point here is that we should always consider ordering the data before plotting it if we want to get the maximum information from our visualization. It doesn’t obligatory have to be an ordering by values: instead, we can decide to rank the data by categories themselves (if they are ordinal, like age ranges), or there could be whatever other logic behind it, if necessary. While other types of plots don’t have to, bar plots do always have to start at zero. The reason behind it is that a bar plot is supposed to show the magnitude of each data point and the proportions between all the data points, instead of just a change of a variable, as it happens in line plots. If we truncate the y-axis (or the x-axis, in case of a horizontal bar plot) starting it at a value other than 0, we cut also the length of each bar, so our graph doesn’t display correctly anymore neither individual values for each category nor the ratios between them: usa = df[df['country']=='USA'].transpose()[1:4].reset_index()usa.columns = ['drinks', 'servings']fig = plt.figure(figsize=(16,6))fig.tight_layout(pad=5)# Creating a case-specific function to avoid code repetitiondef plot_vert_bar(subplot, y_min): plt.subplot(1,2,subplot) ax = sns.barplot(x='drinks', y='servings', data=usa, color='slateblue') plt.title('Drink consumption in the USA', fontsize=30) plt.xlabel(None) plt.xticks(usa.index, ['Beer', 'Spirit', 'Wine'], fontsize=25) plt.ylabel('Servings per person', fontsize=25) plt.yticks(fontsize=17) plt.ylim(y_min, None) sns.despine(bottom=True) ax.grid(False) ax.tick_params(bottom=False, left=True) return None plot_vert_bar(1, y_min=80)plot_vert_bar(2, y_min=None)plt.show() The plot on the left gives us a misleading impression that the consumption of wine in the USA is around 15 times lower than that of spirit, which, in turn, is less than half of that of beer. On the right plot, we see completely different proportions, which are the correct ones. Creating a grouped bar plot, it’s important to mind the distances between the bars, which are considered to be grouped properly when the gaps between bars inside each group are smaller (up to 0) than those between the bars of adjacent groups. Back to the TOP5 countries by pure alcohol consumption, let’s now check the proportions of drinking spirit and wine in each of them: top5_alcohol_rev = top5_alcohol\ .sort_values('total_litres_of_pure_alcohol')\ .reset_index(drop=True)fig, ax = plt.subplots(figsize=(20,9))fig.tight_layout(pad=5)# Creating a case-specific function to avoid code repetitiondef plot_grouped_bar(subplot, width, gap): plt.subplot(1,2,subplot) x = np.arange(len(top5_alcohol_rev['wine_servings'])) plt.barh(x, top5_alcohol_rev['wine_servings'], width, color='tab:red', label='wine') plt.barh(x+width+gap, top5_alcohol_rev['spirit_servings'], width, color='aqua', label='spirit') plt.yticks(x+width/2, top5_alcohol_rev['country'], fontsize=28) plt.title('TOP5 countries \nby pure alcohol consumption', fontsize=40) plt.xlabel('Servings per person', fontsize=30) plt.xticks(fontsize=22) sns.despine(left=True) plt.tick_params(bottom=True, left=False) ax.grid(False) plt.legend(loc='right', frameon=False, fontsize=23) return Noneplot_grouped_bar(1, width=0.4, gap=0.1)plot_grouped_bar(2, width=0.3, gap=0)plt.show() From the graph on the left, it’s difficult to immediately distinguish the boundaries between adjacent groups, since the distances between the bars inside each group and between the groups are equal. The graph on the right, instead, clearly displays to which country each bar is related. We see now that people in Grenada, Belarus, and Lithuania prefer much more spirit than wine, while in France and Andorra — just the opposite. Choosing between a stacked and a grouped bar plots, we should consider the main message of our visualization: If we’re mostly interested in the overall values across several categories, and, as a secondary goal, we’d like to roughly estimate which of the components contributes most of all in the biggest or smallest total values, the best choice would be a stacked bar plot. However, the issue here is that it can be rather difficult to figure out the trends of its individual elements apart from the first one (i.e. the lowermost in a vertically stacked bar plot or the leftmost in a horizontal). It especially counts in a situation when we have a lot of bars, and sometimes, we can even get a deceiving impression and come to a wrong conclusion. If we want to trace the trends of each individual component across the categories, we’d better use a grouped bar plot. Evidently, in this case, we can say nothing about the total values by category. Let’s apply stacked and grouped bar plots to the Baltic countries, to find out their drinking preferences: baltics = df[(df['country']=='Latvia')|(df['country']=='Lithuania')\ |(df['country']=='Estonia')].iloc[:,:4]baltics.columns = ['country', 'beer', 'spirit', 'wine']baltics.reset_index(drop=True, inplace=True)labels = baltics['country'].tolist()beer = np.array(baltics['beer'])spirit = np.array(baltics['spirit'])wine = np.array(baltics['wine'])fig, ax = plt.subplots(figsize=(16,7))fig.tight_layout(pad=5)# Creating a case-specific function to avoid code repetitiondef plot_stacked_grouped(subplot, shift, width, bot1, bot2): x = np.arange(len(baltics)) plt.subplot(1,2,subplot) plt.bar(x-shift, beer, width, label='beer', color='gold') plt.bar(x, spirit, width, bottom=bot1, label='spirit', color='aqua') plt.bar(x+shift, wine, width, bottom=bot2, label='wine', color='tab:red') plt.title('Drink consumption \nin Baltic countries', fontsize=35) plt.xlabel(None) plt.xticks(baltics.index, labels, fontsize=25) plt.ylabel('Servings per person', fontsize=27) plt.yticks(fontsize=20) sns.despine(bottom=True) plt.tick_params(bottom=False, left=True) plt.legend(frameon=False, fontsize=17) return Noneplot_stacked_grouped(1, shift=0, width=0.35, bot1=beer, bot2=beer+spirit)plot_stacked_grouped(2, shift=0.2, width=0.2, bot1=0, bot2=0)plt.show() From the stacked plot above we see that of all the 3 Baltic countries, Lithuania shows the highest level of alcohol consumption, while Estonia — the lowest. The main contribution in both cases comes from beer. About the consumption of spirit and wine in these countries, we can say nothing precise from this plot. Indeed, the amounts seem equal. The grouped plot clearly shows that Lithuania leads also in drinking spirit, while Estonia again shows the lowest level. The difference for this type of drink is not so evident, though, as it was for the beer. As for the wine, the difference is even less noticeable, but it seems that in Latvia the wine consumption is the highest, while in Lithuania — the lowest. From this plot, however, it’s already more difficult to guess the overall alcohol consumption in these countries. We’d have to do some mental arithmetics for it, and in the case of more than 3 bar groups, this task would become impracticable. As we saw, bar plots are not as banal as they could seem. Before creating a meaningful visualization and obtaining the correct insights from it, we have to consider many details, including our goal, our target audience, what can be the most important takeaway from our graph, how to emphasize it while displaying also additional helpful information, and how to exclude the features that are completely useless for our storytelling. Thanks for reading, and za zdorovie! 😉🥂 If you liked this article, you can also find interesting the following ones:
[ { "code": null, "e": 515, "s": 47, "text": "Being one of the most common visualization types, a bar plot is technically very easy to create: we need to write just one short line of code. However, if we want to create a really informative, easily readable graph efficiently revealing the story behind ...
Write Clean Python Code Using Pipes | by Khuyen Tran | Towards Data Science
map and filter are two efficient Python methods to work with iterables. However, the code can look messy if you use both map and filter at the same time. Wouldn’t be nice if you can use pipes | to apply multiple methods on an iterable like below? The library Pipe allows you to do exactly that. Pipe is a Python library that enables you to use pipes in Python. A pipe (|) passes the results of one method to another method. I like Pipe because it makes my code look cleaner when applying multiple methods to a Python iterable. Since Pipe only provides a few methods, it is also very easy to learn Pipe. In this article, I will show you some methods I found the most useful. To install Pipe, type: pip install pipe Similar to SQL, Pipe’s where method can also be used to filter elements in an iterable. The select method is similar to the map method. select applies a method to each element of an iterable. In the code below, I use select to multiply each element in the list by 2. Now, you might wonder: Why do we need the methods where and select if they have the same functionalities as map and filter ? It is because you can insert one method after another method using pipes. As a result, using pipes removes nested parentheses and makes the code more readable. It can be a pain to work with a nested iterable. Luckily, you can use chain to chain a sequence of iterables. Even though the iterable is less nested after applying chain, we still have a nested list. To deal with a deeply nested list, we can use traverse instead. The traverse method can be used to recursively unfold iterables. Thus, you can use this method to turn a deeply nested list into a flat list. Let’s integrate this method with the select method to get the values of a dictionary and flatten the list. Pretty cool! Sometimes, it might be useful to group elements in a list using a certain function. That could be easily done with the groupby method. To see how this method works, let’s turn a list of numbers into a dictionary that groups numbers based on whether they are even or odd. In the code above, we use groupby to group numbers into theEven group and theOdd group. The output after applying this method looks like the below: [('Even', <itertools._grouper at 0x7fbea8030550>), ('Odd', <itertools._grouper at 0x7fbea80309a0>)] Next, we use select to turn a list of tuples into a list of dictionaries whose keys are the first elements in the tuples and values are the second elements in the tuples. [{'Even': [2, 4, 6, 8]}, {'Odd': [1, 3, 5, 7, 9]}] Cool! To get only the values that are greater than 2, we can add the where method inside the select method: Note that there are no longer 2 and 1 in the outputs. The dedup method removes duplicates in a list. That might not sound interesting since the set method can do the same thing. However, this method is more flexible since it enables you to get unique elements using a key. For example, you can use this method to get a unique element that is smaller than 5 and another unique element that is larger than or equal to 5. Now, let’s combine this method with select and where to get the values of a dictionary that has duplicated keys and None values. In the code above, we: remove items with the same name get the values of count only choose the values that are integers. Within a few lines of code, we can apply multiple methods to an iterable while still keeping the code clean. Pretty cool, isn’t it? Congratulations! You have just learned how to use pipe to keep your code clean and short. I hope this article will give you the knowledge to turn complicated operations on an iterable into one simple line of code. Feel free to play and fork the source code of this article here: github.com I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter. Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
[ { "code": null, "e": 201, "s": 47, "text": "map and filter are two efficient Python methods to work with iterables. However, the code can look messy if you use both map and filter at the same time." }, { "code": null, "e": 294, "s": 201, "text": "Wouldn’t be nice if you can use p...
How to detect the user's device using jQuery ? - GeeksforGeeks
24 Jun, 2019 The task is to determine the user’s device, whether it is iPad or not, using JQuery. Below are the required methods: Navigator userAgent Property:This property returns the value of the header of user-agent which is sent by the browser to the server.Returned value, have information like name, version, and platform of the browser.Syntax:navigator.userAgent Return value:It returns a string, which represents the user agent string of the current browser. Syntax: navigator.userAgent Return value:It returns a string, which represents the user agent string of the current browser. Example: This example uses the navigator.userAgent property to identify the user’s device. <!DOCTYPE HTML><html> <head> <title> JQuery | Detect iPad users. </title></head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 17px; font-weight: bold;"> </p> <button> click here </button> <p id="GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script> $('#GFG_UP').text( "Click on the button to see "+ "whether user's device is iPad or not"); $('button').on('click', function() { var is_iPad = navigator.userAgent.match(/iPad/i) != null; $('#GFG_DOWN').text(is_iPad); }); </script></body> </html> Output: Before reaching the bottom: After reaching the bottom: jQuery-Misc JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples How to get the value in an input text box using jQuery ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26979, "s": 26951, "text": "\n24 Jun, 2019" }, { "code": null, "e": 27096, "s": 26979, "text": "The task is to determine the user’s device, whether it is iPad or not, using JQuery. Below are the required methods:" }, { "code": null, "e": 27433, ...
Python - Group Adjacent Coordinates - GeeksforGeeks
11 Jun, 2021 Sometimes, while working with Python lists, we can have a problem in which we need to perform the grouping of all the coordinates which occur adjacent on a matrix, i.e horizontally and vertically at distance 1. This is called Manhatten distance. This kind of problem can occur in competitive programming domain. Let’s discuss certain way in which this task can be performed. Input : test_list = [(4, 4), (6, 4), (7, 8)] Output : [[(7, 8)], [(6, 4)], [(4, 4)]]Input : test_list = [(4, 4), (5, 4)] Output : [[(5, 4), (4, 4)]] Method : Using product() + groupby() + list comprehension The combination of above methods can be used to solve this problem. In this, we perform the task of grouping of elements using groupby() and check for pairs using product(). The logic driving this solution is similar to union find algorithm. Python3 # Python3 code to demonstrate working of# Group Adjacent Coordinates# Using product() + groupby() + list comprehensionfrom itertools import groupby, product def Manhattan(tup1, tup2): return abs(tup1[0] - tup2[0]) + abs(tup1[1] - tup2[1]) # initializing listtest_list = [(4, 4), (6, 4), (7, 8), (11, 11), (7, 7), (11, 12), (5, 4)] # printing original listprint("The original list is : " + str(test_list)) # Group Adjacent Coordinates# Using product() + groupby() + list comprehensionman_tups = [sorted(sub) for sub in product(test_list, repeat = 2) if Manhattan(*sub) == 1] res_dict = {ele: {ele} for ele in test_list}for tup1, tup2 in man_tups: res_dict[tup1] |= res_dict[tup2] res_dict[tup2] = res_dict[tup1] res = [[*next(val)] for key, val in groupby( sorted(res_dict.values(), key = id), id)] # printing resultprint("The grouped elements : " + str(res)) The original list is : [(4, 4), (6, 4), (7, 8), (11, 11), (7, 7), (11, 12), (5, 4)] The grouped elements : [[(6, 4), (5, 4), (4, 4)], [(7, 8), (7, 7)], [(11, 12), (11, 11)]] anikakapoor Python list-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? 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 Jun, 2021" }, { "code": null, "e": 25913, "s": 25537, "text": "Sometimes, while working with Python lists, we can have a problem in which we need to perform the grouping of all the coordinates which occur adjacent on a matrix,...
users command in Linux with Examples - GeeksforGeeks
22 Apr, 2021 users command in Linux system is used to show the user names of users currently logged in to the current host. It will display who is currently logged in according to FILE. If the FILE is not specified, use /var/run/utmp. /var/log/wtmp as FILE is common. Syntax: users [OPTION]... [FILE] Example: users command without any option will print the users currently logged in. Options: users –help: This option will display the help message and exit. users --help users –version: This option will show the version information and exit. users --version simmytarika5 linux-command Linux-system-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C curl command in Linux with Examples Conditional Statements | Shell Script UDP Server-Client implementation in C Tail command in Linux with examples Cat command in Linux with examples touch command in Linux with Examples echo command in Linux with Examples Compiling with g++ scp command in Linux with Examples
[ { "code": null, "e": 25273, "s": 25245, "text": "\n22 Apr, 2021" }, { "code": null, "e": 25529, "s": 25273, "text": "users command in Linux system is used to show the user names of users currently logged in to the current host. It will display who is currently logged in according...
Python | Check if string ends with any string in given list - GeeksforGeeks
29 May, 2019 While working with strings, their prefixes and suffix play an important role in making any decision. For data manipulation tasks, we may need to sometimes, check if a string ends with any of the matching strings. Let’s discuss certain ways in which this task can be performed. Method #1 : Using filter() + endswith() The combination of the above function can help to perform this particular task. The filter method is used to check for each word and endswith method tests for the suffix logic at target list. # Python3 code to demonstrate# Checking for string match suffix# using filter() + endswith() # initializing string test_string = "GfG is best" # initializing suffix listsuff_list = ['best', 'iss', 'good'] # printing original string print("The original string : " + str(test_string)) # using filter() + endswith()# Checking for string match suffixres = list(filter(test_string.endswith, suff_list)) != [] # print resultprint("Does string end with any suffix list sublist ? : " + str(res)) The original string : GfG is best Does string end with any suffix list sublist ? : True Method #2 : Using endswith() As an improvement to the above method, it is not always necessary to include filter method for comparison. This task can be handled solely by supplying a suffix check list as an argument to endswith method as well. # Python3 code to demonstrate# Checking for string match suffix# using endswith() # initializing string test_string = "GfG is best" # initializing suffix listsuff_list = ['best', 'iss', 'good'] # printing original string print("The original string : " + str(test_string)) # using endswith()# Checking for string match suffixres = test_string.endswith(tuple(suff_list)) # print resultprint("Does string end with any suffix list sublist ? : " + str(res)) The original string : GfG is best Does string end with any suffix list sublist ? : True Python string-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? 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": "\n29 May, 2019" }, { "code": null, "e": 25814, "s": 25537, "text": "While working with strings, their prefixes and suffix play an important role in making any decision. For data manipulation tasks, we may need to sometimes, check i...
Print all possible rotations of a given Array - GeeksforGeeks
14 Apr, 2021 Given an integer array arr[] of size N, the task is to print all possible rotations of the array.Examples: Input: arr[] = {1, 2, 3, 4} Output: {1, 2, 3, 4}, {4, 1, 2, 3}, {3, 4, 1, 2}, {2, 3, 4, 1} Explaination: Initial arr[] = {1, 2, 3, 4} After first rotation arr[] = {4, 1, 2, 3} After second rotation arr[] = {3, 4, 1, 2} After third rotation arr[] = {2, 3, 4, 1} After fourth rotation, arr[] returns to its original form.Input: arr[] = [1] Output: [1] Approach: Follow the steps below to solve the problem: Generate all possible rotations of the array, by performing a left rotation of the array one by one.Print all possible rotations of the array until the same rotation of array is encountered. Generate all possible rotations of the array, by performing a left rotation of the array one by one. Print all possible rotations of the array until the same rotation of array is encountered. Below is the implementation of the above approach : C++ Java Python C# Javascript // C++ program to print// all possible rotations// of the given array#include <iostream>using namespace std; // Global declaration of arrayint arr[10000]; // Function to reverse array// between indices s and evoid reverse(int arr[], int s, int e){ while(s < e) { int tem = arr[s]; arr[s] = arr[e]; arr[e] = tem; s = s + 1; e = e - 1; }} // Function to generate all// possible rotations of arrayvoid fun(int arr[], int k){ int n = 4 - 1; int v = n - k; if (v >= 0) { reverse(arr, 0, v); reverse(arr, v + 1, n); reverse(arr, 0, n); }} // Driver codeint main(){ arr[0] = 1; arr[1] = 2; arr[2] = 3; arr[3] = 4; for(int i = 0; i < 4; i++) { fun(arr, i); cout << ("["); for(int j = 0; j < 4; j++) { cout << (arr[j]) << ", "; } cout << ("]"); }} // This code is contributed by Princi Singh // Java program to print// all possible rotations// of the given arrayclass GFG{ // Global declaration of arraystatic int arr[] = new int[10000]; // Function to reverse array// between indices s and epublic static void reverse(int arr[], int s, int e){ while(s < e) { int tem = arr[s]; arr[s] = arr[e]; arr[e] = tem; s = s + 1; e = e - 1; }} // Function to generate all// possible rotations of arraypublic static void fun(int arr[], int k){ int n = 4 - 1; int v = n - k; if (v >= 0) { reverse(arr, 0, v); reverse(arr, v + 1, n); reverse(arr, 0, n); }} // Driver codepublic static void main(String args[]){ arr[0] = 1; arr[1] = 2; arr[2] = 3; arr[3] = 4; for(int i = 0; i < 4; i++) { fun(arr, i); System.out.print("["); for(int j = 0; j < 4; j++) { System.out.print(arr[j] + ", "); } System.out.print("]"); }}} // This code is contributed by gk74533 # Python program to print# all possible rotations# of the given array # Function to reverse array# between indices s and edef reverse(arr, s, e): while s < e: tem = arr[s] arr[s] = arr[e] arr[e] = tem s = s + 1 e = e - 1# Function to generate all# possible rotations of arraydef fun(arr, k): n = len(arr)-1 # k = k % n v = n - k if v>= 0: reverse(arr, 0, v) reverse(arr, v + 1, n) reverse(arr, 0, n) return arr# Driver Codearr = [1, 2, 3, 4]for i in range(0, len(arr)): count = 0 p = fun(arr, i) print(p, end =" ") // C# program to print// all possible rotations// of the given arrayusing System;class GFG{ // Global declaration of arraystatic int []arr = new int[10000]; // Function to reverse array// between indices s and epublic static void reverse(int []arr, int s, int e){ while(s < e) { int tem = arr[s]; arr[s] = arr[e]; arr[e] = tem; s = s + 1; e = e - 1; }} // Function to generate all// possible rotations of arraypublic static void fun(int []arr, int k){ int n = 4 - 1; int v = n - k; if (v >= 0) { reverse(arr, 0, v); reverse(arr, v + 1, n); reverse(arr, 0, n); }} // Driver codepublic static void Main(String []args){ arr[0] = 1; arr[1] = 2; arr[2] = 3; arr[3] = 4; for(int i = 0; i < 4; i++) { fun(arr, i); Console.Write("["); for(int j = 0; j < 4; j++) { Console.Write(arr[j] + ", "); } Console.Write("]"); }}} // This code is contributed by Rajput-Ji <script> // javascript program to print// all possible rotations// of the given array // Global declaration of arrayarr = Array.from({length: 10000}, (_, i) => 0); // Function to reverse array// between indices s and efunction reverse(arr, s , e){ while(s < e) { var tem = arr[s]; arr[s] = arr[e]; arr[e] = tem; s = s + 1; e = e - 1; }} // Function to generate all// possible rotations of arrayfunction fun(arr , k){ var n = 4 - 1; var v = n - k; if (v >= 0) { reverse(arr, 0, v); reverse(arr, v + 1, n); reverse(arr, 0, n); }} // Driver code arr[0] = 1; arr[1] = 2; arr[2] = 3; arr[3] = 4; for(i = 0; i < 4; i++) { fun(arr, i); document.write("["); for(j = 0; j < 4; j++) { document.write(arr[j] + ", "); } document.write("]<br>"); } // This code is contributed by 29AjayKumar</script> [1, 2, 3, 4] [4, 1, 2, 3] [2, 3, 4, 1] [3, 4, 1, 2] Time Complexity: O (N2) Auxiliary Space: O (1) gk74533 Rajput-Ji princi singh 29AjayKumar rotation Arrays School Programming Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Python Dictionary Inheritance in C++ Reverse a string in Java C++ Classes and Objects Interfaces in Java
[ { "code": null, "e": 26767, "s": 26739, "text": "\n14 Apr, 2021" }, { "code": null, "e": 26875, "s": 26767, "text": "Given an integer array arr[] of size N, the task is to print all possible rotations of the array.Examples: " }, { "code": null, "e": 27226, "s": 26...
HashSet remove() Method in Java - GeeksforGeeks
05 Oct, 2021 HashSet remove() method is used to remove a particular element from a HashSet. Note that it is only after JDK version 1.2 and ahead, and will throw compilation errors before in version JDK 1 and JDK1.1. Note: This method returns true if the specified element is present in the HashSet otherwise it returns boolean false. Syntax: HashSet.remove(Object O) Parameters: The parameter O is of the type of HashSet and specifies the element to be removed from the HashSet. Return Value: Boolean true and false Example 1: Java // Java code to illustrate// HashSet.remove() method// over String Elements // Importing required classesimport java.util.*; // Main class// HashSet demopublic class GFG { // Main driver method public static void main(String args[]) { // Creating an empty HashSet // Declaring object of string type HashSet<String> set = new HashSet<String>(); // Adding custom input elements into the Set // using add() method set.add("Welcome"); set.add("To"); set.add("Geeks"); set.add("For"); set.add("Geeks"); // Displaying the HashSet(object elements) System.out.println("HashSet: " + set); // Removing elements // using remove() method set.remove("Geeks"); set.remove("For"); set.remove("Welcome"); // Now displaying the HashSet after removal // of elements from it System.out.println( "HashSet after removing elements: " + set); }} HashSet: [Geeks, For, Welcome, To] HashSet after removing elements: [To] Example 2: Java // Java code to illustrate remove()// method of Hashset class// over Integer Elements // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating an empty HashSet // Declaring object of integer type HashSet<Integer> set = new HashSet<Integer>(); // Adding custom input elements into the Set // using add() method set.add(5); set.add(3); set.add(1); set.add(4); set.add(3); // Displaying the HashSet(object elements) System.out.println("HashSet: " + set); // Removing elements // using remove() method set.remove(3); set.remove(1); // Now displaying the HashSet after removal // of elements from it System.out.println( "HashSet after removing elements: " + set); }} HashSet: [1, 3, 4, 5] HashSet after removing elements: [4, 5] solankimayank Java - util package Java-Collections Java-Functions java-hashset Java 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 Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25251, "s": 25223, "text": "\n05 Oct, 2021" }, { "code": null, "e": 25455, "s": 25251, "text": "HashSet remove() method is used to remove a particular element from a HashSet. Note that it is only after JDK version 1.2 and ahead, and will throw compilation err...
How to replace HTML element in jQuery ? - GeeksforGeeks
22 Apr, 2021 We can replace HTML elements using the jQuery .replaceWith() method. With the jQuery replaceWith() method, we can replace each element in the set of matched elements with the provided new content and return the set of elements that were removed. The .replaceWith() method removes content from the DOM and inserts new content in its place with a single call. Syntax : replaceWith( newContent ) .replaceWith( function ) Return Value: This method returns the selected element with the change. Note: The jQuery .replaceWith() method, returns the jQuery object so that the other methods can be chained onto it. However, it must be noted that the original jQuery object is returned. This object refers to the element that has been removed from the DOM, not the new element that has replaced it. Example 1: We fetch the element we need to replace and write a new element in place of it. HTML <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").replaceWith ("<div style='width:200px;height:100px;\ background-color:red;text-align:center;\ vertical-align:middle;display:table-cell'>\ <strong>new div</strong></div>"); }); }); </script> </head> <body> <p>Example paragraph.</p> <button style="margin: 20px 0px;"> click to replace </button> </body></html> Output : Example 2: We can also replace an HTML element with another existing HTML element. XML <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").replaceWith($("h1")) }); }); </script> </head> <body> <p>Example paragraph.</p> <button style="margin: 20px 0px;"> click to replace </button> <h1>H1 tag</h1> </body></html> Output : Example 3: We can replace multiple HTML elements at the same time. HTML <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $(".X").replaceWith("<h3>new element</h3>") }); }); </script> </head> <body> <p class="X">Example paragraph.</p> <h1 class="X">Example H1</h1> <div style="width: fit-content; background-color: green; padding: 10px;" class="X"> Example div </div> <button style="margin: 20px 0px;"> click to replace </button> </body></html> Output : jQuery-Methods jQuery-Questions Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples How to get the value in an input text box using jQuery ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26954, "s": 26926, "text": "\n22 Apr, 2021" }, { "code": null, "e": 27200, "s": 26954, "text": "We can replace HTML elements using the jQuery .replaceWith() method. With the jQuery replaceWith() method, we can replace each element in the set of matched elemen...
Basic Database Operations Using C# - GeeksforGeeks
14 Sep, 2021 In this article, you are going to learn about how to perform basic database operations using system.data.SqlClient namespace in C#. The basic operations are INSERT, UPDATE, SELECT and DELETE. Although the target database system is SQL Server Database, the same techniques can be applied to other database systems because the query syntax used is standard SQL that is generally supported by all relational database systems.Prerequisites: Microsoft SQL Server Management StudioOpen Microsoft SQL Server Management Studio and write the below script to create a database and table in it. create database Demodb; use Demodb; CREATE TABLE demo( articleID varchar(30) NOT NULL PRIMARY KEY, articleName varchar(30) NOT NULL, ); insert into demo values(1, 'C#'); insert into demo values(2, 'C++'); After executing the above script following table named demo is created and it contains the following data as shown in the screenshot. Connecting C# with Database: To work with a database, the first of all you required a connection. The connection to a database normally consists of the below-mentioned parameters. Database name or Data Source: The database name to which the connection needs to be set up and connection can be made or you can say only work with one database at a time. Credentials: The username and password which needs to be used to establish a connection to the database. Optional Parameters: For each database type, you can specify optional parameters to provide more information on how .NET should connect to the database to handle the data. Note: Here, we are using command prompt to execute these codes. To see the result, you can use the Microsoft SQL Server Management Studio.Code 1#: Connecting with database in C# csharp // C# code to connect the databaseusing System;using System.Data.SqlClient; namespace Database_Operation { class DBConn { // Main Method static void Main() { Connect(); Console.ReadKey(); } static void Connect() { string constr; // for the connection to // sql server database SqlConnection conn; // Data Source is the name of the // server on which the database is stored. // The Initial Catalog is used to specify // the name of the database // The UserID and Password are the credentials // required to connect to the database. constr = @"Data Source=DESKTOP-GP8F496;Initial Catalog=Demodb;User ID=sa;Password=24518300"; conn = new SqlConnection(constr); // to open the connection conn.Open(); Console.WriteLine("Connection Open!"); // to close the connection conn.Close(); }}} Output: Connection Open ! Code #2: Using Select Statement and SqlDataReader for accessing the data in C# csharp // C# code to demonstrate how// to use select statementusing System;using System.Data.SqlClient; namespace Database_Operation { class SelectStatement{ // Main Method static void Main() { Read(); Console.ReadKey(); } static void Read() { string constr; // for the connection to // sql server database SqlConnection conn; // Data Source is the name of the // server on which the database is stored. // The Initial Catalog is used to specify // the name of the database // The UserID and Password are the credentials // required to connect to the database. constr = @"Data Source=DESKTOP-GP8F496;Initial Catalog=Demodb;User ID=sa;Password=24518300"; conn = new SqlConnection(constr); // to open the connection conn.Open(); // use to perform read and write // operations in the database SqlCommand cmd; // use to read a row in // table one by one SqlDataReader dreader; // to sore SQL command and // the output of SQL command string sql, output = ""; // use to fetch rows from demo table sql = "Select articleID, articleName from demo"; // to execute the sql statement cmd = new SqlCommand(sql, conn); // fetch all the rows // from the demo table dreader = cmd.ExecuteReader(); // for one by one reading row while (dreader.Read()) { output = output + dreader.GetValue(0) + " - " + dreader.GetValue(1) + "\n"; } // to display the output Console.Write(output); // to close all the objects dreader.Close(); cmd.Dispose(); conn.Close(); }}} Output: 1 - C# 2 - C++ Code #3: Inserting the data into the database using Insert Statement in C# csharp // C# code for how to use Insert Statementusing System;using System.Data.SqlClient; namespace Database_Operation { class InsertStatement { // Main Method static void Main() { Insert(); Console.ReadKey(); } static void Insert() { string constr; // for the connection to // sql server database SqlConnection conn; // Data Source is the name of the // server on which the database is stored. // The Initial Catalog is used to specify // the name of the database // The UserID and Password are the credentials // required to connect to the database. constr = @"Data Source=DESKTOP-GP8F496;Initial Catalog=Demodb;User ID=sa;Password=24518300"; conn = new SqlConnection(constr); // to open the connection conn.Open(); // use to perform read and write // operations in the database SqlCommand cmd; // data adapter object is use to // insert, update or delete commands SqlDataAdapter adap = new SqlDataAdapter(); string sql = ""; // use the defined sql statement // against our database sql = "insert into demo values(3, 'Python')"; // use to execute the sql command so we // are passing query and connection object cmd = new SqlCommand(sql, conn); // associate the insert SQL // command to adapter object adap.InsertCommand = new SqlCommand(sql, conn); // use to execute the DML statement against // our database adap.InsertCommand.ExecuteNonQuery(); // closing all the objects cmd.Dispose(); conn.Close(); }}} Output: Code #4: Updating the data into the database using Update Statement in C# csharp // C# code for how to use Update Statementusing System;using System.Data.SqlClient; namespace Database_Operation { class UpdateStatement { // Main Method static void Main() { Update(); Console.ReadKey(); } static void Update() { string constr; // for the connection to // sql server database SqlConnection conn; // Data Source is the name of the // server on which the database is stored. // The Initial Catalog is used to specify // the name of the database // The UserID and Password are the credentials // required to connect to the database. constr = @"Data Source=DESKTOP-GP8F496;Initial Catalog=Demodb;User ID=sa;Password=24518300"; conn = new SqlConnection(constr); // to open the connection conn.Open(); // use to perform read and write // operations in the database SqlCommand cmd; // data adapter object is use to // insert, update or delete commands SqlDataAdapter adap = new SqlDataAdapter(); string sql = ""; // use the define sql // statement against our database sql = "update demo set articleName='django' where articleID=3"; // use to execute the sql command so we // are passing query and connection object cmd = new SqlCommand(sql, conn); // associate the insert SQL // command to adapter object adap.InsertCommand = new SqlCommand(sql, conn); // use to execute the DML statement against // our database adap.InsertCommand.ExecuteNonQuery(); // closing all the objects cmd.Dispose(); conn.Close(); }}} Output: Code #5: Deleting the data into the database using Delete Statement in C# csharp // C# code for how to use Delete Statementusing System;using System.Data.SqlClient; namespace Database_Operation { class DeleteStatement { // Main Method static void Main() { Delete(); Console.ReadKey(); } static void Delete() { string constr; // for the connection to // sql server database SqlConnection conn; // Data Source is the name of the // server on which the database is stored. // The Initial Catalog is used to specify // the name of the database // The UserID and Password are the credentials // required to connect to the database. constr = @"Data Source=DESKTOP-GP8F496;Initial Catalog=Demodb;User ID=sa;Password=24518300"; conn = new SqlConnection(constr); // to open the connection conn.Open(); // use to perform read and write // operations in the database SqlCommand cmd; // data adapter object is use to // insert, update or delete commands SqlDataAdapter adap = new SqlDataAdapter(); string sql = ""; // use the define SQL statement // against our database sql = "delete from demo where articleID=3"; // use to execute the sql command so we // are passing query and connection object cmd = new SqlCommand(sql, conn); // associate the insert SQL // command to adapter object adap.InsertCommand = new SqlCommand(sql, conn); // use to execute the DML statement // against our database adap.InsertCommand.ExecuteNonQuery(); // closing all the objects cmd.Dispose(); conn.Close(); }}} Output: rajeev0719singh C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Linked List Implementation in C#
[ { "code": null, "e": 25572, "s": 25544, "text": "\n14 Sep, 2021" }, { "code": null, "e": 26157, "s": 25572, "text": "In this article, you are going to learn about how to perform basic database operations using system.data.SqlClient namespace in C#. The basic operations are INSERT...
How to include a JavaScript file in another JavaScript file ? - GeeksforGeeks
31 Jul, 2019 In native JavaScript before ES6 Modules 2015 has been introduced had no import, include, or require, functionalities. Before that, we can load a JavaScript file into another JavaScript file using a script tag inside the DOM that script will be downloaded and executed immediately. Now after the invention of ES6 modules there are so many different approaches to solve this problem have been developed and discussed below. ES6 Modules: ECMAScript (ES6) modules have been supported in Node.js since v8.5. In this module, we define exported functions in one file and import them in another example.There are two popular way to call a JavaScript file from another function those are listed below: Ajax Techniques Concatenate files Ajax Techniques Example: External JavaScript file named as “main.js”// This alert will export in the main filealert("Hello Geeks") // This alert will export in the main filealert("Hello Geeks") Main file: This file will import the above “main.js” file<!DOCTYPE html><html> <head> <title> Calling JavaScript file from another JavaScript file </title> <script type="text/javascript"> var script = document.createElement('script'); script.src = "https://media.geeksforgeeks.org/wp-content/uploads/20190704153043/main.js"; document.head.appendChild(script) </script></head> <body></body> </html> <!DOCTYPE html><html> <head> <title> Calling JavaScript file from another JavaScript file </title> <script type="text/javascript"> var script = document.createElement('script'); script.src = "https://media.geeksforgeeks.org/wp-content/uploads/20190704153043/main.js"; document.head.appendChild(script) </script></head> <body></body> </html> Output: Concatenate files Example: Here importing multiple JavaScript files into a single JavaScript file and calling that master JavaScript file from a function. External JavaScript file named as “main.js”// This alert will export in the main filealert("Hello Geeks") // This alert will export in the main filealert("Hello Geeks") External JavaScript file “second.js”// This alert will export in the main filealert("Welcome to Geeksforgeeks") // This alert will export in the main filealert("Welcome to Geeksforgeeks") External JavaScript file “master.js”function include(file) { var script = document.createElement('script'); script.src = file; script.type = 'text/javascript'; script.defer = true; document.getElementsByTagName('head').item(0).appendChild(script); } /* Include Many js files */include('https://media.geeksforgeeks.org/wp-content/uploads/20190704153043/main.js');include('https://media.geeksforgeeks.org/wp-content/uploads/20190704162640/second.js'); function include(file) { var script = document.createElement('script'); script.src = file; script.type = 'text/javascript'; script.defer = true; document.getElementsByTagName('head').item(0).appendChild(script); } /* Include Many js files */include('https://media.geeksforgeeks.org/wp-content/uploads/20190704153043/main.js');include('https://media.geeksforgeeks.org/wp-content/uploads/20190704162640/second.js'); Main file: This file will import the above “master.js” file<!DOCTYPE html><html> <head> <title> Calling JavaScript file from another JavaScript file </title> <script type="text/javascript"src="https://media.geeksforgeeks.org/wp-content/uploads/20190704162730/master.js"> </script></head> <body></body></html> <!DOCTYPE html><html> <head> <title> Calling JavaScript file from another JavaScript file </title> <script type="text/javascript"src="https://media.geeksforgeeks.org/wp-content/uploads/20190704162730/master.js"> </script></head> <body></body></html> Output:main.js file import:second.js file import: javascript-functions Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 31331, "s": 31303, "text": "\n31 Jul, 2019" }, { "code": null, "e": 31612, "s": 31331, "text": "In native JavaScript before ES6 Modules 2015 has been introduced had no import, include, or require, functionalities. Before that, we can load a JavaScript file in...
Remove All White Space from Character String in R - GeeksforGeeks
23 Aug, 2021 In this article, we are going to see how to remove all the white space from character string in R Programming Language. We can do it in these ways: Using gsub() function. Using str_replace_all() function. gsub() function is used to remove the space by removing the space in the given string. Syntax: gsub(” “, “”, input_string) where First parameter takes the space to check the string has spaceSecond parameter replaces with “No space” if there is space in the stringThird parameter is the input string. First parameter takes the space to check the string has space Second parameter replaces with “No space” if there is space in the string Third parameter is the input string. Example: R program to remove white space from character string using gsub() function. R # consider the stringdata = "Hello Geek welocme to Geeksforgeeks"print("Original String:")print(data) print("After remove white space:") # remove white spacesprint(gsub(" ","",data)) Output: [1] "Original String:" [1] "Hello Geek welocme to Geeksforgeeks" [1] "After remove white space:" [1] "HelloGeekwelocmetoGeeksforgeeks" This function is used to replace white space with empty, It is similar to gsub() function. It is available in stringr package. To install this module type the below command in the terminal. install.packages("stringr") Here we use str_replace_all() function to remove white space in a string. Syntax: str_replace_all(input_string,” “, “”) where First parameter takes the input stringSecond parameter replaces with “No space” if there is space in the stringThird parameter is to check the string has space First parameter takes the input string Second parameter replaces with “No space” if there is space in the string Third parameter is to check the string has space Example: R program to remove white space in the character string R # consider the stringstring="Hello Geek welocme to Geeksforgeeks"print("Original String:")print(string) print("After remove white space:") # remove white spacesprint(str_replace_all(string," ","")) Output: [1] "Original String:" [1] "Hello Geek welocme to Geeksforgeeks" [1] "After remove white space:" [1] "HelloGeekwelocmetoGeeksforgeeks" Picked R String-Programs R-strings 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 Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 26487, "s": 26459, "text": "\n23 Aug, 2021" }, { "code": null, "e": 26607, "s": 26487, "text": "In this article, we are going to see how to remove all the white space from character string in R Programming Language." }, { "code": null, "e": 26635,...
Processing strings using std::istringstream - GeeksforGeeks
28 Jul, 2021 The std::istringstream is a string class object which is used to stream the string into different variables and similarly files can be stream into strings. Objects of this class use a string buffer that contains a sequence of characters. This sequence of characters can be accessed as a string object.Header File: #include <sstream> 1. Streaming integer from a string with std::istringstream One way to stream a string is to use an input string stream object std::istringstream from the header. Once a std::istringstream object has been created, then the string can be streamed and stored using the extraction operator(>>). The extraction operator will read until whitespace is reached or until the stream fails.Below is the illustration of the std::istringstream: CPP // C++ program to illustrate std::istringstream#include <iostream>#include <sstream>#include <string>using std::istringstream;using std::string;using std::cout; // Driver Codeint main(){ // Input string string a("1 2 3"); // Object class of istringstream istringstream my_stream(a); // Variable to store number n int n; // Stream a number till white space // is encountered my_stream >> n; // Print the number cout << n << "\n";} 1 The std::istringstream object can also be used as a boolean to determine if the last extraction operation failed. This happens if there wasn’t any more of the string to the stream, For Example, If the stream still has more characters then we are able to stream the string again. The extraction operator >> writes the stream to the variable on the right of the operator and returns the std::istringstream object, so the entire expression my_stream >> n is a std::istringstream object which returns a boolean i.e., true if stream is possible else return false.Below is the implementation of using the std::istringstream in the above way: Type 1 Type 2 // C++ program to illustrate std::istringstream#include <iostream>#include <sstream>#include <string>using std::istringstream;using std::string;using std::cout; // Driver Codeint main(){ // Input string string a("1 2 3"); // Object class of istringstream istringstream my_stream(a); // Variable to store number n int n; // Testing to see if the stream was // successful and printing results. while (my_stream) { // Streaming until space is // encountered my_stream >> n; // If my_stream is not empty if (my_stream) { cout << "That stream was successful: " << n << "\n"; } // Else print not successful else { cout << "That stream was NOT successful!" << "\n"; } } return 0;} // C++ program to illustrate std::istringstream#include <iostream>#include <sstream>#include <string>using std::istringstream;using std::string;using std::cout; // Driver Codeint main(){ // Input string string a("1 2 3"); // Object class of istringstream istringstream my_stream(a); // Variable to store number n int n; // Testing to see if the stream was // successful and printing results. while (my_stream >> n) { cout << "That stream was successful: " << n << "\n"; } cout << "That stream was NOT successful!" << "\n"; return 0;} That stream was successful: 1 That stream was successful: 2 That stream was successful: 3 That stream was NOT successful! 2. Strings with Mixed Types In the above illustrations, the string contains only whitespaces and characters which could be converted to int. If the string has mixed types i.e., it contains more than one data type in the stream then it can be used as illustrated below.Below is the illustration of the std::istringstream for the mixed types:Program 1: CPP // C++ program to illustrate std::istringstream// when string has integer followed by character#include <iostream>#include <sstream>#include <string>using std::istringstream;using std::string;using std::cout; // Driver Codeint main(){ // Input string string str("1, 2, 3"); // Object class of istringstream istringstream my_stream(str); // Variable to store the number n // and character ch char c; int n; // Traverse till input stream is valid while (my_stream >> n >> c) { cout << "That stream was successful: " << n << " " << c << "\n"; } cout << "The stream has failed." << "\n"; return 0;} That stream was successful: 1, That stream was successful: 2, The stream has failed. Program 2: CPP // C++ program to illustrate std::istringstream// to tokenize the string#include <iostream>#include <sstream>#include <string>using std::istringstream;using std::string;using std::cout; // Driver Codeint main(){ // Input string string str("abc, def, ghi"); // Object class of istringstream istringstream my_stream(str); // To store the stream string string token; size_t pos = -1; // Traverse till stream is valid while (my_stream >> token) { // If ',' is found then tokenize // the string token while ((pos = token.rfind(',')) != std::string::npos) { token.erase(pos, 1); } // Print the tokenize string cout << token << '\n'; }} abc def ghi Reference: http://www.cplusplus.com/reference/sstream/istringstream/ akshaysingh98088 C++ C++ Programs Strings Strings CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) Header files in C/C++ and its uses Program to print ASCII Value of a character C++ Program for QuickSort How to return multiple values from a function in C or C++? Sorting a Map by value in C++ STL
[ { "code": null, "e": 25369, "s": 25341, "text": "\n28 Jul, 2021" }, { "code": null, "e": 25685, "s": 25369, "text": "The std::istringstream is a string class object which is used to stream the string into different variables and similarly files can be stream into strings. Objects...
Heavy Light Decomposition | Set 2 (Implementation) - GeeksforGeeks
27 Jan, 2021 We strongly recommend to refer below post as a prerequisite of this.Heavy Light Decomposition | Set 1 (Introduction)In the above post, we discussed the Heavy-light decomposition (HLD) with the help of below example. Suppose we have an unbalanced tree (not necessarily a Binary Tree) of n nodes, and we have to perform operations on the tree to answer a number of queries, each can be of one of the two types: change(a, b): Update weight of the ath edge to b.maxEdge(a, b): Print the maximum edge weight on the path from node a to node b. For example maxEdge(5, 10) should print 25. change(a, b): Update weight of the ath edge to b. maxEdge(a, b): Print the maximum edge weight on the path from node a to node b. For example maxEdge(5, 10) should print 25. In this article implementation of same is discussedOur line of attack for this problem is: Creating the treeSetting up the subtree size, depth and parent for each node (using a DFS)Decomposing the tree into disjoint chainsBuilding up the segment treeAnswering queries Creating the tree Setting up the subtree size, depth and parent for each node (using a DFS) Decomposing the tree into disjoint chains Building up the segment tree Answering queries 1. Tree Creation: Implementation uses adjacency matrix representation of the tree, for the ease of understanding. One can use adjacency list rep with some changes to the source. If edge number e with weight w exists between nodes u and v, we shall store e at tree[u][v] and tree[v][u], and the weight w in a separate linear array of edge weights (n-1 edges).2. Setting up the subtree size, depth and parent for each node: Next we do a DFS on the tree to set up arrays that store parent, subtree size and depth of each node. Another important thing we do at the time of DFS is storing the deeper node of every edge we traverse. This will help us at the time of updating the tree (change() query) .3 & 4. Decomposing the tree into disjoint chains and Building Segment Tree Now comes the most important part: HLD. As we traverse the edges and reach nodes (starting from the root), we place the edge in the segment tree base, we decide if the node will be a head to a new chain (if it is a normal child) or will the current chain extend (special child), store the chain ID to which the node belongs, and store its place in the segment tree base (for future queries). The base for segment tree is built such that all edges belonging to the same chain are together, and chains are separated by light edges.Illustration: We start at node 1. Since there wasn’t any edge by which we came to this node, we insert ‘-1’ as the imaginary edge’s weight, in the array that will act as base to the segment tree. Next, we move to node 1’s special child, which is node 2, and since we traversed edge with weight 13, we add 13 to our base array. Node 2’s special child is node 6. We traverse edge with weight 25 to reach node 6. We insert in base array. And similarly we extend this chain further while we haven’t reached a leaf node (node 10 in our case). Then we shift to a normal child of parent of the last leaf node, and mark the beginning of a new chain. Parent here is node 8 and normal child is node 11. We traverse edge with weight 6 and insert it into the base array. This is how we complete the base array for the segment tree. Also remember that we need to store the position of every node in segment tree for future queries. Position of node 1 is 1, node 2 is 2, node 6 is 3, node 8 is 4, ..., node 11 is 6, node 5 is 7, node 9 is 10, node 4 is 11 (1-based indexing). 5. Answering queriesWe have discussed mexEdge() query in detail in previous post. For maxEdge(u, v), we find max weight edge on path from u to LCA and v to LCA and return maximum of two.For change() query, we can update the segment tree by using the deeper end of the edge whose weight is to be updated. We will find the position of deeper end of the edge in the array acting as base to the segment tree and then start our update from that node and move upwards updating segment tree. Say we want to update edge 8 (between node 7 and node 9) to 28. Position of deeper node 9 in base array is 10, We do it as follows: Below is C++ implementation of above steps. CPP Java /* C++ program for Heavy-Light Decomposition of a tree */#include<bits/stdc++.h>using namespace std; #define N 1024 int tree[N][N]; // Matrix representing the tree /* a tree node structure. Every node has a parent, depth, subtree size, chain to which it belongs and a position in base array*/struct treeNode{ int par; // Parent of this node int depth; // Depth of this node int size; // Size of subtree rooted with this node int pos_segbase; // Position in segment tree base int chain;} node[N]; /* every Edge has a weight and two ends. We store deeper end */struct Edge{ int weight; // Weight of Edge int deeper_end; // Deeper end} edge[N]; /* we construct one segment tree, on base array */struct segmentTree{ int base_array[N], tree[6*N];} s; // A function to add Edges to the Tree matrix// e is Edge ID, u and v are the two nodes, w is weightvoid addEdge(int e, int u, int v, int w){ /*tree as undirected graph*/ tree[u-1][v-1] = e-1; tree[v-1][u-1] = e-1; edge[e-1].weight = w;} // A recursive function for DFS on the tree// curr is the current node, prev is the parent of curr,// dep is its depthvoid dfs(int curr, int prev, int dep, int n){ /* set parent of current node to predecessor*/ node[curr].par = prev; node[curr].depth = dep; node[curr].size = 1; /* for node's every child */ for (int j=0; j<n; j++) { if (j!=curr && j!=node[curr].par && tree[curr][j]!=-1) { /* set deeper end of the Edge as this child*/ edge[tree[curr][j]].deeper_end = j; /* do a DFS on subtree */ dfs(j, curr, dep+1, n); /* update subtree size */ node[curr].size+=node[j].size; } }} // A recursive function that decomposes the Tree into chainsvoid hld(int curr_node, int id, int *edge_counted, int *curr_chain, int n, int chain_heads[]){ /* if the current chain has no head, this node is the first node * and also chain head */ if (chain_heads[*curr_chain]==-1) chain_heads[*curr_chain] = curr_node; /* set chain ID to which the node belongs */ node[curr_node].chain = *curr_chain; /* set position of node in the array acting as the base to the segment tree */ node[curr_node].pos_segbase = *edge_counted; /* update array which is the base to the segment tree */ s.base_array[(*edge_counted)++] = edge[id].weight; /* Find the special child (child with maximum size) */ int spcl_chld = -1, spcl_edg_id; for (int j=0; j<n; j++) if (j!=curr_node && j!=node[curr_node].par && tree[curr_node][j]!=-1) if (spcl_chld==-1 || node[spcl_chld].size < node[j].size) spcl_chld = j, spcl_edg_id = tree[curr_node][j]; /* if special child found, extend chain */ if (spcl_chld!=-1) hld(spcl_chld, spcl_edg_id, edge_counted, curr_chain, n, chain_heads); /* for every other (normal) child, do HLD on child subtree as separate chain*/ for (int j=0; j<n; j++) { if (j!=curr_node && j!=node[curr_node].par && j!=spcl_chld && tree[curr_node][j]!=-1) { (*curr_chain)++; hld(j, tree[curr_node][j], edge_counted, curr_chain, n, chain_heads); } }} // A recursive function that constructs Segment Tree for array[ss..se).// si is index of current node in segment tree stint construct_ST(int ss, int se, int si){ // If there is one element in array, store it in current node of // segment tree and return if (ss == se-1) { s.tree[si] = s.base_array[ss]; return s.base_array[ss]; } // If there are more than one elements, then recur for left and // right subtrees and store the minimum of two values in this node int mid = (ss + se)/2; s.tree[si] = max(construct_ST(ss, mid, si*2), construct_ST(mid, se, si*2+1)); return s.tree[si];} // A recursive function that updates the Segment Tree// x is the node to be updated to value val// si is the starting index of the segment tree// ss, se mark the corners of the range represented by siint update_ST(int ss, int se, int si, int x, int val){ if(ss > x || se <= x); else if(ss == x && ss == se-1)s.tree[si] = val; else { int mid = (ss + se)/2; s.tree[si] = max(update_ST(ss, mid, si*2, x, val), update_ST(mid, se, si*2+1, x, val)); } return s.tree[si];} // A function to update Edge e's value to val in segment treevoid change(int e, int val, int n){ update_ST(0, n, 1, node[edge[e].deeper_end].pos_segbase, val); // following lines of code make no change to our case as we are // changing in ST above // Edge_weights[e] = val; // segtree_Edges_weights[deeper_end_of_edge[e]] = val;} // A function to get the LCA of nodes u and vint LCA(int u, int v, int n){ /* array for storing path from u to root */ int LCA_aux[n+5]; // Set u is deeper node if it is not if (node[u].depth < node[v].depth) swap(u, v); /* LCA_aux will store path from node u to the root*/ memset(LCA_aux, -1, sizeof(LCA_aux)); while (u!=-1) { LCA_aux[u] = 1; u = node[u].par; } /* find first node common in path from v to root and u to root using LCA_aux */ while (v) { if (LCA_aux[v]==1)break; v = node[v].par; } return v;} /* A recursive function to get the minimum value in a given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */int RMQUtil(int ss, int se, int qs, int qe, int index){ //printf("%d,%d,%d,%d,%d\n", ss, se, qs, qe, index); // If segment of this node is a part of given range, then return // the min of the segment if (qs <= ss && qe >= se-1) return s.tree[index]; // If segment of this node is outside the given range if (se-1 < qs || ss > qe) return -1; // If a part of this segment overlaps with the given range int mid = (ss + se)/2; return max(RMQUtil(ss, mid, qs, qe, 2*index), RMQUtil(mid, se, qs, qe, 2*index+1));} // Return minimum of elements in range from index qs (query start) to// qe (query end). It mainly uses RMQUtil()int RMQ(int qs, int qe, int n){ // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { printf("Invalid Input"); return -1; } return RMQUtil(0, n, qs, qe, 1);} // A function to move from u to v keeping track of the maximum// we move to the surface changing u and chains// until u and v donot belong to the sameint crawl_tree(int u, int v, int n, int chain_heads[]){ int chain_u, chain_v = node[v].chain, ans = 0; while (true) { chain_u = node[u].chain; /* if the two nodes belong to same chain, * we can query between their positions in the array * acting as base to the segment tree. After the RMQ, * we can break out as we have no where further to go */ if (chain_u==chain_v) { if (u==v); //trivial else ans = max(RMQ(node[v].pos_segbase+1, node[u].pos_segbase, n), ans); break; } /* else, we query between node u and head of the chain to which u belongs and later change u to parent of head of the chain to which u belongs indicating change of chain */ else { ans = max(ans, RMQ(node[chain_heads[chain_u]].pos_segbase, node[u].pos_segbase, n)); u = node[chain_heads[chain_u]].par; } } return ans;} // A function for MAX_EDGE queryvoid maxEdge(int u, int v, int n, int chain_heads[]){ int lca = LCA(u, v, n); int ans = max(crawl_tree(u, lca, n, chain_heads), crawl_tree(v, lca, n, chain_heads)); printf("%d\n", ans);} // driver functionint main(){ /* fill adjacency matrix with -1 to indicate no connections */ memset(tree, -1, sizeof(tree)); int n = 11; /* arguments in order: Edge ID, node u, node v, weight w*/ addEdge(1, 1, 2, 13); addEdge(2, 1, 3, 9); addEdge(3, 1, 4, 23); addEdge(4, 2, 5, 4); addEdge(5, 2, 6, 25); addEdge(6, 3, 7, 29); addEdge(7, 6, 8, 5); addEdge(8, 7, 9, 30); addEdge(9, 8, 10, 1); addEdge(10, 8, 11, 6); /* our tree is rooted at node 0 at depth 0 */ int root = 0, parent_of_root=-1, depth_of_root=0; /* a DFS on the tree to set up: * arrays for parent, depth, subtree size for every node; * deeper end of every Edge */ dfs(root, parent_of_root, depth_of_root, n); int chain_heads[N]; /*we have initialized no chain heads */ memset(chain_heads, -1, sizeof(chain_heads)); /* Stores number of edges for construction of segment tree. Initially we haven't traversed any Edges. */ int edge_counted = 0; /* we start with filling the 0th chain */ int curr_chain = 0; /* HLD of tree */ hld(root, n-1, &edge_counted, &curr_chain, n, chain_heads); /* ST of segregated Edges */ construct_ST(0, edge_counted, 1); /* Since indexes are 0 based, node 11 means index 11-1, 8 means 8-1, and so on*/ int u = 11, v = 9; cout << "Max edge between " << u << " and " << v << " is "; maxEdge(u-1, v-1, n, chain_heads); // Change value of edge number 8 (index 8-1) to 28 change(8-1, 28, n); cout << "After Change: max edge between " << u << " and " << v << " is "; maxEdge(u-1, v-1, n, chain_heads); v = 4; cout << "Max edge between " << u << " and " << v << " is "; maxEdge(u-1, v-1, n, chain_heads); // Change value of edge number 5 (index 5-1) to 22 change(5-1, 22, n); cout << "After Change: max edge between " << u << " and " << v << " is "; maxEdge(u-1, v-1, n, chain_heads); return 0;} /* Java program for Heavy-Light Decomposition of a tree */import java.util.*;class GFG{ static final int N = 1024;static int edge_counted;static int curr_chain;static int [][]tree = new int[N][N]; // Matrix representing the tree /* a tree node structure. Every node has a parent, depth, subtree size, chain to which it belongs and a position in base array*/static class treeNode{ int par; // Parent of this node int depth; // Depth of this node int size; // Size of subtree rooted with this node int pos_segbase; // Position in segment tree base int chain;} ;static treeNode node[] = new treeNode[N]; /* every Edge has a weight and two ends. We store deeper end */static class Edge{ int weight; // Weight of Edge int deeper_end; // Deeper end Edge(int weight, int deeper_end) { this.weight = weight; this.deeper_end = deeper_end; }} ;static Edge edge[] = new Edge[N]; /* we conone segment tree, on base array */static class segmentTree{ int []base_array = new int[N]; int []tree = new int[6*N];} ;static segmentTree s = new segmentTree(); // A function to add Edges to the Tree matrix// e is Edge ID, u and v are the two nodes, w is weightstatic void addEdge(int e, int u, int v, int w){ /*tree as undirected graph*/ tree[u - 1][v - 1] = e - 1; tree[v - 1][u - 1] = e - 1; edge[e - 1].weight = w;} // A recursive function for DFS on the tree// curr is the current node, prev is the parent of curr,// dep is its depthstatic void dfs(int curr, int prev, int dep, int n){ /* set parent of current node to predecessor*/ node[curr].par = prev; node[curr].depth = dep; node[curr].size = 1; /* for node's every child */ for (int j = 0; j < n; j++) { if (j != curr && j != node[curr].par && tree[curr][j] != -1) { /* set deeper end of the Edge as this child*/ edge[tree[curr][j]].deeper_end = j; /* do a DFS on subtree */ dfs(j, curr, dep + 1, n); /* update subtree size */ node[curr].size += node[j].size; } }} // A recursive function that decomposes the Tree into chainsstatic void hld(int curr_node, int id, int n, int chain_heads[]){ /* if the current chain has no head, this node is the first node * and also chain head */ if (chain_heads[curr_chain] == -1) chain_heads[curr_chain] = curr_node; /* set chain ID to which the node belongs */ node[curr_node].chain = curr_chain; /* set position of node in the array acting as the base to the segment tree */ node[curr_node].pos_segbase = edge_counted; /* update array which is the base to the segment tree */ s.base_array[(edge_counted)++] = edge[id].weight; /* Find the special child (child with maximum size) */ int spcl_chld = -1, spcl_edg_id = 0; for (int j = 0; j < n; j++) if (j != curr_node && j != node[curr_node].par && tree[curr_node][j] != -1) if (spcl_chld == -1 || node[spcl_chld].size < node[j].size) { spcl_chld = j; spcl_edg_id = tree[curr_node][j]; } /* if special child found, extend chain */ if (spcl_chld != -1) hld(spcl_chld, spcl_edg_id, n, chain_heads); /* for every other (normal) child, do HLD on child subtree as separate chain*/ for (int j = 0; j < n; j++) { if (j != curr_node && j != node[curr_node].par && j != spcl_chld && tree[curr_node][j] != -1) { (curr_chain)++; hld(j, tree[curr_node][j], n, chain_heads); } }} // A recursive function that constructs Segment Tree for array[ss..se).// si is index of current node in segment tree ststatic int construct_ST(int ss, int se, int si){ // If there is one element in array, store it in current node of // segment tree and return if (ss == se - 1) { s.tree[si] = s.base_array[ss]; return s.base_array[ss]; } // If there are more than one elements, then recur for left and // right subtrees and store the minimum of two values in this node int mid = (ss + se) / 2; s.tree[si] = Math.max(construct_ST(ss, mid, si * 2), construct_ST(mid, se, si * 2 + 1)); return s.tree[si];} // A recursive function that updates the Segment Tree// x is the node to be updated to value val// si is the starting index of the segment tree// ss, se mark the corners of the range represented by sistatic int update_ST(int ss, int se, int si, int x, int val){ if(ss > x || se <= x); else if(ss == x && ss == se - 1)s.tree[si] = val; else { int mid = (ss + se) / 2; s.tree[si] = Math.max(update_ST(ss, mid, si * 2, x, val), update_ST(mid, se, si * 2 + 1, x, val)); } return s.tree[si];} // A function to update Edge e's value to val in segment treestatic void change(int e, int val, int n){ update_ST(0, n, 1, node[edge[e].deeper_end].pos_segbase, val); // following lines of code make no change to our case as we are // changing in ST above // Edge_weights[e] = val; // segtree_Edges_weights[deeper_end_of_edge[e]] = val;} // A function to get the LCA of nodes u and vstatic int LCA(int u, int v, int n){ /* array for storing path from u to root */ int []LCA_aux= new int[n + 5]; // Set u is deeper node if it is not if (node[u].depth < node[v].depth) { int t = u; u = v; v = t; } /* LCA_aux will store path from node u to the root*/ Arrays.fill(LCA_aux, -1); while (u != -1) { LCA_aux[u] = 1; u = node[u].par; } /* find first node common in path from v to root and u to root using LCA_aux */ while (v > 0) { if (LCA_aux[v] == 1)break; v = node[v].par; } return v;} /* A recursive function to get the minimum value in a given range of array indexes. The following are parameters for this function. st -. Pointer to segment tree index -. Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se -. Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe -. Starting and ending indexes of query range */static int RMQUtil(int ss, int se, int qs, int qe, int index){ //System.out.printf("%d,%d,%d,%d,%d\n", ss, se, qs, qe, index); // If segment of this node is a part of given range, then return // the min of the segment if (qs <= ss && qe >= se - 1) return s.tree[index]; // If segment of this node is outside the given range if (se - 1 < qs || ss > qe) return -1; // If a part of this segment overlaps with the given range int mid = (ss + se)/2; return Math.max(RMQUtil(ss, mid, qs, qe, 2 * index), RMQUtil(mid, se, qs, qe, 2 * index + 1));} // Return minimum of elements in range from index qs (query start) to// qe (query end). It mainly uses RMQUtil()static int RMQ(int qs, int qe, int n){ // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { System.out.printf("Invalid Input"); return -1; } return RMQUtil(0, n, qs, qe, 1);} // A function to move from u to v keeping track of the maximum// we move to the surface changing u and chains// until u and v donot belong to the samestatic int crawl_tree(int u, int v, int n, int chain_heads[]){ int chain_u, chain_v = node[v].chain, ans = 0; while (true) { chain_u = node[u].chain; /* if the two nodes belong to same chain, * we can query between their positions in the array * acting as base to the segment tree. After the RMQ, * we can break out as we have no where further to go */ if (chain_u == chain_v) { if (u == v); //trivial else ans = Math.max(RMQ(node[v].pos_segbase + 1, node[u].pos_segbase, n), ans); break; } /* else, we query between node u and head of the chain to which u belongs and later change u to parent of head of the chain to which u belongs indicating change of chain */ else { ans = Math.max(ans, RMQ(node[chain_heads[chain_u]].pos_segbase, node[u].pos_segbase, n)); u = node[chain_heads[chain_u]].par; } } return ans;} // A function for MAX_EDGE querystatic void maxEdge(int u, int v, int n, int chain_heads[]){ int lca = LCA(u, v, n); int ans = Math.max(crawl_tree(u, lca, n, chain_heads), crawl_tree(v, lca, n, chain_heads)); System.out.printf("%d\n", ans);} // driver functionpublic static void main(String[] args){ /* fill adjacency matrix with -1 to indicate no connections */ for(int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { tree[i][j] = -1; } } int n = 11;for(int i = 0; i < edge.length; i++){ edge[i] = new Edge(0, 0);} for(int i = 0; i < node.length; i++){ node[i] = new treeNode();} /* arguments in order: Edge ID, node u, node v, weight w*/ addEdge(1, 1, 2, 13); addEdge(2, 1, 3, 9); addEdge(3, 1, 4, 23); addEdge(4, 2, 5, 4); addEdge(5, 2, 6, 25); addEdge(6, 3, 7, 29); addEdge(7, 6, 8, 5); addEdge(8, 7, 9, 30); addEdge(9, 8, 10, 1); addEdge(10, 8, 11, 6); /* our tree is rooted at node 0 at depth 0 */ int root = 0, parent_of_root = -1, depth_of_root = 0; /* a DFS on the tree to set up: * arrays for parent, depth, subtree size for every node; * deeper end of every Edge */ dfs(root, parent_of_root, depth_of_root, n); int []chain_heads = new int[N]; /*we have initialized no chain heads */ Arrays.fill(chain_heads, -1); /* Stores number of edges for construction of segment tree. Initially we haven't traversed any Edges. */ edge_counted = 0; /* we start with filling the 0th chain */ curr_chain = 0; /* HLD of tree */ hld(root, n - 1, n, chain_heads); /* ST of segregated Edges */ construct_ST(0, edge_counted, 1); /* Since indexes are 0 based, node 11 means index 11-1, 8 means 8-1, and so on*/ int u = 11, v = 9; System.out.print("Max edge between " + u + " and " + v + " is "); maxEdge(u - 1, v - 1, n, chain_heads); // Change value of edge number 8 (index 8-1) to 28 change(8 - 1, 28, n); System.out.print("After Change: max edge between " + u + " and " + v + " is "); maxEdge(u - 1, v - 1, n, chain_heads); v = 4; System.out.print("Max edge between " + u + " and " + v + " is "); maxEdge(u - 1, v - 1, n, chain_heads); // Change value of edge number 5 (index 5-1) to 22 change(5 - 1, 22, n); System.out.print("After Change: max edge between " + u + " and " + v + " is "); maxEdge(u - 1, v - 1, n, chain_heads);}} // This code contributed by Rajput-Ji Output: Max edge between 11 and 9 is 30 After Change: max edge between 11 and 9 is 29 Max edge between 11 and 4 is 25 After Change: max edge between 11 and 4 is 23 This article is contributed by Yash Varyani. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nidhi_biet Rajput-Ji array-range-queries LCA Segment-Tree Advanced Data Structure Segment-Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Agents in Artificial Intelligence Decision Tree Introduction with example Segment Tree | Set 1 (Sum of given range) AVL Tree | Set 2 (Deletion) Ordered Set and GNU C++ PBDS Red-Black Tree | Set 2 (Insert) Disjoint Set Data Structures Design a data structure that supports insert, delete, search and getRandom in constant time Binary Indexed Tree or Fenwick Tree Insert Operation in B-Tree
[ { "code": null, "e": 26353, "s": 26325, "text": "\n27 Jan, 2021" }, { "code": null, "e": 26764, "s": 26353, "text": "We strongly recommend to refer below post as a prerequisite of this.Heavy Light Decomposition | Set 1 (Introduction)In the above post, we discussed the Heavy-light...
ANOVA Test in R Programming - GeeksforGeeks
16 Dec, 2021 ANOVA also known as Analysis of variance is used to investigate relations between categorical variables and continuous variable in R Programming. It is a type of hypothesis testing for population variance. ANOVA test involves setting up: Null Hypothesis: All population means are equal. Alternate Hypothesis: Atleast one population mean is different from other. ANOVA tests are of two types: One way ANOVA: It takes one categorical group into consideration. Two way ANOVA: It takes two categorical group into consideration. The mtcars(motor trend car road test) dataset is used which consist of 32 car brands and 11 attributes. The dataset comes preinstalled in dplyr package in R. To get started with ANOVA, we need to install and load the dplyr package. One way ANOVA test is performed using mtcars dataset which comes preinstalled with dplyr package between disp attribute, a continuous attribute and gear attribute, a categorical attribute. R # Installing the packageinstall.packages(dplyr) # Loading the packagelibrary(dplyr) # Variance in mean within group and between groupboxplot(mtcars$disp~factor(mtcars$gear), xlab = "gear", ylab = "disp") # Step 1: Setup Null Hypothesis and Alternate Hypothesis# H0 = mu = mu01 = mu02(There is no difference# between average displacement for different gear)# H1 = Not all means are equal # Step 2: Calculate test statistics using aov functionmtcars_aov <- aov(mtcars$disp~factor(mtcars$gear))summary(mtcars_aov) # Step 3: Calculate F-Critical Value# For 0.05 Significant value, critical value = alpha = 0.05 # Step 4: Compare test statistics with F-Critical value# and conclude test p < alpha, Reject Null Hypothesis Output: The box plot shows the mean values of gear with respect of displacement. Hear categorical variable is gear on which factor function is used and continuous variable is disp. The summary shows that the gear attribute is very significant to displacement(Three stars denoting it). Also, the P value is less than 0.05, so proves that gear is significant to displacement i.e related to each other and we reject the Null Hypothesis. Two-way ANOVA test is performed using mtcars dataset which comes preinstalled with dplyr package between disp attribute, a continuous attribute and gear attribute, a categorical attribute, am attribute, a categorical attribute. R # Installing the packageinstall.packages(dplyr) # Loading the packagelibrary(dplyr) # Variance in mean within group and between groupboxplot(mtcars$disp~mtcars$gear, subset = (mtcars$am == 0), xlab = "gear", ylab = "disp", main = "Automatic")boxplot(mtcars$disp~mtcars$gear, subset = (mtcars$am == 1), xlab = "gear", ylab = "disp", main = "Manual") # Step 1: Setup Null Hypothesis and Alternate Hypothesis# H0 = mu0 = mu01 = mu02(There is no difference between# average displacement for different gear)# H1 = Not all means are equal # Step 2: Calculate test statistics using aov functionmtcars_aov2 <- aov(mtcars$disp~factor(mtcars$gear) * factor(mtcars$am))summary(mtcars_aov2) # Step 3: Calculate F-Critical Value# For 0.05 Significant value, critical value = alpha = 0.05 # Step 4: Compare test statistics with F-Critical value# and conclude test p < alpha, Reject Null Hypothesis Output: The box plot shows the mean values of gear with respect of displacement. Hear categorical variables are gear and am on which factor function is used and continuous variable is disp. The summary shows that gear attribute is very significant to displacement(Three stars denoting it) and am attribute is not much significant to displacement. P-value of gear is less than 0.05, so it proves that gear is significant to displacement i.e related to each other. P-value of am is greater than 0.05, am is not significant to displacement i.e not related to each other. We see significant results from boxplots and summaries. Displacement is strongly related to Gears in cars i.e displacement is dependent on gears with p < 0.05. Displacement is strongly related to Gears but not related to transmission mode in cars with p 0.05 with am. Akanksha_Rai kumar_satyam R-Graphs R-plots R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Adding elements in a vector in R programming - append() method Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? Convert Factor to Numeric and Numeric to Factor in R Programming Group by function in R using Dplyr How to Change Axis Scales in R Plots?
[ { "code": null, "e": 30289, "s": 30261, "text": "\n16 Dec, 2021" }, { "code": null, "e": 30496, "s": 30289, "text": "ANOVA also known as Analysis of variance is used to investigate relations between categorical variables and continuous variable in R Programming. It is a type of h...
Inspect Module in Python - GeeksforGeeks
17 Dec, 2020 The inspect module helps in checking the objects present in the code that we have written. As Python is an OOP language and all the code that is written is basically an interaction between these objects, hence the inspect module becomes very useful in inspecting certain modules or certain objects. We can also use it to get a detailed analysis of certain function calls or tracebacks so that debugging can be easier. The inspect module provides a lot of methods, these methods can be classified into two categories i.e. methods to verify the type of token and methods to retrieve the source of token. The most commonly used methods of both categories are mentioned below. isclass(): The isclass() method returns True if that object is a class or false otherwise. When it is combined with the getmembers() functions it shows the class and its type. It is used to inspect live classes. Example: Python3 # import required modulesimport inspect # create classclass A(object): pass # use isclass()print(inspect.isclass(A)) Output: True ismodule(): This returns true if the given argument is an imported module. Example: Python3 # import required modulesimport inspectimport numpy # use ismodule()print(inspect.ismodule(numpy)) Output: True isfunction(): This method returns true if the given argument is an inbuilt function name. Example: Python3 # import required modulesimport inspect # explicit functiondef fun(a): return 2*a # use isfunction()print(inspect.isfunction(fun)) Output: True ismethod(): This method is used to check if the argument passed is the name of a method or not. Example: Python3 # import required modulesimport inspectimport collections # use ismethod()print(inspect.ismethod(collections.Counter)) Output: False getclasstree(): The getclasstree() method will help in getting and inspecting class hierarchy. It returns a tuple of that class and that of its preceding base classes. That combined with the getmro() method which returns the base classes helps in understanding the class hierarchy. Example 1: Python3 # import required moduleimport inspect # create classesclass A(object): pass class B(A): pass class C(B): pass # not nestedprint(inspect.getmro(C)) Output: (<class ‘__main__.C’>, <class ‘__main__.B’>, <class ‘__main__.A’>, <class ‘object’>) ​ Example 2: Python3 # import required moduleimport inspect # create classesclass A(object): pass class B(A): pass class C(B): pass # nested list of tuplesfor i in (inspect.getclasstree(inspect.getmro(C))): print(i) Output: (<class ‘object’>, ()) [(<class ‘__main__.A’>, (<class ‘object’>,)), [(<class ‘__main__.B’>, (<class ‘__main__.A’>,)), [(<class ‘__main__.C’>, (<class ‘__main__.B’>,))]]] getmembers(): This method returns the member functions present in the module passed as an argument of this method. Example: Python3 # import required moduleimport inspectimport math # shows the member functions# of any module or objectprint(inspect.getmembers(math)) Output: [(‘__doc__’, ‘This module provides access to the mathematical functions\ndefined by the C standard.’), (‘__loader__’, <class ‘_frozen_importlib.BuiltinImporter’>), (‘__name__’, ‘math’), (‘__package__’, ”), (‘__spec__’, ModuleSpec(name=’math’, loader=<class ‘_frozen_importlib.BuiltinImporter’>, origin=’built-in’)), (‘acos’, <built-in function acos>), (‘acosh’, <built-in function acosh>), (‘asin’, <built-in function asin>), (‘asinh’, <built-in function asinh>), (‘atan’, <built-in function atan>), (‘atan2’, <built-in function atan2>), (‘atanh’, <built-in function atanh>), (‘ceil’, <built-in function ceil>), (‘copysign’, <built-in function copysign>), (‘cos’, <built-in function cos>), (‘cosh’, <built-in function cosh>), (‘degrees’, <built-in function degrees>), (‘e’, 2.718281828459045), (‘erf’, <built-in function erf>), (‘erfc’, <built-in function erfc>), (‘exp’, <built-in function exp>), (‘expm1’, <built-in function expm1>), (‘fabs’, <built-in function fabs>), (‘factorial’, <built-in function factorial>), (‘floor’, <built-in function floor>), (‘fmod’, <built-in function fmod>), (‘frexp’, <built-in function frexp>), (‘fsum’, <built-in function fsum>), (‘gamma’, <built-in function gamma>), (‘gcd’, <built-in function gcd>), (‘hypot’, <built-in function hypot>), (‘inf’, inf), (‘isclose’, <built-in function isclose>), (‘isfinite’, <built-in function isfinite>), (‘isinf’, <built-in function isinf>), (‘isnan’, <built-in function isnan>), (‘ldexp’, <built-in function ldexp>), (‘lgamma’, <built-in function lgamma>), (‘log’, <built-in function log>), (‘log10’, <built-in function log10>), (‘log1p’, <built-in function log1p>), (‘log2’, <built-in function log2>), (‘modf’, <built-in function modf>), (‘nan’, nan), (‘pi’, 3.141592653589793), (‘pow’, <built-in function pow>), (‘radians’, <built-in function radians>), (‘remainder’, <built-in function remainder>), (‘sin’, <built-in function sin>), (‘sinh’, <built-in function sinh>), (‘sqrt’, <built-in function sqrt>), (‘tan’, <built-in function tan>), (‘tanh’, <built-in function tanh>), (‘tau’, 6.283185307179586), (‘trunc’, <built-in function trunc>)] signature(): The signature() method helps the user in understanding the attributes which are to be passed on to a function. Python3 # import required modulesimport inspectimport collections # use signature()print(inspect.signature(collections.Counter)) Output: (*args, **kwds) stack(): This method helps in examining the interpreter stack or the order in which functions were called. Python3 # import required moduleimport inspect # define explicit functiondef Fibonacci(n): if n < 0: return 0 elif n == 0: return 0 elif n == 1: return 1 else: return Fibonacci(n-1)+Fibonacci(n-2) # Driver Program(Fibonacci(12)) # inpsecting interpreter stackprint(inspect.stack()) Output: [FrameInfo(frame=<frame at 0x000002AC9BF9FD18, file ‘<ipython-input-8-3080f52ca090>’, line 22, code <module>>, filename='<ipython-input-8-3080f52ca090>’, lineno=22, function='<module>’, code_context=[‘print(inspect.stack())\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BAABA38, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py’, line 3331, code run_code>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py’, lineno=3331, function=’run_code’, code_context=[‘ exec(code_obj, self.user_global_ns, self.user_ns)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9A94B608, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py’, line 3254, code run_ast_nodes>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py’, lineno=3254, function=’run_ast_nodes’, code_context=[‘ if (await self.run_code(code, result, async_=asy)):\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BA8D768, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py’, line 3063, code run_cell_async>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py’, lineno=3063, function=’run_cell_async’, code_context=[‘ interactivity=interactivity, compiler=compiler, result=result)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9C452618, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\async_helpers.py’, line 68, code _pseudo_sync_runner>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\async_helpers.py’, lineno=68, function=’_pseudo_sync_runner’, code_context=[‘ coro.send(None)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BEE1778, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py’, line 2886, code _run_cell>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py’, lineno=2886, function=’_run_cell’, code_context=[‘ return runner(coro)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BE85FC8, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py’, line 2858, code run_cell>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\IPython\\core\\interactiveshell.py’, lineno=2858, function=’run_cell’, code_context=[‘ raw_cell, store_history, silent, shell_futures)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9C464208, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\zmqshell.py’, line 536, code run_cell>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\zmqshell.py’, lineno=536, function=’run_cell’, code_context=[‘ return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BECB108, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\ipkernel.py’, line 300, code do_execute>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\ipkernel.py’, lineno=300, function=’do_execute’, code_context=[‘ res = shell.run_cell(code, store_history=store_history, silent=silent)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BF9FAF8, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\gen.py’, line 209, code wrapper>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\gen.py’, lineno=209, function=’wrapper’, code_context=[‘ yielded = next(result)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BECAEB8, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\kernelbase.py’, line 541, code execute_request>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\kernelbase.py’, lineno=541, function=’execute_request’, code_context=[‘ user_expressions, allow_stdin,\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BF9F6B8, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\gen.py’, line 209, code wrapper>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\gen.py’, lineno=209, function=’wrapper’, code_context=[‘ yielded = next(result)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BEE1BD8, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\kernelbase.py’, line 268, code dispatch_shell>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\kernelbase.py’, lineno=268, function=’dispatch_shell’, code_context=[‘ yield gen.maybe_future(handler(stream, idents, msg))\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BFA0378, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\gen.py’, line 209, code wrapper>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\gen.py’, lineno=209, function=’wrapper’, code_context=[‘ yielded = next(result)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9C44A848, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\kernelbase.py’, line 361, code process_one>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\kernelbase.py’, lineno=361, function=’process_one’, code_context=[‘ yield gen.maybe_future(dispatch(*args))\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BE85368, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\gen.py’, line 748, code run>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\gen.py’, lineno=748, function=’run’, code_context=[‘ yielded = self.gen.send(value)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9C456048, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\gen.py’, line 787, code inner>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\gen.py’, lineno=787, function=’inner’, code_context=[‘ self.run()\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BE882D8, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\ioloop.py’, line 743, code _run_callback>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\ioloop.py’, lineno=743, function=’_run_callback’, code_context=[‘ ret = callback()\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9C4519A8, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\ioloop.py’, line 690, code <lambda>>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\ioloop.py’, lineno=690, function='<lambda>’, code_context=[‘ lambda f: self._run_callback(functools.partial(callback, future))\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BEE5808, file ‘D:\\Software\\Anaconda\\lib\\asyncio\\events.py’, line 88, code _run>, filename=’D:\\Software\\Anaconda\\lib\\asyncio\\events.py’, lineno=88, function=’_run’, code_context=[‘ self._context.run(self._callback, *self._args)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9BEC9798, file ‘D:\\Software\\Anaconda\\lib\\asyncio\\base_events.py’, line 1782, code _run_once>, filename=’D:\\Software\\Anaconda\\lib\\asyncio\\base_events.py’, lineno=1782, function=’_run_once’, code_context=[‘ handle._run()\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9C44BB88, file ‘D:\\Software\\Anaconda\\lib\\asyncio\\base_events.py’, line 538, code run_forever>, filename=’D:\\Software\\Anaconda\\lib\\asyncio\\base_events.py’, lineno=538, function=’run_forever’, code_context=[‘ self._run_once()\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9C44B9A8, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\platform\\asyncio.py’, line 153, code start>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\tornado\\platform\\asyncio.py’, lineno=153, function=’start’, code_context=[‘ self.asyncio_loop.run_forever()\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9C335248, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\kernelapp.py’, line 583, code start>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel\\kernelapp.py’, lineno=583, function=’start’, code_context=[‘ self.io_loop.start()\n’], index=0), FrameInfo(frame=<frame at 0x000002AC9A980F38, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\traitlets\\config\\application.py’, line 664, code launch_instance>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\traitlets\\config\\application.py’, lineno=664, function=’launch_instance’, code_context=[‘ app.start()\n’], index=0), FrameInfo(frame=<frame at 0x000002AC98403228, file ‘D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel_launcher.py’, line 16, code <module>>, filename=’D:\\Software\\Anaconda\\lib\\site-packages\\ipykernel_launcher.py’, lineno=16, function='<module>’, code_context=[‘ app.launch_new_instance()\n’], index=0), FrameInfo(frame=<frame at 0x000002AC985AE468, file ‘D:\\Software\\Anaconda\\lib\\runpy.py’, line 85, code _run_code>, filename=’D:\\Software\\Anaconda\\lib\\runpy.py’, lineno=85, function=’_run_code’, code_context=[‘ exec(code, run_globals)\n’], index=0), FrameInfo(frame=<frame at 0x000002AC97CE5038, file ‘D:\\Software\\Anaconda\\lib\\runpy.py’, line 193, code _run_module_as_main>, filename=’D:\\Software\\Anaconda\\lib\\runpy.py’, lineno=193, function=’_run_module_as_main’, code_context=[‘ “__main__”, mod_spec)\n’], index=0)] getsource(): This method returns the source code of a module, class, method, or a function passes as an argument of getsource() method. Example: Python3 # import required modulesimport inspect def fun(a,b): # product of # two numbers return a*b # use getsource()print(inspect.getsource(fun)) Output: def fun(a,b): # product of # two numbers return a*b getmodule(): This method returns the module name of a particular object pass as an argument in this method. Python3 # import required modulesimport inspectimport collections # use getmodule()print(inspect.getmodule(collections)) Output: <module ‘collections’ from ‘D:\\Software\\Anaconda\\lib\\collections\\__init__.py’> getdoc(): The getdoc() method returns the documentation of the argument in this method as a string. Example: Python3 # import required modulesimport inspectfrom tkinter import * # create objectroot = Tk() # use getdoc()print(inspect.getdoc(root)) Output: Toplevel widget of Tk which represents mostly the main windowof an application. It has an associated Tcl interpreter. python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n17 Dec, 2020" }, { "code": null, "e": 25955, "s": 25537, "text": "The inspect module helps in checking the objects present in the code that we have written. As Python is an OOP language and all the code that is written is basical...
Python program to convert URL Parameters to Dictionary items - GeeksforGeeks
11 Oct, 2020 Given URL Parameters string, convert to dictionary items. Input : test_str = ‘gfg=4&is=5’ Output : {‘gfg’: [‘4’], ‘is’: [‘5’]} Explanation : gfg’s value is 4. Input : test_str = ‘gfg=4’ Output : {‘gfg’: [‘4’]} Explanation : gfg’s value is 4 as param. Method #1 : Using urllib.parse.parse_qs() This is default inbuilt function which performs this task, it parses and the keys are formed from LHS of “=” and return list of values that are in RHS values for the parameters. Thus, import external urllib.parse(), to enable this to work. Python3 # import moduleimport urllib.parse # initializing stringtest_str = 'gfg=4&is=5&best=yes' # printing original stringprint("The original string is : " + str(test_str)) # parse_qs gets the Dictionary and value listres = urllib.parse.parse_qs(test_str) # printing resultprint("The parsed URL Params : " + str(res)) The original string is : gfg=4&is=5&best=yesThe parsed URL Params : {‘gfg’: [‘4’], ‘is’: [‘5’], ‘best’: [‘yes’]} Method #2 : Using findall() + setdefault() In this, we get all the parameters using findall(), and then assign keys and values using setdefault() and loop. Python3 import re # initializing stringtest_str = 'gfg=4&is=5&best=yes' # printing original stringprint("The original string is : " + str(test_str)) # getting all paramsparams = re.findall(r'([^=&]+)=([^=&]+)', test_str) # assigning keys with valuesres = dict()for key, val in params: res.setdefault(key, []).append(val) # printing resultprint("The parsed URL Params : " + str(res)) The original string is : gfg=4&is=5&best=yesThe parsed URL Params : {‘gfg’: [‘4’], ‘is’: [‘5’], ‘best’: [‘yes’]} Python dictionary-programs Python string-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": "\n11 Oct, 2020" }, { "code": null, "e": 25595, "s": 25537, "text": "Given URL Parameters string, convert to dictionary items." }, { "code": null, "e": 25696, "s": 25595, "text": "Input : test_str = ‘gfg=4&is=5’ ...
Node.js os.endianness() Method - GeeksforGeeks
13 Oct, 2021 Endianness refers to the order of bits in a sequence within a binary representation of a number. The os.endianness() method is an inbuilt application programming interface of the os module which is used to get endianness of the CPU of the computer for which the node.js is compiled. Syntax: os.endianness() Parameters: This method does not accept any parameters. Return Value: This method returns a string value that specifies the endianness of the CPU. The returned string will be either BE (for big endian) or LE (for little endian). LE: It is the most significant bits/values in the sequence that is stored in higher memory address. BE: It is the most significant bits/values in the sequence that is stored in lower memory address. Below examples illustrate the use of os.endianness() method in Node.js: Example 1: // Node.js program to demonstrate the // os.endianness() method // Allocating os moduleconst os = require('os'); // Printing os.endianness() valueconsole.log(os.endianness()); Output: LE Example 2: // Node.js program to demonstrate the // os.endianness() method // Allocating os moduleconst os = require('os'); // Printing os.endianness() valueswitch(os.endianness()) { case 'LE': console.log("CPU is little endian format"); break; case 'BE': console.log("CPU is big endian format"); break; default: colsole.log("Unknown endianness");} Output: CPU is little endian format Note: The above program will compile and run by using the node index.js command. Reference: https://nodejs.org/api/os.html#os_os_endianness Node.js-os-module Node.js Web Technologies 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 ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 38501, "s": 38473, "text": "\n13 Oct, 2021" }, { "code": null, "e": 38598, "s": 38501, "text": "Endianness refers to the order of bits in a sequence within a binary representation of a number." }, { "code": null, "e": 38784, "s": 38598, "t...
How to list tables using SQLite3 in Python ? - GeeksforGeeks
09 May, 2021 In this article, we will discuss how to list all the tables in the SQLite database using Python. Database Used: All tables which are present inside our database 1. Creating a connection object using connect() method, sqliteConnection = sqlite3.connect('SQLite_Retrieving_data.db') 2. Created one SQL query with which we will search a list of all tables which are present inside the sqlite3 database. sql_query = """SELECT name FROM sqlite_master WHERE type='table';""" 3. Using Connection Object, we are creating a cursor object. cursor = sqliteConnection.cursor() 4. Using execute() methods, we will execute the above SQL query. cursor.execute(sql_query) 5. Finally, We will print a list of all tables which are present inside the sqlite3 database. print(cursor.fetchall()) Below is the implementation. Python3 # Importing Sqlite3 Moduleimport sqlite3 try: # Making a connection between sqlite3 # database and Python Program sqliteConnection = sqlite3.connect('SQLite_Retrieving_data.db') # If sqlite3 makes a connection with python # program then it will print "Connected to SQLite" # Otherwise it will show errors print("Connected to SQLite") # Getting all tables from sqlite_master sql_query = """SELECT name FROM sqlite_master WHERE type='table';""" # Creating cursor object using connection object cursor = sqliteConnection.cursor() # executing our sql query cursor.execute(sql_query) print("List of tables\n") # printing all tables list print(cursor.fetchall()) except sqlite3.Error as error: print("Failed to execute the above query", error) finally: # Inside Finally Block, If connection is # open, we need to close it if sqliteConnection: # using close() method, we will close # the connection sqliteConnection.close() # After closing connection object, we # will print "the sqlite connection is # closed" print("the sqlite connection is closed") Output: Final output Picked Python-SQLite Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n09 May, 2021" }, { "code": null, "e": 25635, "s": 25537, "text": "In this article, we will discuss how to list all the tables in the SQLite database using Python. " }, { "code": null, "e": 25650, "s": 25635, "...
Java Long decode() method with Examples - GeeksforGeeks
05 Dec, 2018 The java.lang.Long.decode() is a built in function in java that decodes a String into a Long. It accepts decimal, hexadecimal, and octal numbers. Syntax: public static Long decode(String number) throws NumberFormatException Parameter: number- the number that has to be decoded into a Long. Error and Exceptions: NumberFormatException: If the String does not contain a parsable long, the program returns this error. Returns: It returns the decoded string. Program 1: The program below demonstrates the working of function. // Java program to demonstrate// of java.lang.Long.decode() methodimport java.lang.Math; class GFG { // driver code public static void main(String args[]) { // demonstration of function Long l = new Long(14); String str = "54534"; System.out.println("Number = " + l.decode(str)); }} Output: Number = 54534 Program 2: The program demonstrates the conversions using decode() function // Java program to demonstrate// of java.lang.Long.decode() methodimport java.lang.Math; class GFG { // driver code public static void main(String args[]) { // demonstration of conversions String decimal = "10"; // Decimal String hexa = "0XFF"; // Hexa String octal = "067"; // Octal // convert decimal val to number using decode() method Integer number = Integer.decode(decimal); System.out.println("Decimal [" + decimal + "] = " + number); number = Integer.decode(hexa); System.out.println("Hexa [" + hexa + "] = " + number); number = Integer.decode(octal); System.out.println("Octal [" + octal + "] = " + number); }} Output: Decimal [10] = 10 Hexa [0XFF] = 255 Octal [067] = 55 Program 3: The program demonstrates error and exceptions. // Java program to demonstrate// of java.lang.Long.decode() methodimport java.lang.Math; class GFG { // driver code public static void main(String args[]) { // demonstration of errorand exception when // a non-parsable Long is passed String decimal = "1A"; // throws an error Integer number = Integer.decode(decimal); System.out.println("string [" + decimal + "] = " + number); }} Output: Exception in thread "main" java.lang.NumberFormatException: For input string: "1A" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.valueOf(Integer.java:740) at java.lang.Integer.decode(Integer.java:1197) at GFG.main(File.java:16) Java-Functions Java-lang package java-Long Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25767, "s": 25739, "text": "\n05 Dec, 2018" }, { "code": null, "e": 25913, "s": 25767, "text": "The java.lang.Long.decode() is a built in function in java that decodes a String into a Long. It accepts decimal, hexadecimal, and octal numbers." }, { "co...
Multiple Joins in SQL - GeeksforGeeks
30 Jun, 2021 Structured Query Language or SQL is a standard database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, etc. In this article, we will be using the Microsoft SQL Server. Multiple Joins :Here we are going to implement the concept of multiple joins. Multiple joins can be described as a query containing joins of the same or different types used more than once, thus giving them the ability to combine multiple tables. For this article we will first create a database geeks and then create three tables in it and then run our queries on those tables. Venn Diagram Representation of Multiple Joins 1. Creating Database : CREATE geeks; Output –Query ok, 1 row affected 2. To use this database : USE geeks; Output –Database changed 3. Adding Tables to the Database : create table students(id int, name varchar(50),branch varchar(50)); create table marks(id int, marks int); create table attendance(id int, attendance int); Output –Query ok, 0 row affectedQuery ok, 0 row affectedQuery ok, 0 row affected 4. Inserting Data into Tables:Students table – --students insert into students values(1,'anurag','cse'); insert into students values(2,'harsh','ece'); insert into students values(3,'sumit','ece'); insert into students values(4,'kae','cse'); Output –Query ok, 1 row affectedQuery ok, 1 row affectedQuery ok, 1 row affectedQuery ok, 1 row affected 5. Marks Table : --marks insert into marks values(1,95); insert into marks values(2,85); insert into marks values(3,80); insert into marks values(4,65); Output –Query ok, 1 row affectedQuery ok, 1 row affectedQuery ok, 1 row affectedQuery ok, 1 row affected 6. Attendance table : --attendance insert into attendance values(1,75); insert into attendance values(2,65); insert into attendance values(3,80); insert into attendance values(4,80); Output –Query ok, 1 row affectedQuery ok, 1 row affectedQuery ok, 1 row affectedQuery ok, 1 row affected 7. View data inside the tables : select *from students; Output – Students Table – select *from marks; Output – Marks Table- select *from attendance; Output –Attendance table- Screenshot of Final Output – Tables after data Insertion 8. Performing Multiple Joins :Now we will perform multiple joins on our tables. First we will inner join the students and the marks tables and then we will join the resulting table with the attendance table only for those students which have attendance greater than or equal to 75. Syntax – JOIN table1.column_name=table2.column_name JOIN table2.column_name=table3.column_name Example query : select s.id, name, marks, attendance from students as s inner join marks as m on s.id=m.id inner join attendance as a on m.id=a.id where a.attendance>=75; Output – Screenshot of Final Output – Output after Multiple Joins Reference: https://www.geeksforgeeks.org/sql-query-to-find-the-highest-salary-of-each-department/ DBMS-SQL Picked SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL SQL Trigger | Student Database How to Update Multiple Columns in Single Update Statement in SQL? Difference between DDL and DML in DBMS Difference between SQL and NoSQL SQL | GROUP BY SQL | Views Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function Difference between DELETE and TRUNCATE
[ { "code": null, "e": 25511, "s": 25483, "text": "\n30 Jun, 2021" }, { "code": null, "e": 25742, "s": 25511, "text": "Structured Query Language or SQL is a standard database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracl...
Python | Pokémon Training Game - GeeksforGeeks
26 Mar, 2020 Problem :You are a Pokémon trainer. Each Pokémon has its own power, described by a positive integer value. As you travel, you watch Pokémon and you catch each of them. After each catch, you have to display maximum and minimum powers of Pokémon caught so far. You must have linear time complexity. So sorting won’t help here. Try having minimum extra space complexity.Examples:Suppose you catch Pokémon of powers 3 8 9 7. Then the output should be3 33 83 93 9 Input : The single line describing powers of N Pokémon caught. Output : N lines stating minimum power so far and maximum power so far separated by single space Code : Python code to implement Pokemon training game # python code to train pokemonpowers = [3, 8, 9, 7] mini, maxi = 0, 0 for power in powers: if mini == 0 and maxi == 0: mini, maxi = powers[0], powers[0] print(mini, maxi) else: mini = min(mini, power) maxi = max(maxi, power) print(mini, maxi) # Time Complexity is O(N) with Space Complexity O(1) Output : 3 3 3 8 3 9 3 9 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26071, "s": 26043, "text": "\n26 Mar, 2020" }, { "code": null, "e": 26535, "s": 26071, "text": "Problem :You are a Pokémon trainer. Each Pokémon has its own power, described by a positive integer value. As you travel, you watch Pokémon and you catch each o...
Find an equal point in a string of brackets - GeeksforGeeks
22 Apr, 2022 Given a string of brackets, the task is to find an index k which decides the number of opening brackets is equal to the number of closing brackets. The string must be consists of only opening and closing brackets i.e. ‘(‘ and ‘)’. An equal point is an index such that the number of opening brackets before it is equal to the number of closing brackets from and after. Examples: Input: str = “(())))(“Output: 4Explanation: After index 4, string splits into (()) and ))(. The number of opening brackets in the first part is equal to the number of closing brackets in the second part. Input: str = “))”Output: 2Explanation: As after 2nd position i.e. )) and “empty” string will be split into these two parts. So, in this number of opening brackets i.e. 0 in the first part is equal to the number of closing brackets in the second part i.e. also 0. Asked in: Amazon Approach 1: Store the number of opening brackets appears in the string up to every index, it must start from starting index. Similarly, Store the number of closing brackets appears in the string upto each and every index but it should be done from last index. Check if any index has the same value of opening and closing brackets. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to find an index k which// decides the number of opening brackets// is equal to the number of closing brackets#include<bits/stdc++.h>using namespace std; // Function to find an equal indexint findIndex(string str){ int len = str.length(); int open[len+1], close[len+1]; int index = -1; memset(open, 0, sizeof (open)); memset(close, 0, sizeof (close)); open[0] = 0; close[len] = 0; if (str[0]=='(') open[1] = 1; if (str[len-1] == ')') close[len-1] = 1; // Store the number of opening brackets // at each index for (int i = 1; i < len; i++) { if ( str[i] == '(' ) open[i+1] = open[i] + 1; else open[i+1] = open[i]; } // Store the number of closing brackets // at each index for (int i = len-2; i >= 0; i--) { if ( str[i] == ')' ) close[i] = close[i+1] + 1; else close[i] = close[i+1]; } // check if there is no opening or closing // brackets if (open[len] == 0) return len; if (close[0] == 0) return 0; // check if there is any index at which // both brackets are equal for (int i=0; i<=len; i++) if (open[i] == close[i]) index = i; return index;} // Driver codeint main(){ string str = "(()))(()()())))"; cout << findIndex(str); return 0;} // Java program to find an index k which// decides the number of opening brackets// is equal to the number of closing brackets public class GFG{ // Method to find an equal index static int findIndex(String str) { int len = str.length(); int open[] = new int[len+1]; int close[] = new int[len+1]; int index = -1; open[0] = 0; close[len] = 0; if (str.charAt(0)=='(') open[1] = 1; if (str.charAt(len-1) == ')') close[len-1] = 1; // Store the number of opening brackets // at each index for (int i = 1; i < len; i++) { if ( str.charAt(i) == '(' ) open[i+1] = open[i] + 1; else open[i+1] = open[i]; } // Store the number of closing brackets // at each index for (int i = len-2; i >= 0; i--) { if ( str.charAt(i) == ')' ) close[i] = close[i+1] + 1; else close[i] = close[i+1]; } // check if there is no opening or closing // brackets if (open[len] == 0) return len; if (close[0] == 0) return 0; // check if there is any index at which // both brackets are equal for (int i=0; i<=len; i++) if (open[i] == close[i]) index = i; return index; } // Driver Method public static void main(String[] args) { String str = "(()))(()()())))"; System.out.println(findIndex(str)); }} # Method to find an equal indexdef findIndex(str): l = len(str) open = [0] * (l + 1) close = [0] * (l + 1) index = -1 open[0] = 0 close[l] = 0 if (str[0]=='('): open[1] = 1 if (str[l - 1] == ')'): close[l - 1] = 1 # Store the number of # opening brackets # at each index for i in range(1, l): if (str[i] == '('): open[i + 1] = open[i] + 1 else: open[i + 1] = open[i] # Store the number # of closing brackets # at each index for i in range(l - 2, -1, -1): if ( str[i] == ')'): close[i] = close[i + 1] + 1 else: close[i] = close[i + 1] # check if there is no # opening or closing brackets if (open[l] == 0): return len if (close[0] == 0): return 0 # check if there is any # index at which both # brackets are equal for i in range(l + 1): if (open[i] == close[i]): index = i return index # Driver Codestr = "(()))(()()())))"print(findIndex(str)) # This code is contributed# by ChitraNayal // C# program to find an index// k which decides the number// of opening brackets is equal// to the number of closing bracketsusing System; class GFG{// Method to find an equal indexstatic int findIndex(string str){ int len = str.Length; int[] open = new int[len + 1]; int[] close = new int[len + 1]; int index = -1; open[0] = 0; close[len] = 0; if (str[0] == '(') open[1] = 1; if (str[len - 1] == ')') close[len - 1] = 1; // Store the number of // opening brackets // at each index for (int i = 1; i < len; i++) { if (str[i] == '(') open[i + 1] = open[i] + 1; else open[i + 1] = open[i]; } // Store the number // of closing brackets // at each index for (int i = len - 2; i >= 0; i--) { if (str[i] == ')') close[i] = close[i + 1] + 1; else close[i] = close[i + 1]; } // check if there is no // opening or closing // brackets if (open[len] == 0) return len; if (close[0] == 0) return 0; // check if there is any // index at which both // brackets are equal for (int i = 0; i <= len; i++) if (open[i] == close[i]) index = i; return index;} // Driver Codepublic static void Main(){ string str = "(()))(()()())))"; Console.Write(findIndex(str));}} // This code is contributed// by ChitraNayal <?php// Method to find an equal indexfunction findIndex($str){ $len = strlen($str); $open = array(0, $len + 1, NULL); $close = array(0, $len + 1, NULL); $index = -1; $open[0] = 0; $close[$len] = 0; if ($str[0] == '(') $open[1] = 1; if ($str[$len - 1] == ')') $close[$len - 1] = 1; // Store the number // of opening brackets // at each index for ($i = 1; $i < $len; $i++) { if ($str[$i] == '(') $open[$i + 1] = $open[$i] + 1; else $open[$i + 1] = $open[$i]; } // Store the number // of closing brackets // at each index for ($i = $len - 2; $i >= 0; $i--) { if ($str[$i] == ')') $close[$i] = $close[$i + 1] + 1; else $close[$i] = $close[$i + 1]; } // check if there is no // opening or closing // brackets if ($open[$len] == 0) return $len; if ($close[0] == 0) return 0; // check if there is any // index at which both // brackets are equal for ($i = 0; $i <= $len; $i++) if ($open[$i] == $close[$i]) $index = $i; return $index;} // Driver Code$str = "(()))(()()())))";echo (findIndex($str)); // This code is contributed// by ChitraNayal?> <script> // Javascript program to find an index k which// decides the number of opening brackets// is equal to the number of closing brackets // Method to find an equal indexfunction findIndex(str){ let len = str.length; let open = new Array(len + 1); let close = new Array(len + 1); for(let i = 0; i < len + 1; i++) { open[i] = 0; close[i] = 0; } let index = -1; open[0] = 0; close[len] = 0; if (str[0] == '(') open[1] = 1; if (str[len - 1] == ')') close[len - 1] = 1; // Store the number of opening brackets // at each index for(let i = 1; i < len; i++) { if (str[i] == '(') open[i + 1] = open[i] + 1; else open[i + 1] = open[i]; } // Store the number of closing brackets // at each index for(let i = len - 2; i >= 0; i--) { if (str[i] == ')') close[i] = close[i + 1] + 1; else close[i] = close[i + 1]; } // Check if there is no opening or closing // brackets if (open[len] == 0) return len; if (close[0] == 0) return 0; // Check if there is any index at which // both brackets are equal for(let i = 0; i <= len; i++) if (open[i] == close[i]) index = i; return index;} // Driver Codelet str = "(()))(()()())))"; document.write(findIndex(str)); // This code is contributed by avanitrachhadiya2155 </script> 9 Time Complexity: O(N), where N is the size of given stringAuxiliary Space: O(N) Approach 2: Count the total number of closed brackets in string and store in variable, let’s say cnt_close. So count of open brackets is length of (string – count) of closed brackets. Traverse string again but now keep count of open brackets in string, let’s say cnt_open. Now while traversing, let index be i, so count of closed brackets till that index will be (i+1 – cnt_open). Hence, we can check for what index, the count of open brackets in first part equals that of count of closed brackets in second part. Equation becomes cnt_close – (i+1 – cnt_open) = cnt_open, we have to find i. After evaluating above equation we can see cnt_open gets cancelled on both sides so no need. C++ Java Python3 Javascript PHP // C++ program to find an index k which// decides the number of opening brackets// is equal to the number of closing brackets#include <bits/stdc++.h>using namespace std; // Function to find an equal indexint findIndex(string str){ // STL to count occurrences of ')' int cnt_close = count(str.begin(), str.end(), ')'); for (int i = 0; str[i] != '\0'; i++) if (cnt_close == i) return i; // If no opening brackets return str.size();} // Driver codeint main(){ string str = "(()))(()()())))"; cout << findIndex(str); return 0;} // This code is contributed by Dhananjay Dhawale @chessnoobdj // Java program to find an index k which// decides the number of opening brackets// is equal to the number of closing brackets public class GFG { // Method to find an equal index static int findIndex(String str) { int len = str.length(); int cnt_close = 0; for (int i = 0; i < len; i++) if (str.charAt(i) == ')') cnt_close++; for (int i = 0; i < len; i++) if (cnt_close == i) return i; // If no opening brackets return len; } // Driver Method public static void main(String[] args) { String str = "(()))(()()())))"; System.out.println(findIndex(str)); }} // This code is contributed by Aditya Kumar (adityakumar129) # Method to find an equal indexdef findIndex(str): cnt_close = 0 l = len(str) for i in range(1, l): if(str[i] == ')'): cnt_close = cnt_close + 1 for i in range(1, l): if(cnt_close == i): return i # If no opening brackets return l # Driver Codestr = "(()))(()()())))"print(findIndex(str)) # This code is contributed by Aditya Kumar (adityakumar129) <script> // Javascript program to find an index k which// decides the number of opening brackets// is equal to the number of closing brackets // Method to find an equal indexfunction findIndex(str){ let len = str.length; int cnt_close = 0; for(let i = 0; i < len; i++) if (str[i] == ')') cnt_close++; for(let i = 0; i < len; i++) if (cnt_close == i) return i; // If no opening brackets return len; // Driver Codelet str = "(()))(()()())))"; document.write(findIndex(str)); // This code is contributed by Aditya Kumar (adityakumar129) </script> <?php// Method to find an equal indexfunction findIndex($str){ $len = strlen($str); $cnt_close = 0; for ($i = 1; $i < $len; $i++) if ($str[$i] == ')') $cnt_close ++; for ($i = 1; $i < $len; $i++) if ($cnt_close == $i) return $i; return $len;} // Driver Code$str = "(()))(()()())))";echo (findIndex($str)); // This code is contributed by Aditya Kumar (adityakumar129)?> 9 Time Complexity: O(N), Where N is the size of given stringAuxiliary Space: O(1) This article is contributed by Sahil Chhabra (akku). 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. ukasp Shravankashyap2 avanitrachhadiya2155 chessnoobdj adityakumar129 harendrakumar123 rkbhola5 Amazon Arrays Strings Amazon Arrays Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 26137, "s": 26109, "text": "\n22 Apr, 2022" }, { "code": null, "e": 26368, "s": 26137, "text": "Given a string of brackets, the task is to find an index k which decides the number of opening brackets is equal to the number of closing brackets. The string must...
File.ReadLines(String, Encoding) Method in C# with Examples - GeeksforGeeks
01 Jun, 2020 File.ReadLines(String, Encoding) is an inbuilt File class method that is used to read the lines of a file that has a specified encoding. Syntax: public static System.Collections.Generic.IEnumerable ReadLines (string path, System.Text.Encoding encoding); Parameter: This function accepts two parameters which are illustrated below: path: This is the specified file for reading. encoding: This encoding is applied to the contents of the file. Exceptions: ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters defined by the GetInvalidPathChars() method. ArgumentNullException: The path is null. DirectoryNotFoundException: The path is invalid. FileNotFoundException: The file specified by the path was not found. IOException: An I/O error occurred while opening the file. PathTooLongException: The path exceeds the system-defined maximum length. SecurityException: The caller does not have the required permission. UnauthorizedAccessException: The path specifies a file that is read-only. OR this operation is not supported on the current platform. OR the path is a directory. OR the caller does not have the required permission. Return Value: Returns all the lines of the specified file. Below are the programs to illustrate the File.ReadLines(String, Encoding) method. Program 1: Initially, a file file.txt is created with some contents shown below- // C# program to illustrate the usage// of File.ReadLines(String, Encoding) method // Using System, System.IO// and System.Text namespacesusing System;using System.IO;using System.Text; public class GFG { public static void Main(String[] argv) { // Calling the ReadLines(String, Encoding) function foreach(string line in File.ReadLines(@"file.txt", Encoding.UTF8)) { // Printing the file contents Console.WriteLine(line); } }} Output: GFG gfg Geeks GeeksforGeeks geeksforgeeks Program 2: Initially, a file file.txt is created with some contents shown below- Below code filter some contents from the file and prints them back. // C# program to illustrate the usage// of File.ReadLines(String, Encoding) method // Using System, System.IO// and System.Text namespacesusing System;using System.IO;using System.Text; public class GFG { public static void Main(String[] argv) { // Calling the ReadLines(String, Encoding) function foreach(string line in File.ReadLines(@"file.txt", Encoding.UTF8)) { // Filtering the file contents and printing if (line.Contains("GFG")) { Console.WriteLine(line); } } }} Output: GFG CSharp-File-Handling C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? Switch Statement in C# Linked List Implementation in C# Convert String to Character Array in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n01 Jun, 2020" }, { "code": null, "e": 25684, "s": 25547, "text": "File.ReadLines(String, Encoding) is an inbuilt File class method that is used to read the lines of a file that has a specified encoding." }, { "code": null...
Sort the given Array as per given conditions - GeeksforGeeks
07 Feb, 2022 Given an array arr[] consisting of N positive integers, the task is to sort the array such that – All even numbers must come before all odd numbers. All even numbers that are divisible by 5 must come first than even numbers not divisible by 5. If two even numbers are divisible by 5 then the number having a greater value will come first If two even numbers were not divisible by 5 then the number having a greater index in the array will come first. All odd numbers must come in relative order as they are present in the array. Examples: Input: arr[] = {5, 10, 30, 7}Output: 30 10 5 7Explanation: Even numbers = [10, 30]. Odd numbers = [5, 7]. After sorting of even numbers, even numbers = [30, 10] as both 10 and 30 divisible by 5 but 30 has a larger value so it will come before 10.After sorting A = [30, 10, 5, 7] as all even numbers must come before all odd numbers. Approach: This problem can be solved by using sorting. Follow the steps below to solve the problem: Create three vectors say v1, v2, v3 where v1 stores number which is even and divisible by 5, v2 stores number which is even but not divisible by 5, and v3 stores the numbers which are odd. Iterate in the range [0, N-1] using the variable i and perform the following steps-If arr[i]%2 = 0 and arr[i]%5=0, then insert arr[i] in v1.If arr[i]%2 = 0 and arr[i]%5 != 0, then insert arr[i] in v2.If arr[i]%2 then insert arr[i] in v3. If arr[i]%2 = 0 and arr[i]%5=0, then insert arr[i] in v1. If arr[i]%2 = 0 and arr[i]%5 != 0, then insert arr[i] in v2. If arr[i]%2 then insert arr[i] in v3. Sort the vector v1 in descending order. After performing the above steps, print vector v1 then print vector v2 and then v3 as the answer. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to sort array in the way// mentioned abovevoid AwesomeSort(vector<int> m, int n){ // Create three vectors vector<int> v1, v2, v3; int i; // Traverse through the elements // of the array for (i = 0; i < n; i++) { // If elements are even and // divisible by 10 if (m[i] % 10 == 0) v1.push_back(m[i]); // If number is even but not divisible // by 5 else if (m[i] % 2 == 0) v2.push_back(m[i]); else // If number is odd v3.push_back(m[i]); } // Sort v1 in descending orde sort(v1.begin(), v1.end(), greater<int>()); for (int i = 0; i < v1.size(); i++) { cout << v1[i] << " "; } for (int i = v2.size()-1; i >= 0; i--) { cout << v2[i] << " "; } for (int i = 0; i < v3.size(); i++) { cout << v3[i] << " "; }} // Driver Codeint main(){ // Given Input vector<int> arr{ 5, 10, 30, 7 }; int N = arr.size(); // FunctionCall AwesomeSort(arr, N); return 0;} // Java program for the above approachimport java.util.Collections;import java.util.Vector; public class GFG_JAVA { // Function to sort array in the way // mentioned above static void AwesomeSort(Vector<Integer> m, int n) { // Create three vectors Vector<Integer> v1 = new Vector<>(); Vector<Integer> v2 = new Vector<>(); Vector<Integer> v3 = new Vector<>(); int i; // Traverse through the elements // of the array for (i = 0; i < n; i++) { // If elements are even and // divisible by 10 if (m.get(i) % 10 == 0) v1.add(m.get(i)); // If number is even but not divisible // by 5 else if (m.get(i) % 2 == 0) v2.add(m.get(i)); else // If number is odd v3.add(m.get(i)); } // Sort v1 in descending orde Collections.sort(v1, Collections.reverseOrder()); for (int ii = 0; ii < v1.size(); ii++) { System.out.print(v1.get(ii) + " "); } for (int ii = v2.size()-1; ii >= 0; ii--) { System.out.print(v2.get(ii) + " "); } for (int ii = 0; ii < v3.size(); ii++) { System.out.print(v3.get(ii) + " "); } } // Driver code public static void main(String[] args) { // Given Input Vector<Integer> arr = new Vector<>(); arr.add(5); arr.add(10); arr.add(30); arr.add(7); int N = arr.size(); // FunctionCall AwesomeSort(arr, N); }} // This code is contributed by abhinavjain194 # Python program for the above approach # Function to sort array in the way# mentioned abovedef AwesomeSort(m, n): # Create three vectors v1, v2, v3 = [],[],[] # Traverse through the elements # of the array for i in range(n): # If elements are even and # divisible by 10 if (m[i] % 10 == 0): v1.append(m[i]) # If number is even but not divisible # by 5 elif (m[i] % 2 == 0): v2.append(m[i]) else: # If number is odd v3.append(m[i]) # Sort v1 in descending orde v1 = sorted(v1)[::-1] for i in range(len(v1)): print(v1[i], end = " ") for i in range(len(v2)): print(v2[i], end = " ") for i in range(len(v3)): print (v3[i], end = " ") # Driver Codeif __name__ == '__main__': # Given Input arr = [5, 10, 30, 7] N = len(arr) # FunctionCall AwesomeSort(arr, N) # This code is contributed by mohit kumar 29. // C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Function to sort array in the way // mentioned above static void AwesomeSort(List<int> m, int n) { // Create three vectors List<int> v1 = new List<int>(); List<int> v2 = new List<int>(); List<int> v3 = new List<int>(); int i; // Traverse through the elements // of the array for (i = 0; i < n; i++) { // If elements are even and // divisible by 10 if (m[i] % 10 == 0) v1.Add(m[i]); // If number is even but not divisible // by 5 else if (m[i] % 2 == 0) v2.Add(m[i]); else // If number is odd v3.Add(m[i]); } // Sort v1 in descending orde v1.Sort(); v1.Reverse(); for (int ii = 0; ii < v1.Count; ii++) { Console.Write(v1[ii] + " "); } for (int ii = 0; ii < v2.Count; ii++) { Console.Write(v2[ii] + " "); } for (int ii = 0; ii < v3.Count; ii++) { Console.Write(v3[ii] + " "); } } static void Main() { // Given Input List<int> arr = new List<int>(); arr.Add(5); arr.Add(10); arr.Add(30); arr.Add(7); int N = arr.Count; // FunctionCall AwesomeSort(arr, N); }} // This code is contributed by divyeshrabadiya07. <script> // JavaScript program for the above approach // Function to sort array in the way// mentioned abovefunction AwesomeSort(m, n){ // Create three vectors let v1 = []; let v2 = []; let v3 = []; let i; // Traverse through the elements // of the array for (i = 0; i < n; i++) { // If elements are even and // divisible by 10 if (m[i] % 10 == 0) v1.push(m[i]); // If number is even but not divisible // by 5 else if (m[i] % 2 == 0) v2.push(m[i]); else // If number is odd v3.push(m[i]); } // Sort v1 in descending orde v1.sort((a, b) => b - a); for (let i = 0; i < v1.length; i++) { document.write(v1[i] + " "); } for (let i = 0; i < v2.length; i++) { document.write(v2[i] + " "); } for (let i = 0; i < v3.length; i++) { document.write(v3[i] + " "); }} // Driver Code // Given Inputlet arr = [5, 10, 30, 7];let N = arr.length; // FunctionCallAwesomeSort(arr, N); </script> 30 10 5 7 Time Complexity: O(NlogN)Auxiliary Space: O(N) abhinavjain194 mohit kumar 29 _saurabh_jaiswal divyeshrabadiya07 pk218 Lowe's Company Arrays Sorting Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element
[ { "code": null, "e": 26066, "s": 26038, "text": "\n07 Feb, 2022" }, { "code": null, "e": 26165, "s": 26066, "text": "Given an array arr[] consisting of N positive integers, the task is to sort the array such that – " }, { "code": null, "e": 26216, "s": 26165, ...
String hashing using Polynomial rolling hash function - GeeksforGeeks
09 Apr, 2022 A Hash function is a function that maps any kind of data of arbitrary size to fixed-size values. The values returned by the function are called Hash Values or digests. There are many popular Hash Functions such as DJBX33A, MD5, and SHA-256. This post will discuss the key features, implementation, advantages and drawbacks of the Polynomial Rolling Hash Function. Note that if two strings are equal, their hash values should also be equal. But the inverse need not be true. Polynomial rolling hash function is a hash function that uses only multiplications and additions. The following is the function: or simply, Where The input to the function is a string of length . and are some positive integers. The choice of and affects the performance and the security of the hash function. If the string consists of only lower-case letters, then is a good choice.Competitive Programmers prefer using a larger value for . Examples include , , . Competitive Programmers prefer using a larger value for . Examples include , , . shall necessarily be a large prime since the probability of two keys colliding (producing the same hash) is nearly . and are widely used values for . The output of the function is the hash value of the string which ranges between and inclusive. Below is the implementation of the Polynomial Rolling Hash Function C C++ Java Python3 #include <stdio.h>#include <string.h> int get_hash(const char* s, const int n) { const int p = 31, m = 1e9 + 7; int hash = 0; long p_pow = 1; for(int i = 0; i < n; i++) { hash = (hash + (s[i] - 'a' + 1) * p_pow) % m; p_pow = (p_pow * p) % m; } return hash;} int main() { char s[] = "geeksforgeeks"; int n = strlen(s); printf("Hash of %s is %d\n", s, get_hash(s, n)); return 0;} #include <bits/stdc++.h>using namespace std; struct Hash { const int p = 31, m = 1e9 + 7; int hash_value; Hash(const string& s) { int hash_so_far = 0; long p_pow = 1; const int n = s.length(); for (int i = 0; i < n; ++i) { hash_so_far = (hash_so_far + (s[i] - 'a' + 1) * p_pow) % m; p_pow = (p_pow * p) % m; } hash_value = hash_so_far; } bool operator==(const Hash& other) { return (hash_value == other.hash_value); }}; int main() { const string s = "geeksforgeeks"; Hash h(s); cout << "Hash of " << s << " is: " << h.hash_value << '\n'; return 0;} class Hash { final int p = 31, m = 1000000007; int hash_value; Hash(String S) { int hash_so_far = 0; final char[] s = S.toCharArray(); long p_pow = 1; final int n = s.length; for (int i = 0; i < n; i++) { hash_so_far = (int)((hash_so_far + (s[i] - 'a' + 1) * p_pow) % m); p_pow = (p_pow * p) % m; } hash_value = hash_so_far; }} class Main { public static void main(String[] args) { String s = "geeksforgeeks"; Hash h = new Hash(s); System.out.println("Hash of " + s + " is " + h.hash_value); }} class Hash: def __init__(self, s: str): self.hash_value = 0 self.p, self.m = 31, 10**9 + 7 self.length = len(s) hash_so_far = 0 p_pow = 1 for i in range(self.length): hash_so_far = (hash_so_far + (1 + ord(s[i]) - ord('a')) * p_pow) % self.m p_pow = (p_pow * self.p) % self.m self.hash_value = hash_so_far def __eq__(self, other): return self.hash_value == other.hash_value if __name__ == '__main__': s = "geeksforgeeks" h = Hash(s) print("Hash value of {} is {}".format(s, h.hash_value)) Since the output of the Hash function is an integer in the range , there are high chances for two strings producing the same hash value. For instance, the strings and produce the same hash value for and . Also, the strings and produce the same hash value for and . We can guarantee a collision within a very small domain. Consider a set of strings, , consisting of only lower-case letters, such that the length of any string in doesn’t exceed . We have . Since the range of the Hash Function is , one-one mapping is impossible. Hence, we can guarantee a collision by arbitrarily generating two strings whose length doesn’t exceed . We can note that the value of affects the chances of collision. We have seen that the probability of collision is . We can increase the value of to reduce the probability of collision. But that affects the speed of the algorithm. Larger the value of , the slower the algorithm. Also, some languages (C, C++, Java) have a limit on the size of the integer. Hence, we can’t increase the value of to a very large value. Then how can we minimise the chances of a collision? Note that the hash of a string depends on two parameters: and . We have seen that the strings and produce the same hash value for and . But for and , they produce different hashes. If two strings produce the same hash values for a pair , they will produce different hashes for a different pair, . We cannot, however, nullify the chances of collision because there are infinitely many strings. But, surely, we can reduce the probability of two strings colliding. We can reduce the probability of collision by generating a pair of hashes for a given string. The first hash is generated using and , while the second hash is generated using and . We are generating two hashes using two different modulo values, and . The probability of a collision is now . Since both and are greater than , the probability that a collision occurs is now less than which is so much better than the original probability of collision, . Below is the implementation for the same C C++ Java Python3 #include <stdio.h>#include <string.h> int get_hash1(const char* s, int length) { const int p = 31, m = 1e9 + 7; int hash_value = 0; long p_pow = 1; for(int i = 0; i < length; i++) { hash_value = (hash_value + (s[i] - 'a' + 1) * p_pow) % m; p_pow = (p_pow * p) % m; } return hash_value;} int get_hash2(const char* s, int length) { const int p = 37, m = 1e9 + 9; int hash_value = 0; long p_pow = 1; for(int i = 0; i < length; i++) { hash_value = (hash_value + (s[i] - 'a' + 1) * p_pow) % m; p_pow = (p_pow * p) % m; } return hash_value;} int main() { char s[] = "geeksforgeeks"; int length = strlen(s); int hash1 = get_hash1(s, length); int hash2 = get_hash2(s, length); printf("Hash values of %s are: (%d, %d)\n", s, hash1, hash2); return 0;} #include <bits/stdc++.h>using namespace std; struct Hash { const int p1 = 31, m1 = 1e9 + 7; const int p2 = 37, m2 = 1e9 + 9; int hash1 = 0, hash2 = 0; Hash(const string& s) { compute_hash1(s); compute_hash2(s); } void compute_hash1(const string& s) { long p_pow = 1; for(char ch: s) { hash1 = (hash1 + (ch + 1 - 'a') * p_pow) % m1; p_pow = (p_pow * p1) % m1; } } void compute_hash2(const string& s) { long p_pow = 1; for(char ch: s) { hash2 = (hash2 + (ch + 1 - 'a') * p_pow) % m2; p_pow = (p_pow * p2) % m2; } } // For two strings to be equal // they must have same hash1 and hash2 bool operator==(const Hash& other) { return (hash1 == other.hash1 && hash2 == other.hash2); }}; int main() { const string s = "geeksforgeeks"; Hash h(s); cout << "Hash values of " << s << " are: "; cout << "(" << h.hash1 << ", " << h.hash2 << ")" << '\n'; return 0;} class Hash { final int p1 = 31, m1 = 1000000007; final int p2 = 37, m2 = 1000000009; int hash_value1, hash_value2; Hash(String s) { compute_hash1(s); compute_hash2(s); } void compute_hash1(String s) { int hash_so_far = 0; final char[] s_array = s.toCharArray(); long p_pow = 1; final int n = s_array.length; for (int i = 0; i < n; i++) { hash_so_far = (int)((hash_so_far + (s_array[i] - 'a' + 1) * p_pow) % m1); p_pow = (p_pow * p1) % m1; } hash_value1 = hash_so_far; } void compute_hash2(String s) { int hash_so_far = 0; final char[] s_array = s.toCharArray(); long p_pow = 1; final int n = s_array.length; for (int i = 0; i < n; i++) { hash_so_far = (int)((hash_so_far + (s_array[i] - 'a' + 1) * p_pow) % m2); p_pow = (p_pow * p2) % m2; } hash_value2 = hash_so_far; }} class Main { public static void main(String[] args) { String s = "geeksforgeeks"; Hash h = new Hash(s); System.out.println("Hash values of " + s + " are: " + h.hash_value1 + ", " + h.hash_value2); }} class Hash: def __init__(self, s: str): self.p1, self.m1 = 31, 10**9 + 7 self.p2, self.m2 = 37, 10**9 + 9 self.hash1, self.hash2 = 0, 0 self.compute_hashes(s) def compute_hashes(self, s: str): pow1, pow2 = 1, 1 hash1, hash2 = 0, 0 for ch in s: seed = 1 + ord(ch) - ord('a') hash1 = (hash1 + seed * pow1) % self.m1 hash2 = (hash2 + seed * pow2) % self.m2 pow1 = (pow1 * self.p1) % self.m1 pow2 = (pow2 * self.p2) % self.m2 self.hash1, self.hash2 = hash1, hash2 def __eq__(self, other): return self.hash1 == other.hash1 and self.hash2 == other.hash2 def __str__(self): return f'({self.hash1}, {self.hash2})' if __name__ == '__main__': s = "geeksforgeeks" hash = Hash(s) print("Hash of " + s + " is " + str(hash)) Note that computing the hash of the string S will also compute the hashes of all of the prefixes. We just have to store the hash values of the prefixes while computing. Say \text{hash[i]} denotes the hash of the prefix \text{S[0...i]}, we have This allows us to quickly compute the hash of the substring in provided we have powers of ready. Recall that the hash of a string is given by Say, we change a character at some index to some other character . How will the hash change? If denotes the hash value before changing and is the hash value after changing, then the relation between them is given by Therefore, queries can be performed very quickly instead of recalculating the hash from beginning, provided we have the powers of ready. A more elegant implementation is provided below. C++ #include <bits/stdc++.h>using namespace std; long long power(long long x, long long y, long long p) { long long result = 1; for(; y; y >>= 1, x = x * x % p) { if(y & 1) { result = result * x % p; } } return result;} long long inverse(long long x, long long p) { return power(x, p - 2, p);} class Hash {private: int length; const int mod1 = 1e9 + 7, mod2 = 1e9 + 9; const int p1 = 31, p2 = 37; vector<int> hash1, hash2; pair<int, int> hash_pair; public: inline static vector<int> inv_pow1, inv_pow2; inline static int inv_size = 1; Hash() {} Hash(const string& s) { length = s.size(); hash1.resize(length); hash2.resize(length); int h1 = 0, h2 = 0; long long p_pow1 = 1, p_pow2 = 1; for(int i = 0; i < length; i++) { h1 = (h1 + (s[i] - 'a' + 1) * p_pow1) % mod1; h2 = (h2 + (s[i] - 'a' + 1) * p_pow2) % mod2; p_pow1 = (p_pow1 * p1) % mod1; p_pow2 = (p_pow2 * p2) % mod2; hash1[i] = h1; hash2[i] = h2; } hash_pair = make_pair(h1, h2); if(inv_size < length) { for(; inv_size < length; inv_size <<= 1); inv_pow1.resize(inv_size, -1); inv_pow2.resize(inv_size, -1); inv_pow1[inv_size - 1] = inverse(power(p1, inv_size - 1, mod1), mod1); inv_pow2[inv_size - 1] = inverse(power(p2, inv_size - 1, mod2), mod2); for(int i = inv_size - 2; i >= 0 && inv_pow1[i] == -1; i--) { inv_pow1[i] = (1LL * inv_pow1[i + 1] * p1) % mod1; inv_pow2[i] = (1LL * inv_pow2[i + 1] * p2) % mod2; } } } int size() { return length; } pair<int, int> prefix(const int index) { return {hash1[index], hash2[index]}; } pair<int, int> substr(const int l, const int r) { if(l == 0) { return {hash1[r], hash2[r]}; } int temp1 = hash1[r] - hash1[l - 1]; int temp2 = hash2[r] - hash2[l - 1]; temp1 += (temp1 < 0 ? mod1 : 0); temp2 += (temp2 < 0 ? mod2 : 0); temp1 = (temp1 * 1LL * inv_pow1[l]) % mod1; temp2 = (temp2 * 1LL * inv_pow2[l]) % mod2; return {temp1, temp2}; } bool operator==(const Hash& other) { return (hash_pair == other.hash_pair); }}; int main() { string my_str = "geeksforgeeks"; const int n = my_str.length(); auto hash = Hash(my_str); auto hash_pair = hash.substr(0, n - 1); cout << "Hashes of the string " << my_str << " are:\n"; cout << hash_pair.first << ' ' << hash_pair.second << '\n'; return 0;} In the above implementation, we are computing the inverses of powers of $p$ in linear time. Consider this problem: Given a sequence S of N strings and Q queries. In each query, you are given two indices, i and j, your task is to find the length of the longest common prefix of the strings S[i] and S[j]. Before getting into the approach to solve this problem, note that the constraints are: Using Hashing, the problem can be solved in O(N + Q\log|S|_{max}). The approach is to compute hashes for all the strings in O(N) time, Then for each query, we can binary search the length of the longest common prefix using hashing. The implementation for this approach is provided below. C++14 #include <bits/stdc++.h>using namespace std; long long power(long long x, long long y, long long p) { long long result = 1; for(; y; y >>= 1, x = x * x % p) { if(y & 1) { result = result * x % p; } } return result;} long long inverse(long long x, long long p) { return power(x, p - 2, p);} class Hash {private: int length; const int mod1 = 1e9 + 7, mod2 = 1e9 + 9; const int p1 = 31, p2 = 37; vector<int> hash1, hash2; pair<int, int> hash_pair; public: inline static vector<int> inv_pow1, inv_pow2; inline static int inv_size = 1; Hash() {} Hash(const string& s) { length = s.size(); hash1.resize(length); hash2.resize(length); int h1 = 0, h2 = 0; long long p_pow1 = 1, p_pow2 = 1; for(int i = 0; i < length; i++) { h1 = (h1 + (s[i] - 'a' + 1) * p_pow1) % mod1; h2 = (h2 + (s[i] - 'a' + 1) * p_pow2) % mod2; p_pow1 = (p_pow1 * p1) % mod1; p_pow2 = (p_pow2 * p2) % mod2; hash1[i] = h1; hash2[i] = h2; } hash_pair = make_pair(h1, h2); if(inv_size < length) { for(; inv_size < length; inv_size <<= 1); inv_pow1.resize(inv_size, -1); inv_pow2.resize(inv_size, -1); inv_pow1[inv_size - 1] = inverse(power(p1, inv_size - 1, mod1), mod1); inv_pow2[inv_size - 1] = inverse(power(p2, inv_size - 1, mod2), mod2); for(int i = inv_size - 2; i >= 0 && inv_pow1[i] == -1; i--) { inv_pow1[i] = (1LL * inv_pow1[i + 1] * p1) % mod1; inv_pow2[i] = (1LL * inv_pow2[i + 1] * p2) % mod2; } } } int size() { return length; } pair<int, int> prefix(const int index) { return {hash1[index], hash2[index]}; } pair<int, int> substr(const int l, const int r) { if(l == 0) { return {hash1[r], hash2[r]}; } int temp1 = hash1[r] - hash1[l - 1]; int temp2 = hash2[r] - hash2[l - 1]; temp1 += (temp1 < 0 ? mod1 : 0); temp2 += (temp2 < 0 ? mod2 : 0); temp1 = (temp1 * 1LL * inv_pow1[l]) % mod1; temp2 = (temp2 * 1LL * inv_pow2[l]) % mod2; return {temp1, temp2}; } bool operator==(const Hash& other) { return (hash_pair == other.hash_pair); }}; void query(vector<Hash>& hashes, const int N) { int i = 0, j = 0; cin >> i >> j; i--, j--; int lb = 0, ub = min(hashes[i].size(), hashes[j].size()); int max_length = 0; while(lb <= ub) { int mid = (lb + ub) >> 1; if(hashes[i].prefix(mid) == hashes[j].prefix(mid)) { if(mid + 1 > max_length) { max_length = mid + 1; } lb = mid + 1; } else { ub = mid - 1; } } cout << max_length << '\n';} int main() { int N = 0, Q = 0; cin >> N >> Q; vector<Hash> hashes; for(int i = 0; i < N; i++) { string s; cin >> s; hashes.push_back(Hash(s)); } for(; Q > 0; Q--) { query(hashes, N); } return 0;} Input: 5 4 geeksforgeeks geeks hell geeksforpeaks hello 1 2 1 3 3 5 1 4 Expected Output: 5 0 4 8 SHIVAMSINGH67 amit143katiyar 29AjayKumar souravghosh0416 pankajsharmagfg sourashis69 sweetyty suman_1729 C-String-Question cpp-strings Hash maths-polynomial Advanced Data Structure Competitive Programming Data Structures Hash Strings cpp-strings Data Structures Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Agents in Artificial Intelligence Decision Tree Introduction with example AVL Tree | Set 2 (Deletion) Ordered Set and GNU C++ PBDS Red-Black Tree | Set 2 (Insert) Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Fast I/O for Competitive Programming
[ { "code": null, "e": 25955, "s": 25927, "text": "\n09 Apr, 2022" }, { "code": null, "e": 26319, "s": 25955, "text": "A Hash function is a function that maps any kind of data of arbitrary size to fixed-size values. The values returned by the function are called Hash Values or dige...
How to Compare Two Columns in Pandas? - GeeksforGeeks
20 Dec, 2021 In this article, we learn how to compare the columns in the pandas’ dataframe. Pandas is a very useful library in python, it is mainly used for data analysis, visualization, data cleaning, and many. Comparing the columns is very needful, when we want to compare the values between them or if we want to know the similarity between them. For example, if we take two columns, and we want to find which column is greater than or lesser than the other column or also to find the similarity between them, Comparing the column is the suitable thing that we might need to do. There are many types of methods in pandas and NumPy to compare the values between them, We will see all the methods and implementation in this article. In this method, the condition is passed into this method and if the condition is true, then it will be the value we give( that is ‘X in the syntax) if it is false then, it will be the value we give to them (that is ‘y’ in the syntax). Syntax: numpy.where(condition[,x, y]) Parameters: condition : When True, yield x, otherwise yield y. x, y : Values from which to choose. In the below code, we are importing the necessary libraries that are pandas and NumPy. We created a dictionary, and the values for each column are given. Then it is converted into a pandas dataframe. By using the Where() method in NumPy, we are given the condition to compare the columns. If ‘column1’ is lesser than ‘column2’ and ‘column1’ is lesser than the ‘column3’, We print the values of ‘column1’. If the condition fails, we give the value as ‘NaN’. These results are stored in the new column in the dataframe. Python3 # Importing Librariesimport pandas as pdimport numpy as np # data's stored in dictionarydetails = { 'Column1': [1, 2, 30, 4], 'Column2': [7, 4, 25, 9], 'Column3': [3, 8, 10, 30]} # creating a Dataframe objectdf = pd.DataFrame(details) # Where method to compare the values# The values were stored in the new columndf['new'] = np.where((df['Column1'] <= df['Column2']) & ( df['Column1'] <= df['Column3']), df['Column1'], np.nan) # printing the dataframeprint(df) Output: np.Where() This method Test whether two-column contain the same elements. This function allows two Series or DataFrames to be compared against each other to see if they have the same shape and elements. NaNs in the same location are considered equal. Syntax: DataFrame.equals(other) Parameters: OtherSeries or DataFrame: The other Series or DataFrame to be compared with the first. Returns: bool True if all elements are the same in both objects, False otherwise In the below code, we are following the same procedure, which is importing libraries and creating a dataframe. In this dataframe, I have added a new column that is equal to the ‘column2’ to show what the method does in this dataframe. Python3 # importing librariesimport pandas as pd # Storing data in dictionarydetails = { 'Column1': [1, 2, 3, 4], 'Column2': [7, 4, 25, 9], 'Column3': [3, 8, 10, 30], 'Column4': [7, 4, 25, 9],} # creating a Dataframe objectdf = pd.DataFrame(details) df['Column4'].equals(df['Column2']) # Returns True # df['Column1'].equals(df['Column2']) Returns False Output: True This method allows us to pass the function or condition and get to apply the same function throughout the pandas’ dataframe series. This method saves us time and code. Syntax: DataFrame.apply(func, axis=0, raw=False, result_type=None, args=(), **kwargs) In the below code, We are repeating the same process to create a dataframe in pandas. By using apply() method we are creating a temporary anonymous function made in apply() itself using lambda. It checks whether the ‘column1’ is lesser than ‘column2’ and ‘column1’ is lesser than ‘column3’. If it is True it will give ‘column1’ value. If it is False It will print NaN. These values are stored inside the New column. Hence we compared the columns. Python3 import pandas as pddetails = { 'Column1': [1, 2, 3, 4], 'Column2': [7, 4, 2, 9], 'Column3': [3, 8, 10, 30],} # creating a Dataframe objectdf = pd.DataFrame(details) # apply functiondf['New'] = df.apply(lambda x: x['Column1'] if x['Column1'] <= x['Column2'] and x['Column1'] <= x['Column3'] else np.nan, axis=1) # printing the dataframeprint(df) Output: Apply() sweetyty pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25555, "s": 25527, "text": "\n20 Dec, 2021" }, { "code": null, "e": 25756, "s": 25555, "text": "In this article, we learn how to compare the columns in the pandas’ dataframe. Pandas is a very useful library in python, it is mainly used for data analysis, visu...
Angular PrimeNG SplitButton Component - GeeksforGeeks
30 Sep, 2021 Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive websites. In this article, we will see how to use SplitButton component in angular primeNG. The SplitButton component is used to make a button as a dropdown. Properties: label: it is the text of the button. It is of string data type, the default value is null. icon: it is the name of the icon. It is of string data type, the default value is null. iconPos: it is the position of the icon. It is of string data type, the default value is null. style: It is the Inline style of the component. It is of string data type, the default value is null. styleClass: It is the Style class of the component. It is of string data type, the default value is null. menuStyle: It is the Inline style of the overlay menu. It is of string data type, the default value is null. menuStyleClass: It is the Style class of the overlay menu. It is of string data type, the default value is null. appendTo: It is the Target element to attach the overlay. It is of string data type, the default value is null. disabled: it specifies that the component should be disabled. It is of boolean data type, the default value is false. tabindex: It is the Index of the element in tabbing order. It is of number data type, the default value is null. dir: It Indicates the direction of the element. It is of string data type, the default value is null. showTransitionOptions: These are the Transition options of the show animation. It is of string data type, the default value is null. hideTransitionOptions: These are the Transition options of the hide animation. It is of string data type, the default value is null. Event: onClick: It is the Callback to invoke when default command button is clicked. onDropdownClick: It is the Callback to invoke when dropdown button is clicked. Styling: p-splitbutton: It is the Container element. p-splitbutton-menubutton: It is the Dropdown button. p-menu: It is the Overlay menu Creating Angular Application And Installing Module: Step 1: Create a Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: It will look like the following. Example: This is the basic example that shows how to use SplitButton component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG SplitButton Component</h5><p-splitButton label="GeeksforGeeks" [model]="gfg"></p-splitButton> app.module.ts import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import {RouterModule} from '@angular/router';import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { SplitButtonModule } from 'primeng/splitbutton'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, SplitButtonModule, RouterModule.forRoot([ {path:'',component: AppComponent} ]) ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]}) export class AppModule { } app.component.ts import { Component, OnInit, ViewEncapsulation} from '@angular/core';import {MenuItem} from 'primeng/api';import {MessageService} from 'primeng/api'; @Component({ selector: 'app-root', providers: [MessageService], templateUrl: './app.component.html', styles: [` :host ::ng-deep .ui-splitbutton { margin-right: .25em; } `]})export class AppComponent { gfg: MenuItem[]; constructor(private messageService: MessageService) {} ngOnInit() { this.gfg = [ {label: 'Angular'}, {label: 'PrimeNG'}, {label: 'SplitButton'} ]; }} Output: Reference: https://primefaces.org/primeng/showcase/#/splitbutton Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event Angular PrimeNG Messages Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26354, "s": 26326, "text": "\n30 Sep, 2021" }, { "code": null, "e": 26523, "s": 26354, "text": "Angular PrimeNG is a framework used with angular to create components with great styling and this framework is very easy to use and is used to make responsive webs...
How to cbind vectors of different length without repetition of elements of the smaller vector in R?
We can join vectors by columns using cbind and it does not matter whether these vectors are of same length or not. If the vectors are of same length then all the values of both the vectors are printed but if the length of these vectors are different then the values of the smaller vector gets repeated. But we might not want to repeat the values/elements of the smaller vector and it is possible by setting the length of the smaller vector to the length of larger vector, this will create NA values in the smaller at places where the original vector does not have any values. x1<-c(4,7,8,12) x2<-1:20 n<-max(length(x1),length(x2)) length(x1)<-n cbind(x1,x2) x1 x2 [1,] 4 1 [2,] 7 2 [3,] 8 3 [4,] 12 4 [5,] NA 5 [6,] NA 6 [7,] NA 7 [8,] NA 8 [9,] NA 9 [10,] NA 10 [11,] NA 11 [12,] NA 12 [13,] NA 13 [14,] NA 14 [15,] NA 15 [16,] NA 16 [17,] NA 17 [18,] NA 18 [19,] NA 19 [20,] NA 20 y1<-c("A","B","C","D","E") y2<-LETTERS[1:20] n<-max(length(y1),length(y2)) length(y1)<-n cbind(y1,y2) y1 y2 [1,] "A" "A" [2,] "B" "B" [3,] "C" "C" [4,] "D" "D" [5,] "E" "E" [6,] NA "F" [7,] NA "G" [8,] NA "H" [9,] NA "I" [10,] NA "J" [11,] NA "K" [12,] NA "L" [13,] NA "M" [14,] NA "N" [15,] NA "O" [16,] NA "P" [17,] NA "Q" [18,] NA "R" [19,] NA "S" [20,] NA "T" z1<-1:20 z2<-16:20 n<-max(length(z1),length(z2)) length(z2)<-n cbind(z1,z2) z1 z2 [1,] 1 16 [2,] 2 17 [3,] 3 18 [4,] 4 19 [5,] 5 20 [6,] 6 NA [7,] 7 NA [8,] 8 NA [9,] 9 NA [10,] 10 NA [11,] 11 NA [12,] 12 NA [13,] 13 NA [14,] 14 NA [15,] 15 NA [16,] 16 NA [17,] 17 NA [18,] 18 NA [19,] 19 NA [20,] 20 NA
[ { "code": null, "e": 1638, "s": 1062, "text": "We can join vectors by columns using cbind and it does not matter whether these vectors are of same length or not. If the vectors are of same length then all the values of both the vectors are printed but if the length of these vectors are different the...