title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Algorithm to generate positive rational numbers in Java
Rational Numbers − A number that is expressed in the form of p/q. Given the condition that p and q both should be integers and q should not be equal to 0. Positive rational numbers are those numbers whose final values are positive. For this, either p and q both should be positive or p and q both should be negative. In this problem to generate positive random numbers up to a given number. We have to generate a finite number of positive rational numbers to n i.e. we will find rational numbers between 1 to n. For this algorithm, we will generate random numbers where 1 <= p <= n and 1 <= q <= n. Let's take an example to elaborate on the concept better − Input : 3 Output : 1, 1⁄2 , 1⁄3 , 2 , 2⁄3 , 3/2 , 3 . Explanation − In this example, we will consider values between 1 to 3 for both p and q. The algorithm designed for this will work using sets which are the best data structures for optimally generating the required combinations. As sets can be mapped and mapping can be of the order n to n i.e. each value in set1 can be mapped properly with values in set2 creating a mapping that can generate the required pairs. For generating the required pairs we will use to sets of positive values and map the values to get the solutions. Let’s take an example, (1,1) , (1,2) , (1,3) (2,1) , (2,2) , (2,3) (3,1) , (3,2) , (3,3) Let's re-arrange these values in an inverted L shape traversal method − (1,1) (1,2) , (2,2) , (2,1) (1,3) , (2,3) , (3,3) , (3,2) , (3,1) These are the values that we have used in generating positive rational algorithm examples. For better understanding that we have yielded the exact same values just replace the, with ∕ to get these values − 1/1 1/2 , 2/2 , 2/1 1/3 , 2/3 , 3/3 , 3/2 , 3/1 Though there are values like 1∕1, 2∕2, 3∕3 that point to the same value. We will eliminate these values using the greatest common divisor. import java.util.ArrayList; import java.util.List; class PositiveRational { private static class PositiveRationalNumber { private int numerator; private int denominator; public PositiveRationalNumber(int numerator, int denominator){ this.numerator = numerator; this.denominator = denominator; } @Override public String toString(){ if (denominator == 1) { return Integer.toString(numerator); } else { return Integer.toString(numerator) + '/' + Integer.toString(denominator); } } } private static int gcd(int num1, int num2){ int n1 = num1; int n2 = num2; while (n1 != n2) { if (n1 > n2) n1 -= n2; else n2 -= n1; } return n1; } private static List<PositiveRationalNumber> generate(int n){ List<PositiveRationalNumber> list = new ArrayList<>(); if (n > 1) { PositiveRationalNumber rational = new PositiveRationalNumber(1, 1); list.add(rational); } for (int loop = 1; loop <= n; loop++) { int jump = 1; if (loop % 2 == 0) jump = 2; else jump = 1; for (int row = 1; row <= loop - 1; row += jump) { if (gcd(row, loop) == 1) { PositiveRationalNumber rational = new PositiveRationalNumber(row, loop); list.add(rational); } } for (int col = loop - 1; col >= 1; col -= jump) { if (gcd(col, loop) == 1) { PositiveRationalNumber rational = new PositiveRationalNumber(loop, col); list.add(rational); } } } return list; } public static void main(String[] args){ List<PositiveRationalNumber>rationals = generate(5); System.out.println(rationals.stream(). map(PositiveRationalNumber::toString). reduce((x, y) -> x + ", " + y).get()); } } 1, 1/2, 2, 1/3, 2/3, 3/2, 3, 1/4, 3/4, 4/3, 4, 1/5, 2/5, 3/5, 4/5, 5/4, 5/3, 5/2, 5
[ { "code": null, "e": 1217, "s": 1062, "text": "Rational Numbers − A number that is expressed in the form of p/q. Given the condition that p and q both should be integers and q should not be equal to 0." }, { "code": null, "e": 1379, "s": 1217, "text": "Positive rational numbers a...
How to use NLP to Analyze WhatsApp Messages | by Maarten Grootendorst | Towards Data Science
On 17 August 2018, I married the woman of my dreams and wanted to surprise her with a gift the day before the wedding. Of course, as a Data Scientist, I had to communicate that through data! Our WhatsApp messages seemed like a great source of information. I used NLP to analyze the messages and created a small python package, called SOAN, that allows you to do so. In this post, I will guide you through the analyses that I did and how you would use the package that I created. Follow this link for instructions on downloading your WhatsApp texts as .txt. The package allows you to preprocess the .txt file as a specific format is required to do the analyses. Simply import the helper function to both import the data and process it. The import_data is used to import the data and preprocess_data prepares the data in such a way that it is ready for analysis. from soan.whatsapp import helper # Helper to prepare the datafrom soan.whatsapp import general # General statisticsfrom soan.whatsapp import tf_idf # Calculate uniquenessfrom soan.whatsapp import emoji # Analyse use of emojifrom soan.whatsapp import topic # Topic modelingfrom soan.whatsapp import sentiment # Sentiment analysesfrom soan.whatsapp import wordcloud # Sentiment-based Word Clouds%matplotlib inlinedf = helper.import_data('Whatsapp.txt')df = helper.preprocess_data(df) After preprocessing the data you will have a few columns: Message_Raw, Message_Clean, Message_Only_Text, User, Date, Hour, Day_of_Week. The Message_Raw contains the raw message, Message_Clean only contains the message itself and not the user or date, and Message_Only_Text only keeps lowercased text and removes any non-alphanumeric character: Now that the data is preprocessed, some initial graphs can be created based on the frequency of messages. Call plot_messages to plot the frequency of messages on a weekly basis: general.plot_messages(df, colors=None, trendline=False, savefig=False, dpi=100) Interestingly, this shows a seemingly significant dip in messages around December of 2016. We moved in together at the time which explains why we did not need to text each other that much. I was also interested in the daily frequency of messages between my wife and me. Some inspiration was borrowed from Github to create a calendar plot (using a modified version of CalMap): general.calendar_plot(df, year=2017, how='count', column='index') There are a view days were we texted more often but that does not seem to be a visual observable pattern. Let’s go more in-depth with TF-IDF! I wanted to display words that were unique to us but also frequently used. For example, the word “Hi” might be unique to me (because she always uses the word “Hello”) but if I used it a single time in hundreds of messages it simply will not be that interesting. To model this I used a popular algorithm called TF-IDF (i.e., Term Frequency-Inverse Document Frequency). It takes the frequency of words in a document and calculates the inverse proportion of those words to the corpus: Basically, it shows you which words are important and which are not. For example, words like “the”, “I” and “an” appear in most texts and are typically not that interesting. The version of TF-IDF that you see above is slightly adjusted as I focused on the number of words that were texted by a person instead of the number of texts. The next step is to calculate a uniqueness score for each person by simply dividing the TF-IDF scores for each person: As you can see in the formula above it takes into account the TF-IDF scores of each person in the chat. Thus, it would also work for group chats. One important thing in doing Data Science is to communicate the results in clear but also a fun and engaging manner. Since my audience was my wife I had to make sure my visualizations were clear. I decided to use a horizontal histogram that would show the most unique words and their scores. Words are typically easier to read in a horizontal histogram. To make it more visually interesting you can use the bars as a mask for any image that you want to include. For demonstration purposes I used a picture of my wedding: unique_words = tf_idf.get_unique_words(counts, df, version = 'C')tf_idf.plot_unique_words(unique_words, user='Me', image_path='histogram.jpg', image_url=None, title="Me", title_color="white", title_background='#AAAAAA', width=400, height=500) The emojis that we use, to a certain extent, can describe how we are feeling. I felt like it would be interesting to apply the formula that you saw previously (i.e., TF-IDF + Unique Words) to emojis. In other words, which emojis are unique to whom but also frequently used? I can simply take the raw messages and extract the emojis. Then, it is a simple manner of counting the number of emojis and applying the formula: emoji.print_stats(unique_emoji, counts) Clearly, my unique emojis are more positive while those of her seem to be on the negative side. This does not necessarily mean that I use more positive emojis. It merely means that her unique emojis tend to be more negative. A natural follow-up to these analyses would be the sentiment. Are there perhaps dips in the relationship that can be seen through our messages? First, we need to extract how positive messages are. Make sure to create a new column with the sentiment score through: from pattern.nl import sentiment as sentiment_nldf['Sentiment'] = df.apply(lambda row: sentiment_nl(row.Message_Clean)[0], 1) I decided against putting the sentiment step in the package seeing as there are many ways (and languages) to create the sentiment from. Perhaps you would like to use different methods other than a lexicon based approach. Then, we can calculate the average weekly sentiment and plot the result: sentiment.plot_sentiment(df, colors=[‘#EAAA69’,’#5361A5'], savefig=False) In January of 2018, I was in an accident which explains the negativity of the messages in that period. Word Clouds are often used to demonstrate which words appear frequently in documents. Words that appear frequently are bigger than those that only appear a few times. To make the clouds more interesting I separated them by sentiment. Positive words get a different cloud from negative words: (positive, negative) = wordcloud.extract_sentiment_count(counts, user = "Me")wordcloud.create_wordcloud(data=positive, cmap='Greens', mask='mask.jpg', stopwords='stopwords_dutch.txt', random_state=42, max_words=1000, max_font_size=50, scale=1.5, normalize_plurals=False, relative_scaling=0.5)wordcloud.create_wordcloud(data=negative, cmap='Reds', mask='mask.jpg', stopwords='stopwords_dutch.txt', random_state=42, max_words=1000, max_font_size=50, scale=1.5, normalize_plurals=False, relative_scaling=0.5) The words were selected based on an existing lexicon in the pattern package. Positive words that we typically used were goed (good) and super (super). Negative words include laat (late) and verschrikkelijk (horrible). It is interesting to see that some words were labeled to be negative that I did not use as such. For example, I typically use waanzinnig (crazy) as very to emphasize certain words. Topic Modeling is a tool that tries to extract topics from textual documents. A set of documents likely contains multiple topics that might be interesting to the user. A topic is represented by a set of words. For example, a topic might contain the words dog, cat, and horse. Based on these words, it seems that the topic is about animals. I implemented two algorithms for creating topics in SOAN, namely LDA (Latent Dirichlet allocation) and NMF (Non-negative Matrix Factorization). NMF uses linear algebra for the creation of topics while LDA is based on probabilistic modeling. Check this post for an in-depth explanation of the models. I decided to remove the option to work on the parameters of both models as it was intended to give a quick overview of possible topics. It runs the model for each user separately: topic.topics(df, model='lda', stopwords='stopwords_dutch.txt')topic.topics(df, model='nmf', stopwords='stopwords_dutch.txt') What you can see in the generated topics (if you can read Dutch) is that topics can be found that describe doing groceries. There are also quite some topics that somewhat describe seeing each other the next day or saying good night. This would make sense seeing as most of our messages were sent during the time we did not live together. The downside of using Topic Modeling is that the user needs to interpret the topics themselves. It also could require parameter tweaking to find quality topics. If you are, like me, passionate about AI, Data Science, or Psychology, please feel free to add me on LinkedIn or follow me on Twitter. Make sure to visit the notebook if you want a full overview of the code! You can simply pull the code and add your own WhatsApp.txt file via this link.
[ { "code": null, "e": 363, "s": 172, "text": "On 17 August 2018, I married the woman of my dreams and wanted to surprise her with a gift the day before the wedding. Of course, as a Data Scientist, I had to communicate that through data!" }, { "code": null, "e": 538, "s": 363, "tex...
Python Tweepy – Getting the source of a tweet - GeeksforGeeks
18 Jun, 2020 In this article we will see how we can get the source of a status/tweet. The source of the tweet tells us how the tweet was posted. Some examples of sources are : Twitter for Android Twitter for iPhone Twitter Web App The source attribute of the Status object provides us with the source of the status. Identifying the source of the status in the GUI : In the above mentioned status, the source of the status is : Twitter for Android In order to get the source of the status, we have to do the following : Identify the status ID of the status from the GUI.Get the Status object of the status using the get_status() method with the status ID.From this object, fetch the source attribute present in it. Identify the status ID of the status from the GUI. Get the Status object of the status using the get_status() method with the status ID. From this object, fetch the source attribute present in it. Example 1 : Consider the following status : We will use the status ID to fetch the status. The status ID of the above mentioned status is 1272771459249844224. # import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the statusid = 1272771459249844224 # fetching the statusstatus = api.get_status(id) # fetching the source attributesource = status.source print("The source of the status is : " + source) Output : The source of the status is : Twitter for Android Example 2 : Consider the following status : We will use the status ID to fetch the status. The status ID of the above mentioned status is 1273112322773581824. # the ID of the statusid = 1273112322773581824 # fetching the statusstatus = api.get_status(id # fetching the source attributesource = status.source print("The source of the status is : " + source) Output : The source of the status is : Twitter Web App Python-Tweepy 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": 25701, "s": 25673, "text": "\n18 Jun, 2020" }, { "code": null, "e": 25864, "s": 25701, "text": "In this article we will see how we can get the source of a status/tweet. The source of the tweet tells us how the tweet was posted. Some examples of sources are :"...
LocalDateTime plusMinutes() method in Java with Examples - GeeksforGeeks
30 Nov, 2018 The plusMinutes() method of LocalDateTime class is used to return a copy of this date-time with the specified minutes added. Syntax: public LocalDateTime plusMinutes(long minutes) Parameter: It accepts a single parameter minutes which specifies the minutes to add which may be negative. Return Value: This method returns a LocalDateTime based on this date-time with the minutes added. Exceptions: The programs throws a DateTimeException which is thrown if the result exceeds the supported date range. Below programs illustrate the YearMonth.plusMinutes() method in Java: Program 1: // Program to illustrate the plusMinutes() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { LocalDateTime dt1 = LocalDateTime .parse("2018-01-11T10:15:30"); System.out.println("LocalDateTime with 15 minutes added: " + dt1.plusMinutes(15)); }} LocalDateTime with 15 minutes added: 2018-01-11T10:30:30 Program 2: // Program to illustrate the plusMinutes() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { LocalDateTime dt1 = LocalDateTime .parse("2018-01-11T08:15:30"); System.out.println("LocalDateTime with -2 minutes added: " + dt1.plusMinutes(-2)); }} LocalDateTime with -2 minutes added: 2018-01-11T08:13:30 Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#plusMinutes(long) Java-Functions Java-LocalDateTime Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n30 Nov, 2018" }, { "code": null, "e": 25350, "s": 25225, "text": "The plusMinutes() method of LocalDateTime class is used to return a copy of this date-time with the specified minutes added." }, { "code": null, "e": 2...
Minimum number of operations required to reduce N to 1 - GeeksforGeeks
23 Dec, 2021 Given an integer element ‘N’, the task is to find the minimum number of operations that need to be performed to make ‘N’ equal to 1. The allowed operations to be performed are: Decrement N by 1.Increment N by 1.If N is a multiple of 3, you can divide N by 3. Decrement N by 1. Increment N by 1. If N is a multiple of 3, you can divide N by 3. Examples: Input: N = 4 Output: 2 4 – 1 = 3 3 / 3 = 1 The minimum number of operations required is 2. Input: N = 8 Output: 3 8 + 1 = 9 9 / 3 = 3 3 / 3 = 1 The minimum number of operations required is 3. Approach: If the number is a multiple of 3, divide it by 3. If the number modulo 3 is 1, decrement it by 1. If the number modulo 3 is 2, increment it by 1. There is an exception when the number is equal to 2, in this case the number should be decremented by 1. Repeat the above steps until the number is greater than 1 and print the count of operations performed in the end. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of above approach#include<bits/stdc++.h>using namespace std; // Function that returns the minimum// number of operations to be performed// to reduce the number to 1int count_minimum_operations(long long n){ // To stores the total number of // operations to be performed int count = 0; while (n > 1) { // if n is divisible by 3 // then reduce it to n / 3 if (n % 3 == 0) n /= 3; // if n modulo 3 is 1 // decrement it by 1 else if (n % 3 == 1) n--; else { if (n == 2) n--; // if n modulo 3 is 2 // then increment it by 1 else n++; } // update the counter count++; } return count;} // Driver codeint main(){ long long n = 4; long long ans = count_minimum_operations(n); cout<<ans<<endl; return 0;} // This code is contributed by mits // Java implementation of above approach class GFG { // Function that returns the minimum // number of operations to be performed // to reduce the number to 1 static int count_minimum_operations(long n) { // To stores the total number of // operations to be performed int count = 0; while (n > 1) { // if n is divisible by 3 // then reduce it to n / 3 if (n % 3 == 0) n /= 3; // if n modulo 3 is 1 // decrement it by 1 else if (n % 3 == 1) n--; else { if (n == 2) n--; // if n modulo 3 is 2 // then increment it by 1 else n++; } // update the counter count++; } return count; } // Driver code public static void main(String[] args) { long n = 4; long ans = count_minimum_operations(n); System.out.println(ans); }} # Python3 implementation of above approach # Function that returns the minimum# number of operations to be performed# to reduce the number to 1def count_minimum_operations(n): # To stores the total number of # operations to be performed count = 0 while (n > 1) : # if n is divisible by 3 # then reduce it to n / 3 if (n % 3 == 0): n //= 3 # if n modulo 3 is 1 # decrement it by 1 elif (n % 3 == 1): n -= 1 else : if (n == 2): n -= 1 # if n modulo 3 is 2 # then increment it by 1 else: n += 1 # update the counter count += 1 return count # Driver codeif __name__ =="__main__": n = 4 ans = count_minimum_operations(n) print (ans) # This code is contributed# by ChitraNayal // C# implementation of above approachusing System; public class GFG{ // Function that returns the minimum // number of operations to be performed // to reduce the number to 1 static int count_minimum_operations(long n) { // To stores the total number of // operations to be performed int count = 0; while (n > 1) { // if n is divisible by 3 // then reduce it to n / 3 if (n % 3 == 0) n /= 3; // if n modulo 3 is 1 // decrement it by 1 else if (n % 3 == 1) n--; else { if (n == 2) n--; // if n modulo 3 is 2 // then increment it by 1 else n++; } // update the counter count++; } return count; } // Driver code static public void Main (){ long n = 4; long ans = count_minimum_operations(n); Console.WriteLine(ans); }} <?php// PHP implementation of above approach // Function that returns the minimum// number of operations to be performed// to reduce the number to 1function count_minimum_operations($n){ // To stores the total number of // operations to be performed $count = 0; while ($n > 1) { // if n is divisible by 3 // then reduce it to n / 3 if ($n % 3 == 0) $n /= 3; // if n modulo 3 is 1 // decrement it by 1 else if ($n % 3 == 1) $n--; else { if ($n == 2) $n--; // if n modulo 3 is 2 // then increment it by 1 else $n++; } // update the counter $count++; } return $count;} // Driver code$n = 4; $ans = count_minimum_operations($n);echo $ans, "\n"; // This code is contributed by akt_mit?> <script> // Javascript implementation of above approach // Function that returns the minimum // number of operations to be performed // to reduce the number to 1 function count_minimum_operations(n) { // To stores the total number of // operations to be performed let count = 0; while (n > 1) { // if n is divisible by 3 // then reduce it to n / 3 if (n % 3 == 0) n /= 3; // if n modulo 3 is 1 // decrement it by 1 else if (n % 3 == 1) n--; else { if (n == 2) n--; // if n modulo 3 is 2 // then increment it by 1 else n++; } // update the counter count++; } return count; } let n = 4; let ans = count_minimum_operations(n); document.write(ans); </script> 2 Recursive Approach: The recursive approach is similar to the approach used above. Below is the implementation: C++ Java Python3 C# Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function that returns the minimum// number of operations to be performed// to reduce the number to 1int count_minimum_operations(long long n){ // Base cases if (n == 2) { return 1; } else if (n == 1) { return 0; } if (n % 3 == 0) { return 1 + count_minimum_operations(n / 3); } else if (n % 3 == 1) { return 1 + count_minimum_operations(n - 1); } else { return 1 + count_minimum_operations(n + 1); }} // Driver codeint main(){ long long n = 4; long long ans = count_minimum_operations(n); cout << ans << endl; return 0;} // This code is contributed by koulick_sadhu // Java implementation of above approachimport java.util.*; class GFG{ // Function that returns the minimum// number of operations to be performed// to reduce the number to 1public static int count_minimum_operations(int n){ // Base cases if (n == 2) { return 1; } else if (n == 1) { return 0; } if (n % 3 == 0) { return 1 + count_minimum_operations(n / 3); } else if (n % 3 == 1) { return 1 + count_minimum_operations(n - 1); } else { return 1 + count_minimum_operations(n + 1); }} // Driver codepublic static void main(String []args){ int n = 4; int ans = count_minimum_operations(n); System.out.println(ans);}} // This code is contributed by avanitrachhadiya2155 # Python3 implementation of above approach # Function that returns the minimum# number of operations to be performed# to reduce the number to 1def count_minimum_operations(n): # Base cases if (n == 2): return 1 elif (n == 1): return 0 if (n % 3 == 0): return 1 + count_minimum_operations(n / 3) elif (n % 3 == 1): return 1 + count_minimum_operations(n - 1) else: return 1 + count_minimum_operations(n + 1) # Driver Coden = 4ans = count_minimum_operations(n) print(ans) # This code is contributed by divyesh072019 // C# implementation of above approachusing System;class GFG { // Function that returns the minimum // number of operations to be performed // to reduce the number to 1 static int count_minimum_operations(int n) { // Base cases if (n == 2) { return 1; } else if (n == 1) { return 0; } if (n % 3 == 0) { return 1 + count_minimum_operations(n / 3); } else if (n % 3 == 1) { return 1 + count_minimum_operations(n - 1); } else { return 1 + count_minimum_operations(n + 1); } } // Driver code static void Main() { int n = 4; int ans = count_minimum_operations(n); Console.WriteLine(ans); }} // This code is contributed by divyeshrabadiya07 <script> // Javascript implementation of above approach // Function that returns the minimum // number of operations to be performed // to reduce the number to 1 function count_minimum_operations(n) { // Base cases if (n == 2) { return 1; } else if (n == 1) { return 0; } if (n % 3 == 0) { return 1 + count_minimum_operations(n / 3); } else if (n % 3 == 1) { return 1 + count_minimum_operations(n - 1); } else { return 1 + count_minimum_operations(n + 1); } } let n = 4; let ans = count_minimum_operations(n); document.write(ans); // This code is contributed by suresh07.</script> 2 Another Method (Efficient): DP using memoization(Top down approach) We can avoid the repeated work done by storing the operations performed calculated so far. We just need to store all the values in an array. C++ Java Python C# Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; int static dp[1001]; // Function that returns the minimum// number of operations to be performed// to reduce the number to 1int count_minimum_operations(long long n){ // Base cases if (n == 2) { return 1; } if (n == 1) { return 0; } if(dp[n] != -1) { return dp[n]; } if (n % 3 == 0) { dp[n] = 1 + count_minimum_operations(n / 3); } else if (n % 3 == 1) { dp[n] = 1 + count_minimum_operations(n - 1); } else { dp[n] = 1 + count_minimum_operations(n + 1); } return dp[n];} // Driver codeint main(){ long long n = 4; memset(dp, -1, sizeof(dp)); long long ans = count_minimum_operations(n); cout << ans << endl; return 0;} // This code is contributed by Samim Hossain Mondal // Java implementation of above approachimport java.util.*;public class GFG{ static int []dp = new int[1001]; // Function that returns the minimum// number of operations to be performed// to reduce the number to 1public static int count_minimum_operations(int n){ // Base cases if (n == 2) { return 1; } else if (n == 1) { return 0; } if(dp[n] != -1) { return dp[n]; } if (n % 3 == 0) { dp[n] = 1 + count_minimum_operations(n / 3); } else if (n % 3 == 1) { dp[n] = 1 + count_minimum_operations(n - 1); } else { dp[n] = 1 + count_minimum_operations(n + 1); } return dp[n];} // Driver codepublic static void main(String []args){ int n = 4; for(int i = 0; i < 1001; i++) { dp[i] = -1; } int ans = count_minimum_operations(n); System.out.println(ans);}} // This code is contributed by Samim Hossain Mondal. # Python3 implementation of above approach # Function that returns the minimum# number of operations to be performed# to reduce the number to 1dp = [-1 for i in range(1001)] def count_minimum_operations(n): # Base cases if (n == 2): return 1 elif (n == 1): return 0 if(dp[n] != -1): return dp[n] elif (n % 3 == 0): dp[n] = 1 + count_minimum_operations(n / 3) elif (n % 3 == 1): dp[n] = 1 + count_minimum_operations(n - 1) else: dp[n] = 1 + count_minimum_operations(n + 1) return dp[n] # Driver Coden = 4ans = count_minimum_operations(n) print(ans) # This code is contributed by Samim Hossain Mondal // C# implementation of above approachusing System;class GFG{ static int []dp = new int[1001]; // Function that returns the minimum // number of operations to be performed // to reduce the number to 1 public static int count_minimum_operations(int n) { // Base cases if (n == 2) { return 1; } else if (n == 1) { return 0; } if(dp[n] != -1) { return dp[n]; } if (n % 3 == 0) { dp[n] = 1 + count_minimum_operations(n / 3); } else if (n % 3 == 1) { dp[n] = 1 + count_minimum_operations(n - 1); } else { dp[n] = 1 + count_minimum_operations(n + 1); } return dp[n]; } // Driver code public static void Main() { int n = 4; for(int i = 0; i < 1001; i++) { dp[i] = -1; } int ans = count_minimum_operations(n); Console.Write(ans); }} // This code is contributed by Samim Hossain Mondal. <script>// Javascript program for the above approach let dp = []; // Function that returns the minimum// number of operations to be performed// to reduce the number to 1function count_minimum_operations(n){ // Base cases if (n == 2) { return 1; } if (n == 1) { return 0; } if(dp[n] != -1) { return dp[n]; } if (n % 3 == 0) { dp[n] = 1 + count_minimum_operations(n / 3); } else if (n % 3 == 1) { dp[n] = 1 + count_minimum_operations(n - 1); } else { dp[n] = 1 + count_minimum_operations(n + 1); } return dp[n];} // Driver Code// Input Nth termlet n = 4; for(let i = 0; i < 1001; i++) { dp[i] = -1;} let ans = count_minimum_operations(n);document.write(ans); // This code is contributed by Samim Hossain Mondal.</script> 2 Time Complexity: O(n) Auxiliary Space: O(n) Sach_Code Mithun Kumar jit_t ukasp koulick_sadhu divyesh072019 divyeshrabadiya07 avanitrachhadiya2155 suresh07 mukesh07 samim2000 Constructive Algorithms divisibility Greedy Mathematical Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Activity Selection Problem | Greedy Algo-1 Fractional Knapsack Problem Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Job Sequencing Problem Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 26677, "s": 26649, "text": "\n23 Dec, 2021" }, { "code": null, "e": 26855, "s": 26677, "text": "Given an integer element ‘N’, the task is to find the minimum number of operations that need to be performed to make ‘N’ equal to 1. The allowed operations to be p...
p5.js | cursor() Function - GeeksforGeeks
30 Oct, 2019 The cursor() function in p5.js is used to set the cursor to a predefined symbol or an image or it makes visible if already hidden. To set an image as the cursor, the recommended size is 16×16 or 32×32 pixels. The values for parameters x and y must be less than the dimensions of the image. Syntax: cursor(type, x, y) Parameters: This function accepts three parameters as mentioned above and described below: type: This parameter stores the type of cursor like ARROW, CROSS, HAND, MOVE, TEXT and WAIT Native CSS properties: ‘grab’, ‘progress’, ‘cell’ etc. External: path for cursor’s images (Allowed File extensions: .cur, .gif, .jpg, .jpeg, .png). x: This parameter stores the horizontal active spot of the cursor. y: This parameter stores the vertical active spot of the cursor. Below program illustrates the cursor() function in p5.js: Example: This example uses cursor() function to display the cursor. function setup() { // Create canvas createCanvas(400, 400); // Set the text size textSize(40); // Set the text alignment // to center textAlign(CENTER);} function draw() { cursor('https://s3.amazonaws.com/mupublicdata/cursor.cur');} Output: Reference: https://p5js.org/reference/#/p5/cursor Akanksha_Rai 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 ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 44937, "s": 44909, "text": "\n30 Oct, 2019" }, { "code": null, "e": 45227, "s": 44937, "text": "The cursor() function in p5.js is used to set the cursor to a predefined symbol or an image or it makes visible if already hidden. To set an image as the cursor, t...
Perl matching operator - GeeksforGeeks
07 May, 2019 m operator in Perl is used to match a pattern within the given text. The string passed to m operator can be enclosed within any character which will be used as a delimiter to regular expressions.To print this matched pattern and the remaining string, m operator provides various operators which include $, which contains whatever the last grouping match matched.$& – contains the entire matched string$` – contains everything before the matched string$’ – contains everything after the matched string Syntax: m/String/ Return:0 on failure and 1 on success Example 1: #!/usr/bin/perl -w # Text String$string = "Geeks for geeks is the best"; # Let us use m operator to search # "or g"$string =~ m/or g/; # Printing the Stringprint "Before: $`\n";print "Matched: $&\n";print "After: $'\n"; Before: Geeks f Matched: or g After: eeks is the best Example 2: #!/usr/bin/perl -w # Text String$string = "Welcome to GeeksForGeeks"; # Let us use m operator to search # "to Ge"$string =~ m/to Ge/; # Printing the Stringprint "Before: $`\n";print "Matched: $&\n";print "After: $'\n"; Before: Welcome Matched: to Ge After: eksForGeeks perl-operators Perl-String Perl-String-Operators Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl Tutorial - Learn Perl With Examples Perl | Basic Syntax of a Perl Program Perl | Inheritance in OOPs Perl | Opening and Reading a File Perl | Multidimensional Hashes Perl | Scope of Variables Perl | ne operator Perl | Hashes Perl | Data Types Perl | defined() Function
[ { "code": null, "e": 25315, "s": 25287, "text": "\n07 May, 2019" }, { "code": null, "e": 25816, "s": 25315, "text": "m operator in Perl is used to match a pattern within the given text. The string passed to m operator can be enclosed within any character which will be used as a d...
puts() vs printf() for printing a string - GeeksforGeeks
27 May, 2021 In C, given a string variable str, which of the following two should be preferred to print it to stdout? 1) puts(str); 2) printf(str); puts() can be preferred for printing a string because it is generally less expensive (implementation of puts() is generally simpler than printf()), and if the string has formatting characters like ‘%s’, then printf() would give unexpected results. Also, if str is a user input string, then use of printf() might cause security issues (see this for details). Also note that puts() moves the cursor to next line. If you do not want the cursor to be moved to next line, then you can use following variation of puts(). fputs(str, stdout) You can try following programs for testing the above discussed differences between puts() and printf(). Program 1 C // C program to show the use of puts#include <stdio.h>int main(){ puts("Geeksfor"); puts("Geeks"); getchar(); return 0;} Program 2 C // C program to show the use of fputs and getchar#include <stdio.h>int main(){ fputs("Geeksfor", stdout); fputs("Geeks", stdout); getchar(); return 0;} Program 3 C // C program to show the side effect of using// %s in printf#include <stdio.h>int main(){ // % is intentionally put here to show side effects of // using printf(str) printf("Geek%sforGeek%s"); getchar(); return 0;} Program 4 C // C program to show the use of puts#include <stdio.h>int main(){ puts("Geek%sforGeek%s"); getchar(); return 0;} Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. TusharSharma5 pamanbpl15 simmytarika5 C-Input and Output Quiz C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Function Pointer in C Substring in C++ fork() in C std::string class in C++ Enumeration (or enum) in C Command line arguments in C/C++ TCP Server-Client implementation in C Different methods to reverse a string in C/C++ Structures in C Exception Handling in C++
[ { "code": null, "e": 25759, "s": 25731, "text": "\n27 May, 2021" }, { "code": null, "e": 25865, "s": 25759, "text": "In C, given a string variable str, which of the following two should be preferred to print it to stdout? " }, { "code": null, "e": 25879, "s": 2586...
C# | How to change Title of the Console - GeeksforGeeks
28 Jan, 2019 Given the normal Console in C#, the task is to find the default value of Title and change it to something else. Approach: This can be done using the Title property in the Console class of the System package in C#. The title refers to the string to be displayed in the title bar of the console. The maximum length of the title string is 24500 characters. If the retrieved title is longer than 24500 characters in a get operation then it will give InvalidOperationException and f the retrieved title is longer than 24500 characters in a set operation then it will give ArgumentOutOfRangeException. Program 1: Finding the default Title // C# program to illustrate the// Console.Title Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Display current Title Console.WriteLine("Default Title: {0}", Console.Title); }}} Output: Program 2: Changing the Title to 100 // C# program to illustrate the// Console.Title Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; namespace GFG { class Program { static void Main(string[] args) { // Display current Title Console.WriteLine("Default Title: {0}", Console.Title); // Set the Title to GeeksForGeeks Console.Title = "GeeksForGeeks"; // Display current Title Console.WriteLine("Changed Title: {0}", Console.Title); }}} Output: CSharp-Console-Class C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Delegates C# | Abstract Classes Extension Method in C# C# | Replace() Method Difference between Ref and Out keywords in C# C# | Class and Object C# | String.IndexOf( ) Method | Set - 1 C# | Constructors Introduction to .NET Framework C# | Data Types
[ { "code": null, "e": 26802, "s": 26774, "text": "\n28 Jan, 2019" }, { "code": null, "e": 26914, "s": 26802, "text": "Given the normal Console in C#, the task is to find the default value of Title and change it to something else." }, { "code": null, "e": 27398, "s"...
Circular tour | Practice | GeeksforGeeks
Suppose there is a circle. There are N petrol pumps on that circle. You will be given two sets of data. 1. The amount of petrol that every petrol pump has. 2. Distance from that petrol pump to the next petrol pump. Find a starting point where the truck can start to get through the complete circle without exhausting its petrol in between. Note : Assume for 1 litre petrol, the truck can go 1 unit of distance. Example 1: Input: N = 4 Petrol = 4 6 7 4 Distance = 6 5 3 5 Output: 1 Explanation: There are 4 petrol pumps with amount of petrol and distance to next petrol pump value pairs as {4, 6}, {6, 5}, {7, 3} and {4, 5}. The first point from where truck can make a circular tour is 2nd petrol pump. Output in this case is 1 (index of 2nd petrol pump). Your Task: Your task is to complete the function tour() which takes the required data as inputs and returns an integer denoting a point from where a truck will be able to complete the circle (The truck will stop at each petrol pump and it has infinite capacity). If there exists multiple such starting points, then the function must return the first one out of those. (return -1 otherwise) Expected Time Complexity: O(N) Expected Auxiliary Space : O(1) Constraints: 2 ≤ N ≤ 10000 1 ≤ petrol, distance ≤ 1000 0 chintubhuarya752 days ago int sum=0, point=0; int i; for( i=0; i<n; i++) { sum+=p[i].petrol-p[i].distance; if(sum<0) { point=i+1; sum=0; } } int j=0; while(point<=n && j<point && j<n) { sum+=p[j].petrol-p[j].distance; j++; } if(sum<0) return -1; return point; 0 akashchourasiya84 days ago it is same as KEYDAN ALGO +1 sabaperween92 weeks ago TC=O(n) SC=O(1) int tour(int petrol[], int distance[]) { int n=petrol.length; int start=0; int end=1; int count=petrol[start]-distance[start]; while(start!=end||count<0){ while(count<0&&start!=end){ count-=petrol[start]-distance[start]; start=(start+1)%n; if(start==0) return -1; } count+=petrol[end]-distance[end]; end=(end+1)%n; } return start; } 0 rajneesh02012 weeks ago int tour(petrolPump p[],int n) { //Your code here int start=0; int end=1; int curr_pet=p[start].petrol - p[start].distance; while(end!=start || curr_pet<0) { while(curr_pet<0 and start !=end) { curr_pet -=p[start].petrol-p[start].distance; start=(start+1)%n; if(start==0) return -1; } curr_pet +=p[end].petrol-p[end].distance; end=(end+1)%n; } return start; } 0 masumasif112 weeks ago 896 25 46 83 68 15 65 35 51 44 9 88 79 77 85 89 for this input expected output is wrong +1 bhaskarmaheshwari83 weeks ago int remaining=0; int required=0; int start=0; for(int i=0;i<n;i++) { remaining=p[i].petrol-p[i].distance+remaining; if(remaining<0) { required+=remaining; start=i+1; remaining=0; } } if(remaining+required>=0) return start; return -1; +1 bhaskarmaheshwari83 weeks ago O(n^2) for(int i=0;i<n;i++) { int cnt=0; int start=i; int remaining=0; for(int j=i;j<n;j++) { if((p[j].petrol-p[j].distance+remaining)<0) break; remaining=(p[j].petrol-p[j].distance+remaining); cnt++; if(j==n-1&&cnt<n) { j=-1; } if(cnt==n) return start; } } return -1; 0 bhaskarmaheshwari8 This comment was deleted. +1 mishra07adi3 weeks ago C++ Sol class Solution{ public: //Function to find starting point where the truck can start to get through //the complete circle without exhausting its petrol in between. int tour(petrolPump p[],int n) { //Your code here int deficit = 0; int balance = 0; int start = 0; for(int i=0;i<n;i++){ balance += p[i].petrol - p[i].distance; if(balance < 0){ deficit+=balance; start = i+1; balance = 0; } } if(deficit + balance >= 0) return start; else return -1; } }; 0 ram9999mishra3 weeks ago Simple Java solution with 100 % case pass class Solution { //Function to find starting point where the truck can start to get through //the complete circle without exhausting its petrol in between. int tour(int petrol[], int distance[]) { int n = petrol.length; int deficit = 0; int balance = 0; int start = 0; for(int i=0;i<n;i++){ balance += petrol[i] - distance[i]; if(balance < 0){ deficit+=balance; start = i+1; balance = 0; } } if(deficit + balance >= 0) return start; else return -1; } } 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": 650, "s": 238, "text": "Suppose there is a circle. There are N petrol pumps on that circle. You will be given two sets of data.\n1. The amount of petrol that every petrol pump has.\n2. Distance from that petrol pump to the next petrol pump.\nFind a starting point where the truck...
Java Program to Use Exceptions with Thread - GeeksforGeeks
01 Dec, 2020 Exceptions are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program. When a method encounters an abnormal condition that it can not handle, an exception is thrown as an exception statement. Exceptions are caught by handlers(here catch block). Exceptions are caught by handlers positioned along with the thread’s method invocation stack. If the calling method is not prepared to catch the exception, it throws the exception up to its calling method and so on. So in the java program exception handlers should be positioned strategically, so the program catches all the exception from which the program want to recover. Lifecycle of a thread: The class implements a Thread class or Runnable interface then the extended class has start() method run the thread, sleep() methods cause the currently executing thread to sleep for the specified number of milliseconds, and many more. Prior to discussing the approaches, state. transactions of thread should be known to further deal with exceptions for better understanding. A thread in Java at any point in time exists in any one of the following states. A thread lies only in one of the shown states at any instant: NewRunnableBlockedWaitingTimed WaitingTerminated New Runnable Blocked Waiting Timed Waiting Terminated 1. A class name RunnableThread implements the Runnable interface which gives the run( ) method executed by the thread. The object of this class is now runnable 2. The Thread constructor is used to create an object of RunnableThread class by passing the runnable object as a parameter. 3. The start() method is invoked on the Thread object as it returns immediately once a thread has been spawned. 4. The thread ends when the run( ) method ends which is to be normal termination or caught exception. 5. Now in order to create a new thread runner = new Thread(this,threadName) ; 6. In order to start the new thread. runner. start() ; 7. public void run( ) is an overrideable method used to display the information of a particular thread. 8. Thread.currentThread().sleep(2000) is used to deactivate the thread until the next thread started execution or used to delay the current thread. Uncaught exception handler will be used to demonstrate the use of exception with thread. It is a specific interface provided by Java to handle exception in the thread run method. There are two methods to create a thread: Extend the thread Class (java.lang.thread)Implement Runnable Interface (java.lang.thread) Extend the thread Class (java.lang.thread) Implement Runnable Interface (java.lang.thread) 1. Exception and Exception handling with threads Here, a new thread is created in the class which is extending the thread class in which run() method is overridden. This invokes the entry point of the new thread created in the class which was extending the thread class. Further, start() method is used to start and run the thread in the program. Java // Java program to Use exceptions with thread // Importing Classes/Filesimport java.io.*; // Child Class(Thread) is inherited from parent Class(GFG)class GFG extends Thread { // Function to check if thread is running public void run() { System.out.println("Thread is running"); // Using for loop to iterate for (int i = 0; i < 10; ++i) { System.out.println("Thread loop running " + i); } } // Main Driver Method public static void main(String[] args) { // Try-catch block to detect exception try { // Creating new thread GFG ob = new GFG(); throw new RuntimeException(); } // Catch block to handle exception catch (Exception e) { // Exception handler System.out.println( "Another thread is not supported"); } }} Output: Another thread is not supported 2. Exception handling with sleep method(): sleep() method of thread class is used where there is a demand to sleep the thread for a particular period of time for the proper workflow of the code. Syntax: public static void sleep(long milliseconds) ; // generally used public static void sleep(long milliseconds, int nanoseconds) ; // used to illustrate the precision only Parameter: Name Action performed Return type: As seen in syntax itself, it does not return any value. Exception: It does often throws out exceptions as java language being involving the concept of multithreading IllegalArgumentException is thrown when the parametric value is negative as it is bounded as discussed between [0 — +999999]InterrupteException is thrown when a thread is interrupted with an ongoing thread as discussed java supports the concepts of multithreading. IllegalArgumentException is thrown when the parametric value is negative as it is bounded as discussed between [0 — +999999] InterrupteException is thrown when a thread is interrupted with an ongoing thread as discussed java supports the concepts of multithreading. Implementation: Java // Java program to Use exceptions with thread /* Note: Dont confuse main method with Main class*/ // Importing Classes/Filesimport java.io.*; // Child Class(Thread) is inherited// from parent Class(GFG)class GFG extends Thread { public void run() { System.out.println("Throwing in " + "MyThread"); throw new RuntimeException(); }} // Main driver methodpublic class Main { public static void main(String[] args) { GFG t = new GFG(); t.start(); // try block to deal with exception try { Thread.sleep(2000); } // catch block to handle the exception catch (Exception x) { // Print command when exception encountered System.out.println("Exception" + x); } // Print command just to show program // run successfully System.out.println("Completed"); }} Output: Throwing in MyThread Exception in thread "Thread-0" java.lang.RuntimeException at testapp.MyThread.run(Main.java:19) Completed Java-Exception Handling Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Iterate through List in Java
[ { "code": null, "e": 25347, "s": 25319, "text": "\n01 Dec, 2020" }, { "code": null, "e": 26053, "s": 25347, "text": "Exceptions are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program. When a...
What is the difference between a list and an array in C#?
An array stores a fixed-size sequential collection of elements of the same type, whereas list is a generic collection. To define a List − List<string7gt; myList = new List<string>(); To set elements in a list, you need to use the Add method − myList.Add("Audi"); myList.Add("BMW"); myList.Add("Chevrolet"); myList.Add("Hyundai"); To define Arrays − int[] arr = new int[5]; To initialize and set elements to Arrays − int[] arr = new int[5] {23, 14, 11, 78, 56};
[ { "code": null, "e": 1181, "s": 1062, "text": "An array stores a fixed-size sequential collection of elements of the same type, whereas list is a generic collection." }, { "code": null, "e": 1200, "s": 1181, "text": "To define a List −" }, { "code": null, "e": 1245, ...
CSS - margin-top
The margin-top property sets the width of the margin on the top of an element. length − Any length value. length − Any length value. percentage − The margin's width is calculated with respect to the width of the element's containing block. percentage − The margin's width is calculated with respect to the width of the element's containing block. auto − Default, Let the browsers automatically set the margin. auto − Default, Let the browsers automatically set the margin. All the HTML elements. object.style.marginTop = "5px" Here is the example − <html> <head> </head> <body> <p style = "margin-top: 15px; border:1px solid black;"> This is a paragraph with a specified top margin </p> <p style = "margin-top: 5%; border:1px solid black;"> This is another paragraph with a specified top margin in percent </p> </body> </html> This will produce following result − This is a paragraph with a specified top margin This is another paragraph with a specified top margin in percent 33 Lectures 2.5 hours Anadi Sharma 26 Lectures 2.5 hours Frahaan Hussain 44 Lectures 4.5 hours DigiFisk (Programming Is Fun) 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 51 Lectures 7.5 hours DigiFisk (Programming Is Fun) 52 Lectures 4 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2705, "s": 2626, "text": "The margin-top property sets the width of the margin on the top of an element." }, { "code": null, "e": 2732, "s": 2705, "text": "length − Any length value." }, { "code": null, "e": 2759, "s": 2732, "text": "lengt...
Sorting string characters by frequency in JavaScript
We are required to write a JavaScript function that takes in the string of characters as the only argument. Our function should prepare and a new string based on the original string in which the characters that appear for most number of times are placed first followed by number with decreasing frequencies. For example, if the input to the function is − const str = 'free'; Then the output should be − const output = 'eefr'; Since e appears twice it is placed first followed by r and f. The code for this will be − Live Demo const str = 'free'; const frequencySort = (str = '') => { let map = {} for (const letter of str) { map[letter] = (map[letter] || 0) + 1; }; let res = ""; let sorted = Object.keys(map).sort((a, b) => map[b] - map[a]) for (let letter of sorted) { for (let count = 0; count < map[letter]; count++) { res += letter } } return res; }; console.log(frequencySort(str)); The steps we took are − First, we prepared a hashmap of letter count First, we prepared a hashmap of letter count Then we sorted the map by count of letters Then we sorted the map by count of letters And finally, we generated res string from the sorted letter And finally, we generated res string from the sorted letter And the output in the console will be − eefr
[ { "code": null, "e": 1170, "s": 1062, "text": "We are required to write a JavaScript function that takes in the string of characters as the only argument." }, { "code": null, "e": 1370, "s": 1170, "text": "Our function should prepare and a new string based on the original string ...
How to Deploy a Telegram Bot using Heroku for FREE | by Haohui | Towards Data Science
Running your telegram bot locally suffices for simple applications. However, if you wanted to scale up your bot and enable others to use your bot even when you are not running the bot locally, you will need to go one step further to deploy the bot. In this tutorial, I will be going through how to deploy a telegram bot you have created using the python-telegram-bot library with Heroku. What’s even better is that we can do this completely for free! Forget about all the fees you incur from other hosting options, Heroku will mostly likely suffice for your needs, without you having to pay a single cent nor enter your credit card details. In order to do so, I will use a simple starter script taken from the examples in the python-telegram-bot Github repository where the bot simply echos whatever the user sends. You may have a different script, but I will show you which sections to modify in order to deploy the bot using Heroku. If you want to go straight to the files needed, head over to this Github repository to download them! This is our starting point: Firstly, we will modify how the bot fetches new data. The python-telegram-bot script uses polling instead of webhooks to fetch new data. For simple testing purposes, polling is sufficient because it’s simple to implement. However, the disadvantage of polling is that it is inefficient and the data it fetches is always old and never real-time. This is because polling sends a request at a predetermined frequency to detect any changes in the data, meaning it constantly checks if the data is modified, instead of being “notified” when a change is made to the data. On the other hand, webhooks act like push notifications. Rather than fetching information, webhooks are triggered when the data is modified. This allows for realtime information and also makes it much more efficient because there is no need to continuously send requests to check for data. We first import os, and then set the port number to listen in for the webhook. import osPORT = int(os.environ.get('PORT', 5000)) Next, we modify the following line from updater.start_polling() to updater.start_webhook(listen="0.0.0.0", port=int(PORT), url_path=TOKEN)updater.bot.setWebhook('https://yourherokuappname.herokuapp.com/' + TOKEN) What this is doing is that it changes the polling method to webhook, listening in to 0.0.0.0 with the port you specified above with the PORT variable. The token refers to the API token of your telegram bot, which should be defined at the top of the code. The next line is to set the Webhook with the link to your heroku app, which we will get to next. With all the changes to the python file, it should look similar to this (with your own Telegram bot token): We are done with editing the python-telegram-bot script, except for changing the name of your heroku app which we will get into soon. In order for heroku to recognise the following as a python app, you need the following files in the same directory: bot.pyProcfilerequirements.txt The python code should be inside the bot.py file, and I will go through the process to create the Procfile and requirements.txt. First, change the directory of your terminal / command prompt to the same directory containing your python script. Then, create a requirements.txt file containing the following line: python-telegram-bot==12.7 This is needed to tell heroku which libraries it needs to install in order to execute the code. Assuming you are using the sample code above, the only library you need is python-telegram-bot, and the version we are using is 12.7. If you are importing other libraries to run your python code, be sure to include the other libraries as well in the requirements.txt file. Next, you need a Procfile. The procfile declares the process type followed by the command, in the format <process type>: <command>. Here, we are using the web process type, which receives external HTTP traffic from Heroku’s routers. The command is python3 bot.py, which tells Heroku to execute the python file as you normally would with a python file locally. So your Procfile should contain the line: web: python3 bot.py Make sure that the Procfile does not have any file extension like .txt behind it, because it won’t work. With the three files in the same directory, we will now create the Heroku Webapp. Login / create a Heroku account.Install the Heroku CLI. If you do not have Git installed, first install Git before proceeding with the Heroku CLI.Once installed, you can use the heroku command in your terminal / command prompt. Go to the same directory as your python files, and type: Login / create a Heroku account. Install the Heroku CLI. If you do not have Git installed, first install Git before proceeding with the Heroku CLI. Once installed, you can use the heroku command in your terminal / command prompt. Go to the same directory as your python files, and type: heroku login A new window will be opened in your browser prompting you to login, so just click on the button. 4. Once you are logged in, go back to the command line. Type in heroku create to create your new webapp. Here, heroku will assign your webapp a name as well as the link to your webapp, which should be of the format https://yourherokuappname.herokuapp.com/. Paste the URL into the bot.py code, for the line updater.bot.setWebhook('https://yourherokuappname.herokuapp.com/' + TOKEN) With all the changes to your bot.py file, it should look similar to this (with your own Telegram bot token and heroku app name, of course): 5. Next, in your command line, type in git initgit add .git commit -m "first commit"heroku git:remote -a YourAppNamegit push heroku master The first line creates a new Git repository. The second line then tells Git that you want to include updates to a particular file in the next commit. The third line then commits the changes. In the fourth line, change “YourAppName” to the name of your heroku app. Lastly, the fifth line pushes everything to the server. You should then see the following messages: In particular, it will say that a Python app is detected and it will install the required libraries in the requirements.txt file using pip. Then, it will read the Procfile which specifies that the bot.py file is to be executed. So that’s it! Once it finishes executing, you can simply head over to Telegram and message /start to your bot. It should now behave as you expect it to. Since you are using the free plan on heroku, the bot will sleep after 30 minutes of inactivity. So do expect the bot to take a few seconds to respond to your /start if you are using it more than 30 minutes after it was previously used. Other than that, the bot will respond almost instantaneously~ I’ve noticed that the bot stops responding after about 24 hours of inactivity (because we are using the free version of Heroku), so if you want to “jolt” the bot awake, one way is to make a change to one of the files (eg. changing the python3 in the procfile to python and vice versa) and then committing the changes with the lines below: git add .git commit -m "changing python3 to python in Procfile"git push heroku master You should see again see the messages about a Python app being detected and once it finishes executing, your bot should revive now!
[ { "code": null, "e": 420, "s": 171, "text": "Running your telegram bot locally suffices for simple applications. However, if you wanted to scale up your bot and enable others to use your bot even when you are not running the bot locally, you will need to go one step further to deploy the bot." }, ...
10 Of My Favorite Python Decorators | by Emmett Boudreau | Towards Data Science
If there is one thing that really fascinates me in computing, it is programming languages. Programming languages are interesting to me because of what they actually are, merely just an abstraction layer from the hardware. And the way that us humans have found to interact with the hardware from these abstraction layers is truly amazing. We wanted to work with something very human: words, relationships, and things; we emulated our brain’s process of definition inside of a computer. While this is similar with hardware programming, I think that these layers of abstraction really make the language interesting because there are all sorts of ways to handle different scenarios and your types with those scenarios that it is very interesting to see the kind of ideas people come up with. This fascination I think grows even more whenever we are talking about a very declarative scripting language — in this case, Python. The great thing about a language like Python is that it is declarative because of abstraction. The language is incredibly easy to use, and all of the underlying hardware and kernel calls are kept very far away from the programmer. But with that much abstraction from the pushes and pops happening underneath, it is really cool to see how syntax can be manipulated to work with those types. In a previous article, I dove into multiple dispatch in Python. The multiple dispatch module uses a simple decorator to turn the language of Python into a multiple dispatch. If you would like to read more about that, the article is here: towardsdatascience.com By the way, I LOVE polymorphism. But writing that article, and exploring that package a bit did get my brain started on decorators again — and I suppose that is for a good reason... Decorators are awesome! They are so useful in so many different scenarios, and they are incredibly easy to use. Another awesome article I wrote, which mirrors this one — and can be considered a precursor of sorts is an article where I detailed 10 awesome Python decorators I like to use, if you would like to read that as well, here is a link: towardsdatascience.com Given the awesome nature of Python decorators, and what they are capable of, I considered it very apt to go about writing a new story with some new incredible decorators to use in your Python code. A lot of these bend the Python paradigm, and can really work to take your Python code to the next level! The decorators on this list are not included on the last, so if you would like to double up, you could read them both for some pretty desirable decorators in your arsenal. Also, there will be a notebook with all of the code and decorators I used in this article on Github at this link: github.com No surprise here, I do have an article I just wrote where I went into the multiple dispatch module and what it is capable of. Needless to say, as I tend to voice my multiple dispatch opinion and my Julia opinion quite loudly, if there is one thing I love it is multiple dispatch. It seems like a very natural way to program that does not really get in the way. I often miss this very Julian programming concept whenever I write Python, so stumbling across this package was a very big delight. Before I go into how to use this decorator, let us first discuss the what and why of multiple dispatch. Firstly, multiple dispatch is a function and type system that allows methods to be listed by their type counter-parts. Typically, in an object-oriented approach all Pythonic functions would be defined within the scope of a Python class. This is basically the definition of object-oriented programming. However, one of the things that makes Python so much more of a usable language is that it does not force one to use this paradigm. A lot of Data-Science code is very methodized in the Pythonic ecosystem, with a lot less of a focus on types in a lot of ways than someone might expect after first hearing the language was “ object-oriented.” I think that polymorphism through multiple dispatch can really take that methodization to the next level. This is even the case within a class, as well, as we will see in my example. The reason why I recommend using this decorator in some instances is because it is just one simple call that can change the code substantially, and make for some pretty great syntax. Let us consider the following example: from multipledispatch import dispatchclass Pasta: def __init__(self, width, height, classification): self.width, self.height = width, height self.classification = classification def classify(): if self.width > 3 and height < 2: self.classification = "Linguine" elif self.width == self.height and self.width < 3: self.classification = "Spaghetti" elif width > 2 and height == 1: self.classification = "Fettuccine" else: self.classification = "Dough"class Bread: def __init__(self, width, height, classification): self.width, self.height = width, height self.classification = classification def classify(): if self.width > 3 and height < 2: self.classification = "Pizza Crust" elif self.width == self.height and self.width < 3: self.classification = "White bread" elif width > 2 and height == 1: self.classification = "Flatbread" else: self.classification = "Dough"class Roller: def __init__(self): pass def roll_thinner(x : Pasta): x.height -= 1 x.width += 1 x.classify() def cut(x : Pasta): x.width -= 1 x.classify() def fold(x : Pasta): x.width += 1 x.classify() We have 3 classes to work with here. The first object is Pasta, which is just pasta that can be rolled out using our rolling pin (Roller.) The next is Bread. Bread has many of the same attributes of Pasta. However, for this example, we have one thing that is missing from the bread class, the only problem is that if we include this value — then none of the Roller functions are going to work on the bread! In a normal event, there would have to either be new functions that work exclusively with this type, so we would have for example roll_thinnerbread() and roll_thinnerpasta() respectively, or there would need to be a second rolling pin that we only use for bread, say class BreadRoller: With multiple dispatch, however, these worries can be gone — we can use multiple dispatch to handle types differently from function to function. In this example, I am only going to be changing one function name in the Bread class. I am just going to change the name of the classify() function to now be bake(). There is also this function I made, which will spit out a new object for us with some preset “ dough” settings: def make_dough(pasta = False): if pasta: return(Pasta(10, 10, "Dough")) else: return(Bread(10, 10, "Dough")) Let’s make some dough! dough = make_dough()print(dough.classification)'Dough' We will also make some pasta dough: pasta_dough = make_dough(pasta = True) Now let us roll out our pasta into a nice linguine, which we will serve alongside our pizza crust dough that we just created. rollingpin = Roller()while pasta_dough.height >= 3: rollingpin.roll_thinner(pasta_dough)while pasta_dough.width > 2: rollingpin.cut(pasta_dough)print(pasta_dough.classification)Linguine Great! We made some linguine! But watch all of this fall apart because our other type has a slightly different structure: rollingpin.roll_thinner(dough)---------------------------------------------------------------------------AttributeError Traceback (most recent call last)<ipython-input-132-b755ead4a785> in <module>----> 1 rollingpin.roll_thinner(dough)<ipython-input-118-1af4dc2d94f2> in roll_thinner(self, x) 5 x.height -= 1 6 x.width += 1----> 7 x.classify() 8 def cut(self, x : Pasta): 9 x.width -= 1AttributeError: 'Bread' object has no attribute 'classify' Oh no! I was really looking forward to that pizza... Fortunately, we can now show off multiple dispatch by altering the functions in our rolling pin class to take both types. We will do so by simply cloning the functions, changing what needs to be changed, then using the dispatch decorator to make this code only execute when the correct type is passed, like so: class Roller: def __init__(self): pass @dispatch (Pasta) def roll_thinner(self, x : Pasta): x.height -= 1 x.width += 1 x.classify() @dispatch (Pasta) def cut(self, x : Pasta): x.width -= 1 x.classify() @dispatch (Pasta) def fold(self, x : Pasta): x.width += 1 x.classify() @dispatch (Bread) def roll_thinner(self, x : Bread): x.height -= 1 x.width += 1 x.bake() @dispatch (Bread) def cut(self, x : Bread): x.width -= 1 x.bake() @dispatch (Bread) def fold(self, x : Bread): x.width += 1 x.bake()rollingpin.roll_thinner(dough) Now this code executes. Needless to say, this can be pretty convenient in many different types of scenarios! Personally, I find multiple dispatch to be a very obvious way to program. It can be very flexible and create some pretty brilliant syntax. What is better is that it is so easy to do with this decorator, given that — I would highly recommend! Celery is a must-have when it comes to working with tasks in Python. Celery is essentially a task manager for Python. It can keep track of task queues, which are operations at which a series of computers or threads are to perform next. The word queue in the computing world should always apply a first in, first out mentality to the data. To put it into a more metaphorical since, we are stacking pancakes but we eat the one on bottom first. The only problem with Celery is that it would be particularly hard to demonstrate. In order to work with this library, I would need to have a production server at my disposal for it to work with. Of course, I do not have this, but I did end up using Celery several times in the past. Here is a basic example of creating tasks with Celery, from the documentation: from celery import Celeryapp = Celery('tasks', broker='pyamqp://guest@localhost//')@app.taskdef add(x, y): return x + y Needless to say, Celery is incredibly easy to use. Just make a Celery stalk class and then use decorators to queue up your tasks. Available servers from the broker will then take on the tasks. Click is another module that I think is really awesome. Click helps Python developers build Command Line Interfaces, or CLI’s. The greatest thing about this is that it can be used to provide CLA’s, or command line arguments to Python. Of course, this is not going to land very well in my Notebook, but regardless, I thought maybe it would still be a substantial tool to add to one’s arsenal. The following is an example that will greet someone after parsing their name as a CLI: import click@click.command()@click.option("--name", prompt="Your name", help="The person to greet.")def hello(count, name): click.echo(f"Hello, {name}!")if __name__ == '__main__': hello() Click is pretty cool because in a lot of ways it works like bash code alongside your Python. However, the advantage to doing that with Click is also that the code will work on a lot more than just Unix-like operating systems. Deprecations can be extremely annoying to carry out. You want to get rid of a function, but everyone is still trying to use it. In a normal case, you might have to type a little bit of code in order to create your deprecation warning. For this, we would use the module warn: warnings.warn( "this function is deprecated... etc.", DeprecationWarning ) However, using deprecated, we only really need to do one thing with one simple call. We call this over our function as a decorator and instantly deprecation warnings can be given. from deprecated import deprecated@deprecated ("This function is deprecated, please do not make dough here")def make_dough(pasta = False): if pasta: return(Pasta(10, 10, "Dough")) else: return(Bread(10, 10, "Dough")) Now when we try to run this function, we will get a deprecation warning: z = make_dough() Now everyone trying to use this function will know there is no dough allowed! Deco is a parallel computing module for Python. If you were around for the last list I did of decorators, I mentioned a package called Numba. Numba can both JIT-compile, and GPU-compile Python software. Deco is a lot like Numba, but allows for synchronous and concurrent processes. For now, we are taking a look specifically at the concurrent decorator. The concurrent option uses multiprocessing.pool to make things concurrent. This is then used with another decorator to run the function inside of a thread in the background while continuing to take care of the function. Let us take a look at a simple use of the concurrent function on our pasta roller from earlier. from deco import concurrent, synchronizeddef roll_linguine(count : int): rollingpin = Roller() pastas = [] for i in range(0, count): dough = make_dough(pasta = True) while dough.height >= 3: rollingpin.roll_thinner(dough) while dough.width > 2: rollingpin.cut(dough) pastas.append(dough) return(pastas) I also made an equivalent for pizza!: def roll_pizzas(count : int): rollingpin = Roller() pizzas = [] for i in range(0, count): dough = make_dough() while dough.height > 3: rollingpin.roll_thinner(dough) while dough.width > 2: rollingpin.cut(dough) In order to now make these functions concurrent, we simply add the decorator: @concurrentdef roll_linguine(count : int): rollingpin = Roller() pastas = [] for i in range(0, count): dough = make_dough(pasta = True) while dough.height >= 3: rollingpin.roll_thinner(dough) while dough.width > 2: rollingpin.cut(dough) pastas.append(dough) return(pastas)@concurrentdef roll_pizzas(count : int): rollingpin = Roller() pizzas = [] for i in range(0, count): dough = make_dough() while dough.height > 3: rollingpin.roll_thinner(dough) while dough.width > 2: rollingpin.cut(dough) I am afraid we have made a mistake in our pizza and linguine endeavors prior... Unfortunately, we are going to have over 500 guests this evening! We will need to make a lot of pizza and linguine if we want to ensure that every guest is going to get fed. Each guest needs 2 pizzas (I invited the pizza enthusiast convention,) and at least 20 linguine noodles (pizza lovers are also pasta lovers in most cases.) Fortunately, since the two functions I have used for those two abilities are concurrent, I can synchronize them using the synchronized decorator from deco! # linguine e pizza? molta bellisima!@synchronizeddef prepare_meal(count : int): roll_linguine(count * 200) roll_pizzas(count * 2)%timeit prepare_meal(500) The pizza/pasta factory has quite a bit of fan noise, but the good news is this all ran — albeit with my deprecation warning from earlier IN EACH CONSECUTIVE LOOP, completely ruining my output. Cache tools is another great package for helping your Python performance. Packages like that are great because they really do make the Python experience a lot better. Really well written Python code can be pretty fast, but the reality is that we are in a scripting language. We need as much performance as we can get. Additionally, we cannot always write flawless code! That in mind, let us take a look at another decorator which will enhance the performance of our Python package! The decorator is called cached, and it can take a lot of different arguments to change what type of cache is used, and the possible sizes of those caches. All of this will also come in handy for our little linguine/pizza business we have started. As this function can be used to store previous calculations for future calls. The good news is that this means we can now have our pizza rollers get really good at rolling pizzas, but they still get tired after they roll out 100 of them, or whatever the set amount will be. from cachetools import cached, LRUCache, TTLCache We can provide a cache key-word argument in order to determine what kind of cache to use. One thing to note is that these caches all behave in different ways. If you are using this code for a large application that will likely have a lot of these, but you do not want your cache to be overwritten for the time it is worked with, you might want to use TTL cache. This cache disappears after 10 minutes, but will not be overwritten. LRU cache on the other hand can be overwritten, but can last forever — it is better choice for general purpose use cases. There is also a version that does not have the arguments that will work similarly to LRU I believe, just might use some other algorithm — to confess, I am not entirely sure. Tomorrow is yet another library that can be used to speed up the performance of the Python programming language. The decorator for this is called threads. It can be called with a positional argument to indicated how many threads we would like to dedicate to the task, and then we can set key-word arguments — for example, timeouts. from tomorrow import threads@threads(5)def prepare_meal(count : int): roll_linguine(count) roll_pizzas(count) And here is an example using the timeout key-word argument: @threads(5, timeout = 1)def prepare_meal(count : int): roll_linguine(count) roll_pizzas(count) Tenacity is a more unique package that can be used to try something again in the case that some code does not execute properly. It can be used with in-development software, or perhaps with requests if they do not get fulfilled. There are hundreds of uses for such a thing, and what is great is that because it is wrapped into this decorator, it can be used incredibly easily! Given the nature of this package, the only way I could think up a demonstration in a notebook was to have a throw with a print. from tenacity import retry@retrydef ohno(): print("function ran once") try: 2 == 3 - 5 == 6 except ValueError: print("Idk what that was even meant to do")ohno() Whenever I ran this, it ran once and then crashed my kernel, that being said — I then retried it outside of the notebook — so there is something to note about this package, this is not so usable in the notebook. The final module decorator we are going to look at is going to be the property decorator. This one is from the standard library, and the decorator portion is used to turn a method into a “ getter” for a read-only attribute of the same name. In other words, we are simply making this attribute a read-only copy of the prior attribute. class PowerLine: def __init__(self): self._voltage = 100000 @property def voltage(self): return self._voltage Decorators are quite an awesome feature in the Python programming language. They are particularly awesome because they can be used to change the way that a given type interacts with the methods around it. I find this to be very exciting personally. Another great thing about decorators is that they can often speed up Python, which I believe to be quite desirable given Python’s scripted nature. Hopefully armed with this list of decorators your Python functions will speed up and change! Thank you very much for reading my article, it means the world! I hope some of these decorators make you a better Pythonista!
[ { "code": null, "e": 835, "s": 47, "text": "If there is one thing that really fascinates me in computing, it is programming languages. Programming languages are interesting to me because of what they actually are, merely just an abstraction layer from the hardware. And the way that us humans have fo...
Ruby | Keywords - GeeksforGeeks
26 Oct, 2018 Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects or as constants. Doing this may result in compile-time error. Example: # Ruby program to illustrate Keywords #!/usr/bin/ruby # here 'if' is a keyword# it can't be used as variableif = 20 # Here 'if' and 'end' are keywords. # if condition to check whether # your age is enough for voting if if >= 18 puts "You are eligible to vote."end Compile Time Error: Error(s), warning(s): source_file.rb:7: syntax error, unexpected ‘=’if = 20^source_file.rb:12: syntax error, unexpected >=if if >= 18^source_file.rb:14: syntax error, unexpected keyword_end, expecting end-of-input There are total 41 keywords present in Ruby as shown below: Example: # Ruby program to illustrate the use of Keywords #!/usr/bin/ruby # defining class Vehicle # using the 'class' keywordclass GFG # defining method # using 'def' keyworddef geeks # printing result puts "Hello Geeks!!" # end of the method # using 'end' keywordend # end of class GFG # using 'end' keywordend # creating object obj = GFG.new # calling method using object obj.geeks Output: Hello Geeks!! Reference: http://ruby-doc.org/docs/keywords/1.9/Object.html Ruby-Basics Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Ruby | Array slice() function Ruby | Array select() function Global Variable in Ruby Ruby | Enumerator each_with_index function Include v/s Extend in Ruby Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1 Ruby | String gsub! Method Ruby | Numeric round() function Ruby | Types of Iterators Ruby | Array count() operation
[ { "code": null, "e": 23706, "s": 23678, "text": "\n26 Oct, 2018" }, { "code": null, "e": 23975, "s": 23706, "text": "Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not ...
Loop Optimization in Compiler Design - GeeksforGeeks
21 Nov, 2019 Loop Optimization is the process of increasing execution speed and reducing the overheads associated with loops. It plays an important role in improving cache performance and making effective use of parallel processing capabilities. Most execution time of a scientific program is spent on loops. Loop Optimization is a machine independent optimization. Decreasing the number of instructions in an inner loop improves the running time of a program even if the amount of code outside that loop is increased. Loop Optimization Techniques: Frequency Reduction (Code Motion):In frequency reduction, the amount of code in loop is decreased. A statement or expression, which can be moved outside the loop body without affecting the semantics of the program, is moved outside the loop.Example:Initial code: while(i<100) { a = Sin(x)/Cos(x) + i; i++; } Optimized code: t = Sin(x)/Cos(x); while(i<100) { a = t + i; i++; } Loop Unrolling:Loop unrolling is a loop transformation technique that helps to optimize the execution time of a program. We basically remove or reduce iterations. Loop unrolling increases the program’s speed by eliminating loop control instruction and loop test instructions.Example:Initial code: for (int i=0; i<5; i++) printf("Pankaj\n"); Optimized code: printf("Pankaj\n"); printf("Pankaj\n"); printf("Pankaj\n"); printf("Pankaj\n"); printf("Pankaj\n"); Loop Jamming:Loop jamming is the combining the two or more loops in a single loop. It reduces the time taken to compile the many number of loops.Example:Initial Code: for(int i=0; i<5; i++) a = i + 5; for(int i=0; i<5; i++) b = i + 10; Optimized code: for(int i=0; i<5; i++) { a = i + 5; b = i + 10; } Frequency Reduction (Code Motion):In frequency reduction, the amount of code in loop is decreased. A statement or expression, which can be moved outside the loop body without affecting the semantics of the program, is moved outside the loop.Example:Initial code: while(i<100) { a = Sin(x)/Cos(x) + i; i++; } Optimized code: t = Sin(x)/Cos(x); while(i<100) { a = t + i; i++; } Example: Initial code: while(i<100) { a = Sin(x)/Cos(x) + i; i++; } Optimized code: t = Sin(x)/Cos(x); while(i<100) { a = t + i; i++; } Loop Unrolling:Loop unrolling is a loop transformation technique that helps to optimize the execution time of a program. We basically remove or reduce iterations. Loop unrolling increases the program’s speed by eliminating loop control instruction and loop test instructions.Example:Initial code: for (int i=0; i<5; i++) printf("Pankaj\n"); Optimized code: printf("Pankaj\n"); printf("Pankaj\n"); printf("Pankaj\n"); printf("Pankaj\n"); printf("Pankaj\n"); Example: Initial code: for (int i=0; i<5; i++) printf("Pankaj\n"); Optimized code: printf("Pankaj\n"); printf("Pankaj\n"); printf("Pankaj\n"); printf("Pankaj\n"); printf("Pankaj\n"); Loop Jamming:Loop jamming is the combining the two or more loops in a single loop. It reduces the time taken to compile the many number of loops.Example:Initial Code: for(int i=0; i<5; i++) a = i + 5; for(int i=0; i<5; i++) b = i + 10; Optimized code: for(int i=0; i<5; i++) { a = i + 5; b = i + 10; } Example: Initial Code: for(int i=0; i<5; i++) a = i + 5; for(int i=0; i<5; i++) b = i + 10; Optimized code: for(int i=0; i<5; i++) { a = i + 5; b = i + 10; } Compiler Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Construction of LL(1) Parsing Table Introduction of Lexical Analysis Flex (Fast Lexical Analyzer Generator ) C program to detect tokens in a C program Introduction of Compiler Design Layers of OSI Model ACID Properties in DBMS Types of Operating Systems TCP/IP Model Page Replacement Algorithms in Operating Systems
[ { "code": null, "e": 24096, "s": 24068, "text": "\n21 Nov, 2019" }, { "code": null, "e": 24392, "s": 24096, "text": "Loop Optimization is the process of increasing execution speed and reducing the overheads associated with loops. It plays an important role in improving cache perf...
C | Structure & Union | Question 4 - GeeksforGeeks
28 Jun, 2021 Consider the following C declaration struct { short s[5]; union { float y; long z; }u; } t; Assume that objects of the type short, float and long occupy 2 bytes, 4 bytes and 8 bytes, respectively. The memory requirement for variable t, ignoring alignment considerations, is (GATE CS 2000) (A) 22 bytes(B) 14 bytes(C) 18 bytes(D) 10 bytesAnswer: (C)Explanation: Short array s[5] will take 10 bytes as size of short is 2 bytes. When we declare a union, memory allocated for the union is equal to memory needed for the largest member of it, and all members share this same memory space. Since u is a union, memory allocated to u will be max of float y(4 bytes) and long z(8 bytes). So, total size will be 18 bytes (10 + 8).Quiz of this Question C-Structure & Union Structure & Union C Language C Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Multidimensional Arrays in C / C++ rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ fork() in C Command line arguments in C/C++ Compiling a C program:- Behind the Scenes Operator Precedence and Associativity in C C | File Handling | Question 1 C | Misc | Question 7 Output of C programs | Set 64 (Pointers)
[ { "code": null, "e": 23934, "s": 23906, "text": "\n28 Jun, 2021" }, { "code": null, "e": 23971, "s": 23934, "text": "Consider the following C declaration" }, { "code": "struct { short s[5]; union { float y; long z; }u; } t;", "e": 24055, ...
rmdir - Unix, Linux Command
rmdir - remove empty directories rmdir [OPTION]... DIRECTORY... Remove the DIRECTORY(ies), if they are empty. Example-1: rmdir command will delete the empty directories. i.e directory without any sub-directories or files: $ rmdir test Example-2: To Delete Nested Empty Directories in Linux: $ rmdir -p dir1/dir2/dir3 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10610, "s": 10577, "text": "rmdir - remove empty directories" }, { "code": null, "e": 10641, "s": 10610, "text": "rmdir [OPTION]... DIRECTORY..." }, { "code": null, "e": 10688, "s": 10641, "text": "Remove the DIRECTORY(ies), if they are em...
Kubernetes - Taint and Toleration - GeeksforGeeks
18 Oct, 2021 A pod is a group of one or more containers and is the smallest deployable unit in Kubernetes. A node is a representation of a single machine in a cluster (we can simply view these machines as a set of CPU and RAM). A node can be a virtual machine, physical machine in a data center hosted on a cloud provider like Azure. When a user runs the below-given pod creation command then the request is sent to the API server. The scheduler is always watching the API server for new events, it identified the unassigned pods and decides which node it should choose to deploy this pod based on various factors like Node selector, Taints/Tolerations, Node Affinity, CPU and memory requirements, etc. Once Node is decided and send to API server then kubelet make sure that pod is running on the assigned node. kubectl (client ): kubectl create -f <pod-yaml-file-path> Nodes with different Hardware: If you have a node that has different hardware (example: GPU ) and you want to schedule only the pods on it which need GPU. Example: Consider there are 2 applications APP 1: A simple dashboard application and APP 2: A data-intensive application both has different CPU and memory requirements. APP1 does not requires much memory and CPU whereas APP 2 needs high memory and CPU (GPU machine ). Now with help of taints and tolerations + Node affinity, we can make sure that APP 2 is deployed on a node that has high CPU and memory, while APP1 can be scheduled on any Node with low CPU and Memory. Limit the number of pods in a node: If you want a node to schedule a certain number of pods to reduce the load on that node then Taints/Tolerations + Node Affinity can help us achieve it. Example: Consider there is pod which consists a database application which needs to be fast in queries the data and highly available. So, we will dedicate a node with high memory and CPU for this pod. Now the node will have only one pod in it, which makes it more fast and efficient to use node resources. Node affinity makes sure that pods are scheduled in particular nodes. Taints are the opposite of node affinity; they allow a node to repel a set of pods. Toleration is applied to pods, and allows (but does not require) the pods to schedule onto nodes with matching taints. Let’s understand this with an example: Consider there is a Person N1 and Mosquito P1. Taint Example: Person N1 applied a repellent (taint) so now Mosquito P1 won’t be able to attack Person N1. Now Let’s suppose there is Wasp P2 which tries to attack Person N1 Toleration Example: Wasp P2 is tolerant to repellent, hence has no effect and a Person N1 would be attacked. Here 2 things decide whether a mosquito or wasp can land on a person: Taint (Repellent ) of the Mosquito P1 and Tolerance of the Wasp P2 In the Kubernetes world, Persons correspond to Nodes, and the Mosquito, Wasp correspond to Pods. Case 1: Taint Node 1 (Blue) Since Pods are not tolerated so none of them would be scheduled on node 1 Node 1 is a taint to blue Case 2: We add tolerance to pod D. Now only Pod D will be able to schedule on Node 1 Pod D tolerant to taint blue Taints are a property of nodes that push pods away if they are not tolerate to node taint. Like Labels, multiple taints can be applied to a node. How can we enable certain pods to be scheduled on tainted nodes ? By specifying which pods are tolerant to specific taint; we add tolerations to certain pods. Tolerations are set to pods, and allow the pods to schedule onto nodes with matching taints. Taints and tolerations have nothing to do with security. Syntax: kubectl taints nodes node-name key=value:taint-effect Taint-effect: NoSchedule: Pods will not be scheduled on the node unless they are tolerant. This means If taint is applied on a node that already contains pods then all the existing pods which do not match the taint will be evicted from the node. No more new pods are scheduled on this node if it doesn’t match all the taints of this node. PreferNoSchedule: Scheduler will prefer not to schedule a pod on taint node but no guarantee. Means Scheduler will try not to place a Pod that does not tolerate the taint on the node, but it is not required. NoExecute: As soon as, NoExecute taint is applied to a node all the existing pods will be evicted without matching the toleration from the node. Currently, none of the pods is tolerant to blue. No taint on nodes Pod D YAML file : Line 1-2 : v1 of Kubernetes Pod API. By kind, Kubernetes knows which component to create. Line 3-4: metadata provides info that does not influence how the pod behaves, it is used to define the name of the pod and few labels(which will be used later by controllers ) Line 5: spec we define containers here. The pod can have multiple containers Line 6-8: container name here is redis-container, image Redis will be pull from the container registry. Line 7: operator default value is Equal. A toleration “matches” a taint if the keys are the same and the effects are the same, and: operator = Exists (in which case no value should be specified). operator = Equal and the values are equal. If keys are empty and the operator exists then it matches all the keys and values (i.e will tolerate everything effect is the type of taint-effect, here we chose NoSchedule effect Now taint node 1 to blue kubectl taint nodes node1 app=blue:NoSchedule Here, node1 –> name of the node on which taint will be applied. The app=blue:NoSchedule –> key-value pair : Type of taint effect. This means that no pod will be able to schedule onto node1 unless it has matching toleration. Pod C will be evicted from Node 1, as it is not tolerant to taint blue. Pod C evicted In the above example, Node D was scheduled on Node 1. What if it was scheduled on another node? Is it possible ? Yes Taints/Tolerations + Node Affinity = Assures that a specific pod can only schedule on a specific node only and No other pods can be scheduled in tainted nodes.Example o Note: The master node does not have any pods in it. Because when cluster is created the Kubernetes taints its master node so no pods are scheduled on master node. kubectl describe node kubemaster | grep Taints Output: Picked TrueGeek-2021 Kubernetes TrueGeek Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Product Based Companies What is "network ID" and "host ID" in IP Addresses? What is Transmission Control Protocol (TCP)? How to Replace Values in Column Based on Condition in Pandas? How to Fix: SyntaxError: positional argument follows keyword argument in Python How to redirect to another page in ReactJS ? How to remove duplicate elements from JavaScript Array ? Basics of API Testing Using Postman SQL Statement to Remove Part of a String Types of Internet Protocols
[ { "code": null, "e": 24571, "s": 24543, "text": "\n18 Oct, 2021" }, { "code": null, "e": 24894, "s": 24571, "text": "A pod is a group of one or more containers and is the smallest deployable unit in Kubernetes. A node is a representation of a single machine in a cluster (we can ...
D3.js | Path.moveTo() Function - GeeksforGeeks
11 Apr, 2022 D3.js is mostly used for making of graph and visualizing data on the HTML svg elements. D3 somehow is related to Data Driven Documents. The Path.moveTo() function is used to move a point inside the svg element. This library is also capable enough to draw simulations, 2D graphs and 3D graphs and used for producing dynamic, interactive data visualizations. It makes use of Scalable Vector Graphics i.e SVG elements. This library mostly works with svg vectors. Syntax: Path.moveTo(x,y) Parameters: This function accepts two parameter as mentioned above and described below: X: This parameter the x-position of the element. Y: This parameter the y-position of the element. Below example illustrate the Path.moveTo() function in D3.js: Example 1: Javascript <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <style> h1 { color: green; } div { display: inline-block; } svg{ background-color: #f2f2f2; } .path1{ stroke: #000; } .path2{ stroke: green; } .path3{ stroke: #000; } </style> <body> <center> <div> <h1>GeeksforGeeks</h1> <b>D3.js | Path.moveTo() Function</b> <br> <svg width="100" height="100"> <path class="path1"> </svg> <svg width="100" height="100"> <path class="path2"> </svg> <svg width="100" height="100"> <path class="path3"> </svg> </div> <script src ="https://d3js.org/d3.v4.min.js"> </script> <script>; // Creating a path var path1= d3.path(); path1.moveTo(0, 0); // Making line to x:0 and y:100 path1.lineTo(0, 100); // Closing the path path1.closePath(); d3.select(".path1").attr("d",path1); var path2= d3.path(); // Start point are x:20 and y:20 path2.moveTo(20, 20); path2.lineTo(20, 100); path2.closePath(); d3.select(".path2").attr("d",path2); var path3= d3.path(); // Start point are x:40 and y:20 path3.moveTo(40,20); path3.lineTo(40, 100); path3.closePath(); d3.select(".path3").attr("d",path3); </script> </center> </body></html> Output: Example 2: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <style> h1 { color: green; } div { display: inline-block; } svg{ background-color: #f2f2f2; } .path1{ stroke: #000; } .path2{ stroke: green; } .path3{ stroke: #000; } </style> <body> <center> <div> <h1>GeeksforGeeks</h1> <b>D3.js | Path.moveTo() Function</b> <br> <svg width="100" height="100"> <path class="path1"> </svg> <svg width="100" height="100"> <path class="path2"> </svg> <svg width="100" height="100"> <path class="path3"> </svg> </div> <script src ="https://d3js.org/d3.v4.min.js"> </script> <script>; // Creating a path var path1= d3.path(); // Start point are x:0 y:0 path1.moveTo(0, 0); // Making line to x:50 and y:50 path1.lineTo(50, 50); // Closing the path path1.closePath(); d3.select(".path1").attr("d",path1); var path2= d3.path(); // Start point are x:0 and y:100 path2.moveTo(0, 100); path2.lineTo(50, 50); path2.closePath(); d3.select(".path2").attr("d",path2); var path3= d3.path(); // Start point are x:100 and y:100 path3.moveTo(100,100); path3.lineTo(50, 50); path3.closePath(); d3.select(".path3").attr("d",path3); </script> </center> </body></html> Output: arorakashish0911 D3.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 append HTML code to a div using 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": 25535, "s": 25507, "text": "\n11 Apr, 2022" }, { "code": null, "e": 25996, "s": 25535, "text": "D3.js is mostly used for making of graph and visualizing data on the HTML svg elements. D3 somehow is related to Data Driven Documents. The Path.moveTo() function ...
Analysis of Different Methods to find Prime Number in Python - GeeksforGeeks
30 Jun, 2021 If you participate in competitive programming, you might be familiar with the fact that questions related to Prime numbers are one of the choices of the problem setter. Here, we will discuss how to optimize your function which checks for the Prime number in the given set of ranges, and will also calculate the timings to execute them. Going by definition, a Prime number is a positive integer that is divisible only by itself and 1. For example: 2,3,5,7. But if a number can be factored into smaller numbers, it is called a Composite number. For example: 4=2*2, 6=2*3 And the integer 1 is neither a prime number nor a composite number. Checking that a number is prime is easy but efficiently checking needs some effort. Method 1: Let us now go with the very first function to check whether a number, say n, is prime or not. In this method, we will test all divisors from 2 to n-1. We will skip 1 and n. If n is divisible by any of the divisor, the function will return False, else True. Following are the steps used in this method: If the integer is less than equal to 1, it returns False.If the given number is divisible by any of the numbers from 2 to n, the function will return FalseElse it will return True If the integer is less than equal to 1, it returns False. If the given number is divisible by any of the numbers from 2 to n, the function will return False Else it will return True Python3 # Python Program to find prime numbers in a rangeimport timedef is_prime(n): if n <= 1: return False for i in range(2,n): if n % i == 0: return False return True # Driver functiont0 = time.time()c = 0 #for counting for n in range(1,100000): x = is_prime(n) c += xprint("Total prime numbers in range :", c) t1 = time.time()print("Time required :", t1 - t0) Output: Total prime numbers in range: 9592 Time required: 60.702312707901 In the above code, we check all the numbers from 1 to 100000 whether those numbers are prime or not. It has a huge runtime as shown. It takes around 1 minute to run. This is a simple approach but takes a lot of time to run. So, it is not preferred in competitive programming. Method 2: In this method, we use a simple trick by reducing the number of divisors we check for. We have found that there is a fine line which acts as the mirror as shows the factorization below the line and factorization above the line just in reverse order. The line which divided the factors into two halves is the line of the square root of the number. If the number is a perfect square, we can shift the line by 1 and if we can get the integer value of the line which divides. 36=1*36 =2*18 =3*12 =4*9 ------------ =6*6 ------------ =9*4 =12*3 =18*2 =36*1 In this function, we calculate an integer, say max_div, which is the square root of the number and get its floor value using the math library of Python. In the last example, we iterate from 2 to n-1. But in this, we reduce the divisors by half as shown. You need to import the math module to get the floor and sqrt function. Following are the steps used in this method: If the integer is less than equal to 1, it returns False.Now, we reduce the numbers which needs to be checked to the square root of the given number.If the given number is divisible by any of the numbers from 2 to the square root of the number, the function will return FalseElse it will return True If the integer is less than equal to 1, it returns False. Now, we reduce the numbers which needs to be checked to the square root of the given number. If the given number is divisible by any of the numbers from 2 to the square root of the number, the function will return False Else it will return True Python3 # Python Program to find prime numbers in a rangeimport mathimport timedef is_prime(n): if n <= 1: return False max_div = math.floor(math.sqrt(n)) for i in range(2, 1 + max_div): if n % i == 0: return False return True # Driver functiont0 = time.time()c = 0 #for counting for n in range(1,100000): x = is_prime(n) c += xprint("Total prime numbers in range :", c) t1 = time.time()print("Time required :", t1 - t0) Output: Total prime numbers in range: 9592 Time required: 0.4116342067718506 In the above code, we check all the numbers from 1 to 100000 whether those numbers are prime or not. It takes comparatively lesser time than the previous method. This is a bit tricky approach but makes a huge difference in the runtime of the code. So, it is more preferred in competitive programming. Method 3: Now, we will optimize our code to next level which takes lesser time than the previous method. You might have noticed that in the last example, we iterated through every even number up to the limit which was a waste. The thing to notice is that all the even numbers except two can not be prime number. In this method, we kick out all the even numbers to optimize our code and will check only the odd divisors. Following are the steps used in this method: If the integer is less than equal to 1, it returns False.If the number is equal to 2, it will return True.If the number is greater than 2 and divisible by 2, then it will return False.Now, we have checked all the even numbers. Now, look for the odd numbers.If the given number is divisible by any of the numbers from 3 to the square root of the number skipping all the even numbers, the function will return FalseElse it will return True If the integer is less than equal to 1, it returns False. If the number is equal to 2, it will return True. If the number is greater than 2 and divisible by 2, then it will return False. Now, we have checked all the even numbers. Now, look for the odd numbers. If the given number is divisible by any of the numbers from 3 to the square root of the number skipping all the even numbers, the function will return False Else it will return True Python3 # Python Program to find prime numbers in a rangeimport mathimport timedef is_prime(n): if n <= 1: return False if n == 2: return True if n > 2 and n % 2 == 0: return False max_div = math.floor(math.sqrt(n)) for i in range(3, 1 + max_div, 2): if n % i == 0: return False return True # Driver functiont0 = time.time()c = 0 #for counting for n in range(1,100000): x = is_prime(n) c += xprint("Total prime numbers in range :", c) t1 = time.time()print("Time required :", t1 - t0) Output: Total prime numbers in range: 9592 Time required: 0.23305177688598633 In the above code, we check all the numbers from 1 to 100000 whether those numbers are prime or not. It takes comparatively lesser time than all the previous methods for running the program. It is most efficient and quickest way to check for the prime number. Therefore, it is most preferred in competitive programming. Next time while attempting any question in competitive programming, use this method for best results. This method prints all the primes smaller than or equal to a given number, n. For example, if n is 10, the output should be “2, 3, 5, 7”. If n is 20, the output should be “2, 3, 5, 7, 11, 13, 17, 19”. This method is considered to be the most efficient method to generate all the primes smaller than the given number, n. It is considered as the fastest method of all to generate a list of prime numbers. This method is not suited to check for a particular number. This method is preferred for generating the list of all the prime numbers. Python3 # Python Program to find prime numbers in a rangeimport timedef SieveOfEratosthenes(n): # Create a boolean array "prime[0..n]" and # initialize all entries it as true. A value # in prime[i] will finally be false if i is # Not a prime, else true. prime = [True for i in range(n+1)] p = 2 while(p * p <= n): # If prime[p] is not changed, then it is # a prime if (prime[p] == True): # Update all multiples of p for i in range(p * p, n + 1, p): prime[i] = False p += 1 c = 0 # Print all prime numbers for p in range(2, n): if prime[p]: c += 1 return c # Driver functiont0 = time.time()c = SieveOfEratosthenes(100000)print("Total prime numbers in range:", c) t1 = time.time()print("Time required:", t1 - t0) Output: Total prime numbers in range: 9592 Time required: 0.0312497615814209 Note : Time required for all the procedures may vary depending on the compiler but the order of time required by the different methods will remain same. Reference : \https://www.geeksforgeeks.org/sieve-of-eratosthenes/ http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes This article is contributed by Rishabh Bansal. 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. shubham_singh jaydeep8583 Amit_152116 jenishg Prime Number Mathematical Python Mathematical Prime Number Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Print all possible combinations of r elements in a given array of size n Operators in C / C++ Program for factorial of a number Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 26403, "s": 26375, "text": "\n30 Jun, 2021" }, { "code": null, "e": 26739, "s": 26403, "text": "If you participate in competitive programming, you might be familiar with the fact that questions related to Prime numbers are one of the choices of the problem se...
AWT Button Class
Button is a control component that has a label and generates an event when pressed. When a button is pressed and released, AWT sends an instance of ActionEvent to the button, by calling processEvent on the button. The button's processEvent method receives all events for the button; it passes an action event along by calling its own processActionEvent method. The latter method passes the action event on to any action listeners that have registered an interest in action events generated by this button. If an application wants to perform some action based on a button being pressed and released, it should implement ActionListener and register the new listener to receive events from this button, by calling the button's addActionListener method. The application can make use of the button's action command as a messaging protocol. Following is the declaration for java.awt.Button class: public class Button extends Component implements Accessible Button() Constructs a button with an empty string for its label. Button(String text) Constructs a new button with specified label. void addActionListener(ActionListener l) Adds the specified action listener to receive action events from this button. void addNotify() Creates the peer of the button. AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this Button. String getActionCommand() Returns the command name of the action event fired by this button. ActionListener[] getActionListeners() Returns an array of all the action listeners registered on this button. String getLabel() Gets the label of this button. <T extends EventListener> T[] getListeners(Class<T> listenerType) Returns an array of all the objects currently registered as FooListeners upon this Button. protected String paramString() Returns a string representing the state of this Button. protected void processActionEvent(ActionEvent e) Processes action events occurring on this button by dispatching them to any registered ActionListener objects. protected void processEvent(AWTEvent e) Processes events on this button. void removeActionListener(ActionListener l) Removes the specified action listener so that it no longer receives action events from this button. void setActionCommand(String command) Sets the command name for the action event fired by this button. void setLabel(String label) Sets the button's label to be the specified string. This class inherits methods from the following classes: java.awt.Component java.awt.Component java.lang.Object java.lang.Object Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui > package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; public class AwtControlDemo { private Frame mainFrame; private Label headerLabel; private Label statusLabel; private Panel controlPanel; public AwtControlDemo(){ prepareGUI(); } public static void main(String[] args){ AwtControlDemo awtControlDemo = new AwtControlDemo(); awtControlDemo.showButtonDemo(); } private void prepareGUI(){ mainFrame = new Frame("Java AWT Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new Label(); headerLabel.setAlignment(Label.CENTER); statusLabel = new Label(); statusLabel.setAlignment(Label.CENTER); statusLabel.setSize(350,100); controlPanel = new Panel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showButtonDemo(){ headerLabel.setText("Control in action: Button"); Button okButton = new Button("OK"); Button submitButton = new Button("Submit"); Button cancelButton = new Button("Cancel"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { statusLabel.setText("Ok Button clicked."); } }); submitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { statusLabel.setText("Submit Button clicked."); } }); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { statusLabel.setText("Cancel Button clicked."); } }); controlPanel.add(okButton); controlPanel.add(submitButton); controlPanel.add(cancelButton); mainFrame.setVisible(true); } } Compile the program using command prompt. Go to D:/ > AWT and type the following command. D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java If no error comes that means compilation is successful. Run the program using following command. D:\AWT>java com.tutorialspoint.gui.AwtControlDemo Verify the following output 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 2253, "s": 1747, "text": "Button is a control component that has a label and generates an event when pressed. When a button is pressed and released, AWT sends an instance of ActionEvent to the button, by calling processEvent on the button. The button's processEvent method receiv...
Armstrong Numbers between two integers - GeeksforGeeks
27 Apr, 2021 A positive integer with digits a, b, c, d... is called an Armstrong number of order n if following condition is satisfied. abcd... = an + bn + cn + dn +... 153 = 1*1*1 + 5*5*5 + 3*3*3 = 1 + 125 + 27 = 153 Therefore, 153 is an Armstrong number. Examples: Input : 100 400 Output :153 370 371 Explanation : 100 and 400 are given two integers.(interval) 153 = 1*1*1 + 5*5*5 + 3*3*3 = 1 + 125 + 27 = 153 370 = 3*3*3 + 7*7*7 + 0 = 27 + 343 = 370 371 = 3*3*3 + 7*7*7 + 1*1*1 = 27 + 343 +1 = 371 The approach implemented below is simple. We traverse through all numbers in given range. For every number, we first count number of digits in it. Let the number of digits in current number be n. Them we find sum of n-th power of all digits. If sum is equal to i, we print the number. C++ Java Python C# PHP Javascript // CPP program to find Armstrong numbers in a range#include <bits/stdc++.h>using namespace std; // Prints Armstrong Numbers in given rangevoid findArmstrong(int low, int high){ for (int i = low+1; i < high; ++i) { // number of digits calculation int x = i; int n = 0; while (x != 0) { x /= 10; ++n; } // compute sum of nth power of // its digits int pow_sum = 0; x = i; while (x != 0) { int digit = x % 10; pow_sum += pow(digit, n); x /= 10; } // checks if number i is equal to the // sum of nth power of its digits if (pow_sum == i) cout << i << " "; }} // Driver codeint main(){ int num1 = 100; int num2 = 400; findArmstrong(num1, num2); cout << '\n'; return 0;} // JAVA program to find Armstrong// numbers in a rangeimport java.io.*;import java.math.*; class GFG { // Prints Armstrong Numbers in given range static void findArmstrong(int low, int high) { for (int i = low + 1; i < high; ++i) { // number of digits calculation int x = i; int n = 0; while (x != 0) { x /= 10; ++n; } // compute sum of nth power of // its digits int pow_sum = 0; x = i; while (x != 0) { int digit = x % 10; pow_sum += Math.pow(digit, n); x /= 10; } // checks if number i is equal // to the sum of nth power of // its digits if (pow_sum == i) System.out.print(i + " "); } } // Driver code public static void main(String args[]) { int num1 = 100; int num2 = 400; findArmstrong(num1, num2); System.out.println(); }} /*This code is contributed by Nikita Tiwari.*/ # PYTHON program to find Armstrong# numbers in a rangeimport math # Prints Armstrong Numbers in given rangedef findArmstrong(low, high) : for i in range(low + 1, high) : # number of digits calculation x = i n = 0 while (x != 0) : x = x / 10 n = n + 1 # compute sum of nth power of pow_sum = 0 x = i while (x != 0) : digit = x % 10 pow_sum = pow_sum + math.pow(digit, n) x = x / 10 # checks if number i is equal to # the sum of nth power of its digits if (pow_sum == i) : print(str(i) + " "), # Driver codenum1 = 100num2 = 400findArmstrong(num1, num2)print("") # This code is contributed by Nikita Tiwari. // C# program to find Armstrong// numbers in a rangeusing System; class GFG { // Prints Armstrong Numbers in given range static void findArmstrong(int low, int high) { for (int i = low + 1; i < high; ++i) { // number of digits calculation int x = i; int n = 0; while (x != 0) { x /= 10; ++n; } // compute sum of nth power of // its digits int pow_sum = 0; x = i; while (x != 0) { int digit = x % 10; pow_sum += (int)Math.Pow(digit, n); x /= 10; } // checks if number i is equal // to the sum of nth power of // its digits if (pow_sum == i) Console.Write(i + " "); } } // Driver code public static void Main() { int num1 = 100; int num2 = 400; findArmstrong(num1, num2); Console.WriteLine(); }} /*This code is contributed by vt_m.*/ <?php// PHP program to find// Armstrong numbers// in a range // Prints Armstrong// Numbers in given rangefunction findArmstrong($low, $high){ for ($i = $low + 1; $i < $high; ++$i) { // number of digits // calculation $x = $i; $n = 0; while ($x != 0) { $x = (int)($x / 10); ++$n; } // compute sum of nth // power of its digits $pow_sum = 0; $x = $i; while ($x != 0) { $digit = $x % 10; $pow_sum += (int)(pow($digit, $n)); $x = (int)($x / 10); } // checks if number i is // equal to the sum of // nth power of its digits if ($pow_sum == $i) echo $i . " "; }} // Driver code$num1 = 100;$num2 = 400;findArmstrong($num1, $num2); // This code is contributed by mits?> <script> // Javascript program to find// Armstrong numbers// in a range // Prints Armstrong// Numbers in given rangefunction findArmstrong(low, high){ for (let i = low + 1; i < high; ++i) { // number of digits // calculation let x = i; let n = 0; while (x != 0) { x = parseInt(x / 10); ++n; } // compute sum of nth // power of its digits let pow_sum = 0; x = i; while (x != 0) { let digit = x % 10; pow_sum += parseInt(Math.pow(digit, n)); x = parseInt(x / 10); } // checks if number i is // equal to the sum of // nth power of its digits if (pow_sum == i) document.write(i + " "); }} // Driver codelet num1 = 100;let num2 = 400;findArmstrong(num1, num2); // This code is contributed by _saurabh_jaiswal</script> Output: 153 370 371 This article is contributed by Aditya Ranjan. 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. Mithun Kumar _saurabh_jaiswal series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Print all possible combinations of r elements in a given array of size n Sieve of Eratosthenes Operators in C / C++ The Knight's tour problem | Backtracking-1 Program for factorial of a number Find minimum number of coins that make a given value
[ { "code": null, "e": 26680, "s": 26652, "text": "\n27 Apr, 2021" }, { "code": null, "e": 26805, "s": 26680, "text": "A positive integer with digits a, b, c, d... is called an Armstrong number of order n if following condition is satisfied. " }, { "code": null, "e": 2...
Analysis of Algorithms | Big-O analysis - GeeksforGeeks
06 Mar, 2021 In our previous articles on Analysis of Algorithms, we had discussed asymptotic notations, their worst and best case performance etc. in brief. In this article, we discuss the analysis of the algorithm using Big – O asymptotic notation in complete detail. Big-O Analysis of Algorithms We can express algorithmic complexity using the big-O notation. For a problem of size N: A constant-time function/method is “order 1” : O(1) A linear-time function/method is “order N” : O(N) A quadratic-time function/method is “order N squared” : O(N 2 ) Definition: Let g and f be functions from the set of natural numbers to itself. The function f is said to be O(g) (read big-oh of g), if there is a constant c > 0 and a natural number n0 such that f (n) ≤ cg(n) for all n >= n0 . Note: O(g) is a set! Abuse of notation: f = O(g) does not mean f ∈ O(g). The Big-O Asymptotic Notation gives us the Upper Bound Idea, mathematically described below: f(n) = O(g(n)) if there exists a positive integer n0 and a positive constant c, such that f(n)≤c.g(n) ∀ n≥n0 The general step wise procedure for Big-O runtime analysis is as follows: Figure out what the input is and what n represents.Express the maximum number of operations, the algorithm performs in terms of n.Eliminate all excluding the highest order terms.Remove all the constant factors. Figure out what the input is and what n represents. Express the maximum number of operations, the algorithm performs in terms of n. Eliminate all excluding the highest order terms. Remove all the constant factors. Some of the useful properties of Big-O notation analysis are as follow: Constant Multiplication: If f(n) = c.g(n), then O(f(n)) = O(g(n)) ; where c is a nonzero constant. Polynomial Function: If f(n) = a0 + a1.n + a2.n2 + —- + am.nm, then O(f(n)) = O(nm). Summation Function: If f(n) = f1(n) + f2(n) + —- + fm(n) and fi(n)≤fi+1(n) ∀ i=1, 2, —-, m, then O(f(n)) = O(max(f1(n), f2(n), —-, fm(n))). Logarithmic Function: If f(n) = logan and g(n)=logbn, then O(f(n))=O(g(n)) ; all log functions grow in the same manner in terms of Big-O. Basically, this asymptotic notation is used to measure and compare the worst-case scenarios of algorithms theoretically. For any algorithm, the Big-O analysis should be straightforward as long as we correctly identify the operations that are dependent on n, the input size. Runtime Analysis of Algorithms In general cases, we mainly used to measure and compare the worst-case theoretical running time complexities of algorithms for the performance analysis. The fastest possible running time for any algorithm is O(1), commonly referred to as Constant Running Time. In this case, the algorithm always takes the same amount of time to execute, regardless of the input size. This is the ideal runtime for an algorithm, but it’s rarely achievable. In actual cases, the performance (Runtime) of an algorithm depends on n, that is the size of the input or the number of operations is required for each input item. The algorithms can be classified as follows from the best-to-worst performance (Running Time Complexity): A logarithmic algorithm – O(logn) Runtime grows logarithmically in proportion to n. A linear algorithm – O(n) Runtime grows directly in proportion to n. A superlinear algorithm – O(nlogn) Runtime grows in proportion to n. A polynomial algorithm – O(nc) Runtime grows quicker than previous all based on n. A exponential algorithm – O(cn) Runtime grows even faster than polynomial algorithm based on n. A factorial algorithm – O(n!) Runtime grows the fastest and becomes quickly unusable for even small values of n. Where, n is the input size and c is a positive constant. Algorithmic Examples of Runtime Analysis: Some of the examples of all those types of algorithms (in worst-case scenarios) are mentioned below: Logarithmic algorithm – O(logn) – Binary Search. Linear algorithm – O(n) – Linear Search. Superlinear algorithm – O(nlogn) – Heap Sort, Merge Sort. Polynomial algorithm – O(n^c) – Strassen’s Matrix Multiplication, Bubble Sort, Selection Sort, Insertion Sort, Bucket Sort. Exponential algorithm – O(c^n) – Tower of Hanoi. Factorial algorithm – O(n!) – Determinant Expansion by Minors, Brute force Search algorithm for Traveling Salesman Problem. Mathematical Examples of Runtime Analysis: The performances (Runtimes) of different orders of algorithms separate rapidly as n (the input size) gets larger. Let’s consider the mathematical example: If n = 10, If n=20, log(10) = 1; log(20) = 2.996; 10 = 10; 20 = 20; 10log(10)=10; 20log(20)=59.9; 102=100; 202=400; 210=1024; 220=1048576; 10!=3628800; 20!=2.432902e+1818; Memory Footprint Analysis of Algorithms For performance analysis of an algorithm, runtime measurement is not only relevant metric but also we need to consider the memory usage amount of the program. This is referred to as the Memory Footprint of the algorithm, shortly known as Space Complexity. Here also, we need to measure and compare the worst case theoretical space complexities of algorithms for the performance analysis. It basically depends on two major aspects described below: Firstly, the implementation of the program is responsible for memory usage. For example, we can assume that recursive implementation always reserves more memory than the corresponding iterative implementation of a particular problem. And the other one is n, the input size or the amount of storage required for each item. For example, a simple algorithm with a high amount of input size can consume more memory than a complex algorithm with less amount of input size. Algorithmic Examples of Memory Footprint Analysis: The algorithms with examples are classified from the best-to-worst performance (Space Complexity) based on the worst-case scenarios are mentioned below: Ideal algorithm - O(1) - Linear Search, Binary Search, Bubble Sort, Selection Sort, Insertion Sort, Heap Sort, Shell Sort. Logarithmic algorithm - O(log n) - Merge Sort. Linear algorithm - O(n) - Quick Sort. Sub-linear algorithm - O(n+k) - Radix Sort. Space-Time Tradeoff and Efficiency There is usually a trade-off between optimal memory use and runtime performance. In general for an algorithm, space efficiency and time efficiency reach at two opposite ends and each point in between them has a certain time and space efficiency. So, the more time efficiency you have, the less space efficiency you have and vice versa. For example, Mergesort algorithm is exceedingly fast but requires a lot of space to do the operations. On the other side, Bubble Sort is exceedingly slow but requires the minimum space. At the end of this topic, we can conclude that finding an algorithm that works in less running time and also having less requirement of memory space, can make a huge difference in how well an algorithm performs. vitiral tripathipriyanshu1998 Algorithms-Analysis of Algorithms Analysis Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexity and Space Complexity Difference between NP hard and NP complete problem Difference between Big Oh, Big Omega and Big Theta Cyclomatic Complexity Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Time complexities of different data structures Lower and Upper Bound Theory Tail Recursion Difference between Recursion and Iteration Analysis of algorithms | little o and little omega notations
[ { "code": null, "e": 26031, "s": 26003, "text": "\n06 Mar, 2021" }, { "code": null, "e": 26288, "s": 26031, "text": "In our previous articles on Analysis of Algorithms, we had discussed asymptotic notations, their worst and best case performance etc. in brief. In this article, we...
Python - Place object in Tweepy - GeeksforGeeks
03 Jul, 2020 Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication. The Place object in Tweepy module contains the information about a place. Here are the list of attributes in the Place object : id : The ID of the place. url : The URL representing the location of the place. place_type : The type of location represented by the place. name : The name of the place. full_name : The full name of the place. country_code : The code of the country of the place. country : The name of the country of the place. contained_within : A Place object containing the place. geometry : The geometry of the place. polylines : The polylines of the place. centroid : The centroid of the place. bounding_box : The coordinates which encloses the place. Example : Use geo_id() method to fetch the place. Consider the city of London. # import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # Twitter ID of London id = "457b4814b4240d87" # fetching the location place = api.geo_id(id) # printing the information print("The id is : " + place.id)print("The url is : " + place.url)print("The place_type is : " + place.place_type)print("The name is : " + place.name)print("The full_name is : " + place.full_name)print("The country_code is : " + place.country_code)print("The country is : " + place.country)print("The contained_within is : " + str(place.contained_within))print("The geometry is : " + str(place.geometry))print("The polylines are : " + str(place.polylines))print("The centroid is : " + str(place.centroid))print("The bounding_box is : " + str(place.bounding_box)) Output : The id is : 457b4814b4240d87The url is : https://api.twitter.com/1.1/geo/id/457b4814b4240d87.jsonThe place_type is : cityThe name is : LondonThe full_name is : London, EnglandThe country_code is : GBThe country is : United KingdomThe contained_within is : [Place(_api=, id=’1090d3ced4b75d04′, url=’https://api.twitter.com/1.1/geo/id/1090d3ced4b75d04.json’, place_type=’admin’, name=’London’, full_name=’London’, country_code=’GB’, country=’United Kingdom’, centroid=[0.07110233274688144, 51.5989395], bounding_box=BoundingBox(_api=, type=’Polygon’, coordinates=[[[-0.853907, 51.105205], [-0.853907, 52.092674], [0.958128, 52.092674], [0.958128, 51.105205], [-0.853907, 51.105205]]]), attributes={})]The geometry is : NoneThe polylines are : []The centroid is : [-0.14032122753075282, 51.50009175]The bounding_box is : BoundingBox(_api=, type=’Polygon’, coordinates=[[[-0.187894, 51.483718], [-0.187894, 51.5164655], [-0.109978, 51.5164655], [-0.109978, 51.483718], [-0.187894, 51.483718]]]) Python-Tweepy 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() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25791, "s": 25763, "text": "\n03 Jul, 2020" }, { "code": null, "e": 26191, "s": 25791, "text": "Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data ...
What are the advantages of Lambda Expressions in Java?
A lambda expression is an inline code that implements a functional interface without creating a concrete or anonymous class. A lambda expression is basically an anonymous method. Fewer Lines of Code − One of the most benefits of a lambda expression is to reduce the amount of code. We know that lambda expressions can be used only with a functional interface. For instance, Runnable is a functional interface, so we can easily apply lambda expressions. Sequential and Parallel execution support by passing behavior as an argument in methods − By using Stream API in Java 8, the functions are passed to collection methods. Now it is the responsibility of collection for processing the elements either in a sequential or parallel manner. Higher Efficiency − By using Stream API and lambda expressions, we can achieve higher efficiency (parallel execution) in case of bulk operations on collections. Also, lambda expression helps in achieving the internal iteration of collections rather than external iteration. (parameters) -> expression or (parameters) -> { statements; } import java.util.*; public class LambdaExpressionTest { public static void main(String args[]) { new LambdaExpressionTest().print(); } public static void print() { List<String> list = new ArrayList<String>(); list.add("Tutorials Point"); list.stream().forEach((String) -> { // lambda expression System.out.println("The string is: " + list); }); } } The string is: [Tutorials Point]
[ { "code": null, "e": 1241, "s": 1062, "text": "A lambda expression is an inline code that implements a functional interface without creating a concrete or anonymous class. A lambda expression is basically an anonymous method." }, { "code": null, "e": 1515, "s": 1241, "text": "Few...
Train a GAN and generate faces using AWS Sagemaker | PyTorch | by Shyam BV | Towards Data Science
I assume you have already heard or worked on GAN. If you have not heard before, then Generative Adversarial Networks(GAN) is one type of neural network architecture that allows us to create synthetic data, images or videos. It has become an interesting subfield in deep learning. Some of the different types of GAN’s are DCGAN, CycleGAN(CGAN), GauGAN, StyleGAN, Pix2Pix, etc. As it is so popular, new types of GAN papers and architecture emerge as we speak! Although there are many different GAN architectures, they all have one thing in common. To train a GAN they need a lot of computing power and they are GPU hungry. So it is really difficult to train a GAN in the local environment unless you have a good distributed GPU set up with time and money. Else you can leverage the cloud to train GAN. Cloud environments can be used for various neural network training and it is not restricted to GAN’s. I faced issues while running in my local environment so I used cloud and able to train easily and deploy it in production quickly! There are different cloud providers, I felt AWS is ahead of other cloud providers in many areas. Particularly in machine learning space, AWS has different services that can be leveraged. So in this blog, we are going to look at Sagemaker service which is provided by AWS. Amazon SageMaker is a fully managed service that provides us the ability to build, train, and deploy machine learning (ML) models quickly. Another huge advantage of SageMaker is the machine learning models can be deployed to production faster with much less effort. Yes, some cloud providers are cheaper than AWS however, sagemaker provides other advantages on deployment. You can also leverage the local GPU environment if you have one while developing models. In this blog, we will generate new faces (Again!) by training celebrities dataset. For generating new images, I will use my local GPU environment(to save some bucks) for development and sanity testing and use Sagemaker for training a full-fledged model. I will also show how to create an endpoint for deployment. As there are plenty of articles on AWS account set up and local environment setup, I am going to skip that part. If you have any questions, please feel free to ask in the comments section. Sagemaker can be accessed via AWS services console page. Now there are two options for Jupyter Notebooks. Use Local EnvironmentSagemaker Environment Use Local Environment Sagemaker Environment Local Environment:If you have a local environment with Jupyter notebook, then congrats! You can save some bucks by using a local environment for development and sanity testing. You install Sagemaker python package and use sagemaker functions locally. If you have GPU with Cuda enabled, then you can use it to test the entire code and submit your job sagemaker. Below are the steps for setting up a local environment. Entire code is present in my Github page Step 1: Install package Install Sagemaker python package in your virtual environment https://pypi.org/project/sagemaker/ Step 2: Connect to your AWS accountAssuming you have created an AWS account and have Sagemaker and S3 bucket access. You can also set access key, secret variables, and region in your .aws/config file. You also need an IAM role for sagemaker execution. It needs full access to Sagemaker. import sagemakerimport boto3sagemaker_session = sagemaker.Session(boto3.session.Session( aws_access_key_id='xxxxxxxxxxxxx', aws_secret_access_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', region_name='update your AWS region'))bucket = sagemaker_session.default_bucket()prefix = 'sagemaker/dcgan'role = 'sagemaker_execution_role' You can test the connection by uploading test data in S3 bucket and check by using the following command input_data = sagemaker_session.upload_data(path=data_dir, bucket=bucket, key_prefix=prefix)input_data If you did not get any error and data is in the S3 bucket, then you are good to start. If you get any error, then please debug and correct the issue. Alternatively, you can provide the S3 bucket link here and download the data from S3 for local testing. Sagemaker Environment:If you do not have a local environment, you can start sagemaker Jupyter notebooks. This will spin up a compute instance and it will deploy required containers for Jupyter notebooks. Step 1: Launch NotebookGoto Notebook instances section sagemaker and create a notebook instance When you go next, you can set up the S3 bucket and IAM roles. Selecting the size of the cloud instance and other technical details depending on your needs and size. Now, we can go ahead and “Create”. AWS takes some time to get the Notebook ready. We can see on the console that the Notebook Instance is “Pending”. Once it is ready, click on the “Open Jupyter” notebook. You are ready to start training your GAN now. GAN Model Training: I am using PyTorch for Training a GAN model. Before training, it requires some pre-processing. If you are using a local environment, you need to upload the data in the S3 bucket. Below are some processing that you need to perform. Transform the input images and have them in a common size. Transform the input images and have them in a common size. def get_dataloader(batch_size, image_size, data_dir): """ Batch the neural network data using DataLoader :param batch_size: The size of each batch; the number of images in a batch :param img_size: The square size of the image data (x, y) :param data_dir: Directory where image data is located :return: DataLoader with batched data """ transform = transforms.Compose([transforms.Resize(image_size), transforms.ToTensor()]) dataset = datasets.ImageFolder(data_dir,transform=transform) #rand_sampler = torch.utils.data.RandomSampler(dataset, num_samples=32, replacement=True) #dataloader = torch.utils.data.dataloader.DataLoader(dataset, batch_size=batch_size,shuffle=False, sampler=rand_sampler) #dataloader = torch.utils.data.dataloader.DataLoader(dataset, batch_size=batch_size,shuffle=True) return dataloader While testing you can use random sampler on the input dataset and use it in the data loader. 2. Scale the images Scaling the images is an important step in the neural network. It is particularly true while performing GAN. def scale(x, feature_range=(-1, 1)): ''' Scale takes in an image x and returns that image, scaled with a feature_range of pixel values from -1 to 1. This function assumes that the input x is already scaled from 0-1.''' # assume x is scaled to (0, 1) # scale to feature_range and return scaled x min, max = feature_range x = x * (max - min) + min return x 3. Create the model When performing GAN, two types of network needs to be trained. One is a generator and another is the discriminator. Input to a generator is from latent space or noise. A generator is trained to generate an image and a Discriminator is trained to detect if the image is real or fake. The final output of playing this game between generator and discriminator is a realistic output from Generator which looks like real images. As mentioned before, there are other architectures of GAN. However, this is the idea behind the GAN. Model code is provided in model.py in the Github repo. I have written a DCGAN model using convolution t 4. Training the model This is the step where we are going to leverage the cloud. Before running many epochs in sagemaker, test the complete workflow in a local environment with sample data. Some hyperparameters need to tuned like learning rate, beta1, and beta2. I have selected it from this paper https://arxiv.org/pdf/1511.06434.pdf Once sanity testing is performed, it is time to submit this job to sagemaker. Create an estimator object using sagemaker PyTorch API and call the fit method. from sagemaker.pytorch import PyTorchestimator = PyTorch(entry_point="train.py", source_dir="train", role=role, framework_version='0.4.0', train_instance_count=4, train_instance_type='ml.p2.xlarge', hyperparameters={ 'epochs': 15, 'conv_dim': 64, })estimator.fit({'training': input_data}) Some points to note on the above code: You can change the ML framework. Sagemaker supports all major frameworks like PyTorch, Tensorflow, etc.The source directory needs to be specified where all the code is present as shown in my GitHub repository.Pytorch framework version needs to be specified. Train directory should also contain requirement.txt file with all the packages which were used in data processing and training.Instance type depends on how big compute instance you need. If you are training a GAN, I would at-least prefer p2.xlarge as it contains GPU. It is recommended to have a GPU enabled compute server. Else the model will train forever. You can change the ML framework. Sagemaker supports all major frameworks like PyTorch, Tensorflow, etc. The source directory needs to be specified where all the code is present as shown in my GitHub repository. Pytorch framework version needs to be specified. Train directory should also contain requirement.txt file with all the packages which were used in data processing and training. Instance type depends on how big compute instance you need. If you are training a GAN, I would at-least prefer p2.xlarge as it contains GPU. It is recommended to have a GPU enabled compute server. Else the model will train forever. Once you call the fit method, it should create some logs like the below one. It is starting a compute instance and training the model. Different colors highlight it is using different compute instances. We are also printing discriminator and generator losses. Now you can leave it to train until it completes. If your training time is large, your kernel session will likely end. Worry not, as we are training in the cloud we can easily attach to the session which we were running by below code. Job name can be found in sagemaker console. estimator = estimator.attach('sagemaker-job-name-2020-xxxxx') Once the model is trained, you are good to deploy it. 5. Deploy the model: Deploy the model to another compute instance which has less compute power. However, if you need GPU for prediction then please use p2.xlarge or above. The model can also be served in a distributed fashion by instance count parameter. predictor = estimator.deploy(initial_instance_count = 1, instance_type = ‘ml.m5.large’) 6. Results -Generate faces After deploying the model, it is time to generate faces from our trained model. #Generate random noisefixed_z = np.random.uniform(-1, 1, size=(16, 100))fixed_z = torch.from_numpy(fixed_z).float()sample_y = predictor.predict(fixed_z) I have added all the files in my Github repo. Once we have the model and endpoint deployed, we can create an AWS Lambda function that could be invoked via the API Gateway. API can be used to generate images from any application. All the code and packages are found at my Github I hope you can make use of the repo along with this story. Questions? Comments? Feel free to leave your feedback in the comments section. To get the complete working code for the article and other updates, please subscribe to my newsletter.
[ { "code": null, "e": 629, "s": 171, "text": "I assume you have already heard or worked on GAN. If you have not heard before, then Generative Adversarial Networks(GAN) is one type of neural network architecture that allows us to create synthetic data, images or videos. It has become an interesting su...
C++ Program for Deadlock free condition in Operating Systems
Given with the P number of processes in the memory and N number of needed resources by them to complete their execution and the task is to find the minimum number of resources R which should be allotted to the processes such that deadlock will never occur. Deadlock is situation in an operating system where multiple processes residing in the memory doesn’t able to perform their execution because the resources which are needed for program execution is being hold by another resource who is waiting for some other resource for completion. Let’s say there are two processes P1 and P2 in memory where P1 requires resource R1 and P2 requires resource R2, but the deadlock will arise when P1 hold the resource R2 and wait for the resource R1 similarly P2 hold resource R1 and wait for the resource R2. This is the example of circular wait which is one of the causes of deadlock. So, to prevent deadlock we need to calculate the number of resources which should be available for the processes such that deadlock will not occur. R >= P * (N - 1) + 1 where, R is the Resources, P is the processes and N is the need of processes Input-: processes = 5, need = 3 Output-: minimum required resources are: 11 Input-: Processes = 7, need = 2 Output-: minimum required resources are: 8 Approach used in the below program is as follows − Input the number of processes and need of the processes in the memory Apply the formula given to calculate the number of resources required Display the result START Step 1-> declare function to calculate the minimum number of resources needed int min_resource(int process, int need) declare int calculate = 0 set calculate = process * (need - 1) + 1 return calculate Step 2-> In main() Declare int process = 5 and need = 3 Call min_resource(process, need) STOP #include <bits/stdc++.h> using namespace std; //calculate minimum number of resources needed int min_resource(int process, int need) { int calculate = 0; calculate = process * (need - 1) + 1; return calculate; } int main() { int process = 5, need = 3; cout << "minimum required resources are : " <<min_resource(process, need); return 0; } minimum required resources are : 11
[ { "code": null, "e": 1319, "s": 1062, "text": "Given with the P number of processes in the memory and N number of needed resources by them to complete their execution and the task is to find the minimum number of resources R which should be allotted to the processes such that deadlock will never occ...
Using combination of “AND” and “OR” in SELECT in ABAP
You can use the following query: SELECT * FROM my_table WHERE condition 1 AND condition 2 AND ( id EQ '2' or id EQ ‘3’ ). Note: There should be space after and before bracket. Alternatively you can use IN statement as below: SELECT * FROM my_table WHERE condition 1 AND condition 2 AND EQ IN ('2', ‘3’ ).
[ { "code": null, "e": 1095, "s": 1062, "text": "You can use the following query:" }, { "code": null, "e": 1184, "s": 1095, "text": "SELECT * FROM my_table\nWHERE condition 1\nAND condition 2\nAND ( id EQ '2' or id EQ ‘3’ )." }, { "code": null, "e": 1238, "s": 1184,...
MySQL - DATE_FORMAT() Function
The DATE, DATETIME and TIMESTAMP datatypes in MySQL are used to store the date, date and time, time stamp values respectively. Where a time stamp is a numerical value representing the number of milliseconds from '1970-01-01 00:00:01' UTC (epoch) to the specified time. MySQL provides a set of functions to manipulate these values. The MYSQL DATE_FORMAT() function accepts date or date—time value and a format string (representing a desired date/time format) as parameters, formats the given date in the specified format and, returns the result. Following is the syntax of the above function – DATE_FORMAT(date,format) Following example demonstrates the usage of the DATE_FORMAT() function. It prints the weekday (full), month (full) and the year of the given date– mysql> SELECT DATE_FORMAT('2015-09-05', '%W %M %Y'); +---------------------------------------+ | DATE_FORMAT('2015-09-05', '%W %M %Y') | +---------------------------------------+ | Saturday September 2015 | +---------------------------------------+ 1 row in set (0.00 sec) Following query prints the weekday (short), month (short) and the day of the month of the given date – mysql> SELECT DATE_FORMAT('2015-09-05', '%a %b %c'); +---------------------------------------+ | DATE_FORMAT('2015-09-05', '%a %b %c') | +---------------------------------------+ | Sat Sep 9 | +---------------------------------------+ 1 row in set (0.00 sec) Following query formats the time value in the specified date — mysql> SELECT DATE_FORMAT('2015-09-05 20:40:45', '%H Hours %i Minutes %S Seconds'); +----------------------------------------------------------------------+ | DATE_FORMAT('2015-09-05 20:40:45', '%H Hours %i Minutes %S Seconds') | +----------------------------------------------------------------------+ | 20 Hours 40 Minutes 45 Seconds | +----------------------------------------------------------------------+ 1 row in set (0.00 sec) Following is another example of this function – mysql> SELECT DATE_FORMAT('2019-11-25 15:45:50','%D %y %a %d %m %b %j'); +-----------------------------------------------------------+ | DATE_FORMAT('2019-11-25 15:45:50','%D %y %a %d %m %b %j') | +-----------------------------------------------------------+ | 25th 19 Mon 25 11 Nov 329 | +-----------------------------------------------------------+ 1 row in set (0.00 sec) Following query prints the time of day in 24 hours format. mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00','%W %M %Y %r'); +--------------------------------------------------+ | DATE_FORMAT('1997-10-04 22:23:00','%W %M %Y %r') | +--------------------------------------------------+ | Saturday October 1997 10:23:00 PM | +--------------------------------------------------+ 1 row in set (0.00 sec) Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below – mysql> CREATE TABLE MyPlayers( ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Date_Of_Birth date, Place_Of_Birth VARCHAR(255), Country VARCHAR(255), PRIMARY KEY (ID) ); Now, we will insert 7 records in MyPlayers table using INSERT statements − mysql> insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India'); mysql> insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica'); mysql> insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka'); mysql> insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India'); mysql> insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India'); mysql> insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India'); mysql> insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England'); Following query formats the value of the Date_Of_Birth column and prints those — mysql> SELECT First_Name, Last_Name, Date_Of_Birth, Country, DATE_FORMAT(Date_Of_Birth, '%D %M %Y, %W') as FormattedDOB FROM MyPlayers; +------------+------------+---------------+-------------+-----------------------------+ | First_Name | Last_Name | Date_Of_Birth | Country | FormattedDOB | +------------+------------+---------------+-------------+-----------------------------+ | Shikhar | Dhawan | 1981-12-05 | India | 5th December 1981, Saturday | | Jonathan | Trott | 1981-04-22 | SouthAfrica | 22nd April 1981, Wednesday | | Kumara | Sangakkara | 1977-10-27 | Srilanka | 27th October 1977, Thursday | | Virat | Kohli | 1988-11-05 | India | 5th November 1988, Saturday | | Rohit | Sharma | 1987-04-30 | India | 30th April 1987, Thursday | | Ravindra | Jadeja | 1988-12-06 | India | 6th December 1988, Tuesday | | James | Anderson | 1982-06-30 | England | 30th June 1982, Wednesday | +------------+------------+---------------+-------------+-----------------------------+ 7 rows in set (0.00 sec) Suppose we have created a table named Subscribers with 5 records in it using the following queries – mysql> CREATE TABLE Subscribers( SubscriberName VARCHAR(255), PackageName VARCHAR(255), SubscriptionDate date ); insert into Subscribers values('Raja', 'Premium', Date('2020-10-21')); insert into Subscribers values('Roja', 'Basic', Date('2020-11-26')); insert into Subscribers values('Puja', 'Moderate', Date('2021-03-07')); insert into Subscribers values('Vanaja', 'Basic', Date('2021-02-21')); insert into Subscribers values('Jalaja', 'Premium', Date('2021-01-30')); In the following example we are passing the column SubscriptionDate as date value to this function – mysql> SELECT SubscriberName, PackageName, SubscriptionDate, DATE_FORMAT(SubscriptionDate, '%D %M %y') as FormattedDate FROM Subscribers; +----------------+-------------+------------------+------------------+ | SubscriberName | PackageName | SubscriptionDate | FormattedDate | +----------------+-------------+------------------+------------------+ | Raja | Premium | 2020-10-21 | 21st October 20 | | Roja | Basic | 2020-11-26 | 26th November 20 | | Puja | Moderate | 2021-03-07 | 7th March 21 | | Vanaja | Basic | 2021-02-21 | 21st February 21 | | Jalaja | Premium | 2021-01-30 | 30th January 21 | +----------------+-------------+------------------+------------------+ 5 rows in set (2.28 sec) Suppose we have created a table named SubscribersData with 5 records in it using the following queries – mysql> CREATE TABLE SubscribersData( SubscriberName VARCHAR(255), PackageName VARCHAR(255), SubscriptionDate date, SubscriptionTime time ); insert into SubscribersData values('Raja', 'Premium', Date('2020-10-21'), Time('20:53:49')); insert into SubscribersData values('Roja', 'Basic', Date('2020-11-26'), Time('10:13:19')); insert into SubscribersData values('Puja', 'Moderate', Date('2021-03-07'), Time('05:43:20')); insert into SubscribersData values('Vanaja', 'Basic', Date('2021-02-21'), Time('16:36:39')); insert into SubscribersData values('Jalaja', 'Premium', Date('2021-01-30'), Time('12:45:45')); Suppose we have created a table named SubscribersData with 5 records in it using the following queries – mysql> SELECT SubscriberName, PackageName, DATE_FORMAT(TIMESTAMP(SubscriptionDate, SubscriptionTime), GET_FORMAT(TIMESTAMP, 'USA')) as TIMESTAMP FROM SubscribersData; +----------------+-------------+---------------------+ | SubscriberName | PackageName | TIMESTAMP | +----------------+-------------+---------------------+ | Raja | Premium | 2020-10-21 20.53.49 | | Roja | Basic | 2020-11-26 10.13.19 | | Puja | Moderate | 2021-03-07 05.43.20 | | Vanaja | Basic | 2021-02-21 16.36.39 | | Jalaja | Premium | 2021-01-30 12.45.45 | +----------------+-------------+---------------------+ 5 rows in set (0.00 sec) There are certain characters with predefined meaning using which you can create a format string They are − %a – Weekday name (Sun..Sat) %b – Month name (Jan..Dec) %c – Month, numeric (0..12) %D – Day of the month with English suffix (0th, 1st, 2nd, 3rd, ...) %d – Day of the month, numeric (00..31) %e – Day of the month, numeric (0..31) %f – Microseconds (000000..999999) %H – Hour (00..23) %h – Hour (01..12) %I – Hour (01..12) %i – Minutes, numeric (00..59) %j – Day of year (001..366) %k – Hour (0..23) %l – Hour (1..12) %M – Month name (January..December) %m – Month, numeric (00..12) %p – AM or PM %r – Time, 12-hour (hh:mm:ss followed by AM or PM) %S – Seconds (00..59) %s – Seconds (00..59) %T – Time, 24-hour (hh:mm:ss) %U – Week (00..53), where Sunday is the first day of the week; WEEK() mode 0 %u – Week (00..53), where Monday is the first day of the week; WEEK() mode 1 %V – Week (01..53), where Sunday is the first day of the week; WEEK() mode 2; used with %X %v – Week (01..53), where Monday is the first day of the week; WEEK() mode 3; used with %x %W – Weekday name (Sunday..Saturday) %w – Day of the week (0=Sunday..6=Saturday) %X – Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V %x – Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v %Y – Year, numeric, four digits %y – Year, numeric (two digits) %% – A literal % character %x – x, for any “x” not listed above 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2664, "s": 2333, "text": "The DATE, DATETIME and TIMESTAMP datatypes in MySQL are used to store the date, date and time, time stamp values respectively. Where a time stamp is a numerical value representing the number of milliseconds from '1970-01-01 00:00:01' UTC (epoch) to the ...
How to extract email id from text using Python regular expression?
The following code using Python regex extracts the email id from given string/text import re s ='manogna@tutorialspoint.com56' result =re.findall('[a-zA-Z0-9]\S*@\S*[a-zA-Z]', s) print result This gives the output ['manogna@tutorialspoint.com']
[ { "code": null, "e": 1145, "s": 1062, "text": "The following code using Python regex extracts the email id from given string/text" }, { "code": null, "e": 1254, "s": 1145, "text": "import re\ns ='manogna@tutorialspoint.com56'\nresult =re.findall('[a-zA-Z0-9]\\S*@\\S*[a-zA-Z]', s)...
Numbers within a range that can be expressed as power of two numbers - GeeksforGeeks
24 Apr, 2018 Given two integers L and R. Find the number of perfect powers in the given range [L, R]. A number x is said to be perfect power if there exists some integers a > 0, p > 1 such that x = ap. Examples : Input : 1 4 Output : 2 Explanation : Suitable numbers are 1 and 4 where 1 can be expressed as 1 = 12 and 4 can be expressed as 4 = 22 Input : 12 29 Output : 3 Explanation : Suitable numbers are 16, 25 and 27. Prerequisites : Check if a number can be expressed as x^y, Binary Search and Perfect power (1, 4, 8, 9, 16, 25, 27, ...) Approach : Let’s fix some power p. It’s obvious that there are no more than 1018/p numbers x such that xp doesn’t exceed 1018 for a particular p. At the same time, only for p = 2 this amount is relatively huge, for all other p ≥ 3 the total amount of such numbers will be of the order of 106. There are 109 squares in the range [1, 1018], so can’t store them to answer our query. Either, generate all of powers for p ≥ 2 and dispose of all perfect squares among them or generate only odd powers of numbers like 3, 5, 7, etc. Then answer to query (L, R) is equal to the amount of generated numbers between L and R plus some perfect squares in range. The number of perfect squares in the range is the difference of floor value of square root of R and floor value of square root of (L – 1), i.e. (floor(sqrt(R)) – floor(sqrt(L – 1)). Note that due to precision issues the standard sqrt might produce incorrect values, so either use binary search or sqrtl inbuilt function defined in cmath (Check here for more description of sqrtl).To generate those odd powers of numbers. First of all, do precomputation of finding such numbers that can be expressed as power of some number upto 1018 so that we can answer many queries and no need to process them again and again for each query. Start by iterating a loop from 2 to 106 (since we are calculating for powers p ≥ 3 and 106 is the maximum number whose power raised to 3 cannot exceed 1018), for each value we insert its square into a set and check further if that value is already a perfect square (already present in the set), we do not find any other powers of that number (since any power of a perfect square is also a perfect square). Otherwise, run an inside loop to find odd powers of the number until it exceeds 1018 and insert into another set say ‘s’. By this approach, we haven’t pushed any perfect square in the set ‘s’. The number of perfect squares in the range is the difference of floor value of square root of R and floor value of square root of (L – 1), i.e. (floor(sqrt(R)) – floor(sqrt(L – 1)). Note that due to precision issues the standard sqrt might produce incorrect values, so either use binary search or sqrtl inbuilt function defined in cmath (Check here for more description of sqrtl). To generate those odd powers of numbers. First of all, do precomputation of finding such numbers that can be expressed as power of some number upto 1018 so that we can answer many queries and no need to process them again and again for each query. Start by iterating a loop from 2 to 106 (since we are calculating for powers p ≥ 3 and 106 is the maximum number whose power raised to 3 cannot exceed 1018), for each value we insert its square into a set and check further if that value is already a perfect square (already present in the set), we do not find any other powers of that number (since any power of a perfect square is also a perfect square). Otherwise, run an inside loop to find odd powers of the number until it exceeds 1018 and insert into another set say ‘s’. By this approach, we haven’t pushed any perfect square in the set ‘s’. Hence the final answer would be sum of number of perfect squares in the range and difference of upper value of R and lower value of L (using binary search).Below is the implementation of above approach in C++. // CPP Program to count the numbers// within a range such that number// can be expressed as power of some// other number#include <bits/stdc++.h> using namespace std; #define N 1000005#define MAX 1e18 // Vector to store powers greater than 3vector<long int> powers; // set to store perfect squaresset<long int> squares; // set to store powers other// than perfect squaresset<long int> s; void powersPrecomputation(){ for (long int i = 2; i < N; i++) { // pushing squares squares.insert(i * i); // if the values is already // a perfect square means // present in the set if (squares.find(i) != squares.end()) continue; long int temp = i; // run loop until some // power of current number // doesn't exceed MAX while (i * i <= MAX / temp) { temp *= (i * i); /* pushing only odd powers as even power of a number can always be expressed as a perfect square which is already present in set squares */ s.insert(temp); } } // Inserting those sorted // values of set into a vector for (auto x : s) powers.push_back(x);} long int calculateAnswer(long int L, long int R){ // calculate perfect squares in // range using sqrtl function long int perfectSquares = floor(sqrtl(R)) - floor(sqrtl(L - 1)); // calculate upper value of R // in vector using binary search long int high = (upper_bound(powers.begin(), powers.end(), R) - powers.begin()); // calculate lower value of L // in vector using binary search long int low = (lower_bound(powers.begin(), powers.end(), L) - powers.begin()); // add into final answer perfectSquares += (high - low); return perfectSquares;} // Driver Codeint main(){ // precompute the powers powersPrecomputation(); // left value of range long int L = 12; // right value of range long int R = 29; cout << "Number of powers between " << L << " and " << R << " = " << calculateAnswer(L, R) << endl; L = 1; R = 100000000000; cout << "Number of powers between " << L << " and " << R << " = " << calculateAnswer(L, R) << endl; return 0;} Number of powers between 12 and 29 = 3 Number of powers between 1 and 100000000000 = 320990 cpp-set number-theory Searching Technical Scripter Searching number-theory Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments 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 Program to remove vowels from a String Recursive Programs to find Minimum and Maximum elements of array Find common elements in three sorted arrays Find closest number in array Binary Search In JavaScript Find the row with maximum number of 1s Interpolation search vs Binary search
[ { "code": null, "e": 24615, "s": 24587, "text": "\n24 Apr, 2018" }, { "code": null, "e": 24804, "s": 24615, "text": "Given two integers L and R. Find the number of perfect powers in the given range [L, R]. A number x is said to be perfect power if there exists some integers a > 0...
Transform Perl Arrays to Strings
We can use the join() function in Perl to rejoin the array elements and form one long scalar string. This function has the following syntax − join EXPR, LIST This function joins the separate strings of LIST into a single string with fields separated by the value of EXPR and returns the string. Following is the example − Live Demo #!/usr/bin/perl # define Strings $var_string = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens"; $var_names = "Larry,David,Roger,Ken,Michael,Tom"; # transform above strings into arrays. @string = split('-', $var_string); @names = split(',', $var_names); $string1 = join( '-', @string ); $string2 = join( ',', @names ); print "$string1\n"; print "$string2\n"; This will produce the following result − Rain-Drops-On-Roses-And-Whiskers-On-Kittens Larry,David,Roger,Ken,Michael,Tom
[ { "code": null, "e": 1204, "s": 1062, "text": "We can use the join() function in Perl to rejoin the array elements and form one long scalar string. This function has the following syntax −" }, { "code": null, "e": 1220, "s": 1204, "text": "join EXPR, LIST" }, { "code": nu...
Smallest missing non-negative integer upto every array index - GeeksforGeeks
10 Nov, 2021 Given an array arr[] of size N, the task is for every array indices is to find the smallest missing non-negative integer upto that index of the given array. Examples: Input: arr[] = {1, 3, 0, 2}Output: 0 0 2 4Explanation:Smallest missing non-negative integer from index 0 to 0 is 0.Smallest missing non-negative integer from index 0 to 1 is 0.Smallest missing non-negative integer from index 0 to 2 is 2.Smallest missing non-negative integer from index 0 to 3 is 4. Input: arr[] = {0, 1, 2, 3, 5}Output: 1 2 3 4 4 Approach: This problem can be solved using Hashing. Follow the steps below to solve the problem: Initialize a variable, say smNonNeg to store the smallest missing non-negative integers between the start index and the current index of the given array. Initialize an array, say hash[N] to check if smNonNeg present between the start index and the current index or not. Traverse the given array and check if hash[smNonNeg] equal to 0 or not. If found to be true, then print the value of smNonNeg. Otherwise, increment the value of smNonNeg while hash[smNonNeg] not equal to 0. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to print the smallest// missing non-negative integer// up to every array indicesvoid smlstNonNeg(int arr[], int N){ // Stores the smallest missing // non-negative integers between // start index to current index int smNonNeg = 0; // Store the boolean value to check // smNonNeg present between start // index to each index of the array bool hash[N + 1] = { 0 }; // Traverse the array for (int i = 0; i < N; i++) { // Since output always lies // in the range[0, N - 1] if (arr[i] >= 0 and arr[i] < N) { hash[arr[i]] = true; } // Check if smNonNeg is // present between start index // and current index or not while (hash[smNonNeg]) { smNonNeg++; } // Print smallest missing // non-negative integer cout << smNonNeg << " "; }} // Driver Codeint main(){ int arr[] = { 0, 1, 2, 3, 5 }; int N = sizeof(arr) / sizeof(arr[0]); smlstNonNeg(arr, N);} // Java program to implement// the above approachimport java.io.*;import java.util.Arrays; class GFG{ // Function to print the smallest// missing non-negative integer// up to every array indicesstatic void smlstNonNeg(int arr[], int N){ // Stores the smallest missing // non-negative integers between // start index to current index int smNonNeg = 0; // Store the boolean value to check // smNonNeg present between start // index to each index of the array Boolean[] hash = new Boolean[N + 1]; Arrays.fill(hash, false); // Traverse the array for(int i = 0; i < N; i++) { // Since output always lies // in the range[0, N - 1] if (arr[i] >= 0 && arr[i] < N) { hash[arr[i]] = true; } // Check if smNonNeg is // present between start index // and current index or not while (hash[smNonNeg]) { smNonNeg++; } // Print smallest missing // non-negative integer System.out.print(smNonNeg + " "); }} // Driver Codepublic static void main (String[] args){ int arr[] = { 0, 1, 2, 3, 5 }; int N = arr.length; smlstNonNeg(arr, N);}} // This code is contributed by sanjoy_62 # Python3 program to implement# the above approach # Function to print smallest# missing non-negative integer# up to every array indicesdef smlstNonNeg(arr, N): # Stores the smallest missing # non-negative integers between # start index to current index smNonNeg = 0 # Store the boolean value to check # smNonNeg present between start # index to each index of the array hash = [0] * (N + 1) # Traverse the array for i in range(N): # Since output always lies # in the range[0, N - 1] if (arr[i] >= 0 and arr[i] < N): hash[arr[i]] = True # Check if smNonNeg is # present between start index # and current index or not while (hash[smNonNeg]): smNonNeg += 1 # Print smallest missing # non-negative integer print(smNonNeg, end = " ") # Driver Codeif __name__ == '__main__': arr = [ 0, 1, 2, 3, 5 ] N = len(arr) smlstNonNeg(arr, N) # This code is contributed by mohit kumar 29 // C# program to implement// the above approachusing System; class GFG{ // Function to print the smallest// missing non-negative integer// up to every array indicesstatic void smlstNonNeg(int[] arr, int N){ // Stores the smallest missing // non-negative integers between // start index to current index int smNonNeg = 0; // Store the boolean value to check // smNonNeg present between start // index to each index of the array bool[] hash = new bool[N + 1]; for(int i = 0; i < N; i++) { hash[i] = false; } // Traverse the array for(int i = 0; i < N; i++) { // Since output always lies // in the range[0, N - 1] if (arr[i] >= 0 && arr[i] < N) { hash[arr[i]] = true; } // Check if smNonNeg is // present between start index // and current index or not while (hash[smNonNeg]) { smNonNeg++; } // Print smallest missing // non-negative integer Console.Write(smNonNeg + " "); }} // Driver Codepublic static void Main (){ int[] arr = { 0, 1, 2, 3, 5 }; int N = arr.Length; smlstNonNeg(arr, N);}} // This code is contributed by code_hunt <script> // Javascript program to implement// the above approach // Function to print the smallest// missing non-negative integer// up to every array indicesfunction smlstNonNeg(arr, N){ // Stores the smallest missing // non-negative integers between // start index to current index let smNonNeg = 0; // Store the boolean value to check // smNonNeg present between start // index to each index of the array let hash = []; for(let i = 0; i < N; i++) { hash[i] = false; } // Traverse the array for(let i = 0; i < N; i++) { // Since output always lies // in the range[0, N - 1] if (arr[i] >= 0 && arr[i] < N) { hash[arr[i]] = true; } // Check if smNonNeg is // present between start index // and current index or not while (hash[smNonNeg]) { smNonNeg++; } // Print smallest missing // non-negative integer document.write(smNonNeg + " "); }} // Driver Codelet arr = [ 0, 1, 2, 3, 5 ];let N = arr.length; smlstNonNeg(arr, N); // This code is contributed by target_2 </script> 1 2 3 4 4 Time Complexity: O(N)Auxiliary Space: O(N) mohit kumar 29 sanjoy_62 code_hunt target_2 simranarora5sos khushboogoyal499 ankita_saini frequency-counting Arrays Greedy Hash Mathematical Arrays Hash Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Huffman Coding | Greedy Algo-3 Write a program to print all permutations of a given string
[ { "code": null, "e": 24847, "s": 24819, "text": "\n10 Nov, 2021" }, { "code": null, "e": 25004, "s": 24847, "text": "Given an array arr[] of size N, the task is for every array indices is to find the smallest missing non-negative integer upto that index of the given array." }, ...
Default to and select the first item in Tkinter Listbox
Tkinter Listbox widgets are used to display a scrollable list of items with vertically stacked menus. Sometimes, we may need to set the list item selected, by default. We can use the select_set(list_item_index) method by specifying the index of the list items that need to be selected by default. So, let us suppose that we have a list of programming languages in our Listbox and what we want is to set the first item selected, then we can provide the index of a first list item in the method. The method must be invoked before the end of mainloop() function. #Import tkinter library from tkinter import * #Create an instance of Tkinter frame or window win= Tk() #Set the geometry of tkinter frame win.geometry("750x250") listbox=Listbox(win) #Create a listbox widget listbox.pack(padx=10,pady=10,fill=BOTH, expand=True) listbox.insert(1, "Python") listbox.insert(2, "Java") listbox.insert(3, "C++") listbox.insert(4, "Rust") listbox.insert(5, "GoLang") listbox.insert(6, "C#") listbox.insert(7, "JavaScript") listbox.insert(8, "R") listbox.insert(9, "Php") #Select the first item of listbox listbox.select_set(0) win.mainloop() Running the above code will display a list of programming languages. In the given output, the first list item in the list box is selected, by default.
[ { "code": null, "e": 1359, "s": 1062, "text": "Tkinter Listbox widgets are used to display a scrollable list of items with vertically stacked menus. Sometimes, we may need to set the list item selected, by default. We can use the select_set(list_item_index) method by specifying the index of the list...
What is the difference between All and Any in C# Linq?
Any(<predicate>) method returns true if at least one of the elements in the source sequence matches the provided predicate. Otherwise, it returns false. On the other hand, the All(<predicate>) method returns true if every element in the source sequence matches the provided predicate. Otherwise, it returns false static void Main(string[] args){ IEnumerable<double> doubles = new List<double> { 1.2, 1.7, 2.5, 2.4 }; bool result = doubles.Any(val => val < 1); System.Console.WriteLine(result); IEnumerable<double> doubles1 = new List<double> { 0.8, 1.7, 2.5, 2.4 }; bool result1 = doubles1.Any(val => val < 1); System.Console.WriteLine(result1); Console.ReadLine(); } False True static void Main(string[] args){ IEnumerable<double> doubles = new List<double> { 0.8, 0.9, 0.6, 0.7 }; bool result = doubles.All(val => val < 1); System.Console.WriteLine(result); IEnumerable<double> doubles1 = new List<double> { 0.8, 0.9, 1.0, 0.7 }; bool result1 = doubles1.All(val => val < 1); System.Console.WriteLine(result1); Console.ReadLine(); } True False
[ { "code": null, "e": 1375, "s": 1062, "text": "Any(<predicate>) method returns true if at least one of the elements in the source sequence matches the provided predicate. Otherwise, it returns false. On the other hand, the All(<predicate>) method returns true if every element in the source sequence ...
ReactJS – shouldComponentUpdate() method
In this article, we are going to see how to increase the performance of React application by rerendering the component only when the props passed to it changes or on when certain conditions are met. This method is majorly used to take an exit from the complex React lifecycle, but using it extensively may lead to bugs in the application. shouldComponentUpdate(nextProps, nextState) By default, the return value of this method is true; but if it returns false, then the render(), componentWillUpdate() and componentDidUpdate() methods are not called. In this example, we will build a React application with components only getting re-rendered if the props passed to them changes. Our first component in the following example is App. This component is the parent of the MyComp component. We are creating MyComp separately and just adding it inside the JSX tree in our App component. Only the App component needs to be exported. App.jsx import React from 'react'; class App extends React.Component { constructor() { super(); this.state = { color: '#000' }; } render() { return ( <div> <h1 style={{ color: this.state.color }}>Tutorialspoint</h1> <button onClick={() => this.setState({ color: '#ff0000' })}> Change Color </button> <MyComp /> </div> ); } } class MyComp extends React.Component { shouldComponentUpdate(nextProps) { // Rendering the component only if // passed props value is changed if (nextProps.value !== this.props.value) { return true; } else { return false; } } render() { console.log('MyComp component is called'); return ( <div> <h1>Simply Easy Learning</h1> </div> ); } } export default App; In the above example, MyComp component gets re-rendered only if the received props and the previous props are different. The above code will generate the following result − In the next example, we are going to execute the same code without shouldComponentUpdate() method to see the difference. App.jsx import React from 'react'; class App extends React.Component { constructor() { super(); this.state = { color: '#000' }; } render() { return ( <div> <h1 style={{ color: this.state.color }}>Tutorialspoint</h1> <button onClick={() => this.setState({ color: '#ff0000' })}> Change Color </button> <MyComp /> </div> ); } } class MyComp extends React.Component { render() { console.log('MyComp component is called'); return ( <div> <h1>Simply Easy Learning</h1> </div> ); } } export default App; Here, MyComp component gets re-rendered every time when the parent component, i.e., the App component gets re-rendered. The above code will generate the following result −
[ { "code": null, "e": 1261, "s": 1062, "text": "In this article, we are going to see how to increase the performance of React application by rerendering the component only when the props passed to it changes or on when certain conditions are met." }, { "code": null, "e": 1401, "s": 12...
Using Bayesian Hierarchical Models in PyMC3 to Infer the Disease Parameters of COVID-19 | by Srijith Rajamohan, Ph.D. | Towards Data Science
In this post, we look at how to use PyMC3 to infer the disease parameters for COVID-19. PyMC3 is a popular probabilistic programming framework that is used for Bayesian modeling. Two popular methods to accomplish this are the Markov Chain Monte Carlo (MCMC) and Variational Inference methods. The work here looks at using the currently available data for the infected cases in the United States as a time-series and attempts to model this using a compartmental probabilistic model. We want to try to infer the disease parameters and eventually estimate R0 using MCMC sampling. We will then explore how to do the same using Bayesian hierarchical models and the benefits compared to a pooled or an unpooled model. We conclude with the limitations of this model and outline the steps for improving the inference process. The work presented here is for illustration purposes only and real-life Bayesian modeling requires far more sophisticated tools than what is shown here. Various assumptions regarding population dynamics are made here, which may not be valid for large non-homogeneous populations. Also, interventions such as social distancing and vaccinations are not considered here. This post will cover the following: Compartmental models for EpidemicsWhere the data comes from and how it is ingestedThe SIR/SIRS models for disease dynamicsBayesian Inference for ODEs with PyMC3Extension of the work with hierarchical modelsGuidelines and debugging tips for probabilistic programming Compartmental models for Epidemics Where the data comes from and how it is ingested The SIR/SIRS models for disease dynamics Bayesian Inference for ODEs with PyMC3 Extension of the work with hierarchical models Guidelines and debugging tips for probabilistic programming I have also launched a series of courses on Coursera covering this topic of Bayesian modeling and inference, courses 2 and 3 are particularly relevant to this post. Check them out at: https://www.coursera.org/specializations/compstats . For an overview of compartmental models and their behavior, please refer to this notebook in Julia — https://github.com/sjster/Epidemic. Compartmental models are a set of Ordinary Differential Equations (ODEs) for closed populations, which imply that there is no movement of the population in or out of this compartment. These aim to model disease propagation in compartments of populations that are homogeneous. As you can imagine, these assumptions may not be valid in large populations. It is also important to point out here that vital statistics such as the number of births and deaths in the population may not be included in this model. The following list mentions some of the compartmental models along with the various compartments of disease propagation, however, this is not an exhaustive list by any means. Susceptible Infected (SI) Susceptible Infected Recovered (SIR) Susceptible Infected Susceptible (SIS) Susceptible Infected Recovered Susceptible (SIRS) Susceptible Infected Recovered Dead (SIRD) Susceptible Exposed Infected Recovered (SEIR) Susceptible Exposed Infected Recovered Susceptible (SEIRS) Susceptible Exposed Infected Recovered Dead (SEIRD) Maternally-derived Immunity Susceptible Infectious Recovered (MSIR) SIDARTHE (https://www.nature.com/articles/s41591-020-0883-7) The last one listed above is more recent and specifically targets COVID-19 and maybe worth a read for those interested. Real-world disease modeling often involves more than just the temporal evolution of disease stages since many of the assumptions associated with compartments are violated. To understand how the disease propagates, we would want to look at the spatial discretization and evolution of the progression of the disease through the population. An example of a framework that models this spatio-temporal evolution is GLEAM (Fig.1). ​ Fig. 1- Real-world epidemic modeling (spatio-temporal dynamics). Tools such as GLEAM use the population census data and the mobility patterns to understand how people move geographically. GLEAM divides the globe into spatial grids of roughly 25km x 25km. There are broadly two types of mobility: global or long-range mobility and local or short-range mobility. Long-term mobility mostly involves air travel and as such airports are considered a central hub for disease transmission. Travel by sea is also another significant factor and therefore naval ports are another type of access point. Along with the mathematical models listed above, this provides a stochastic framework that can be used to make millions of simulations to draw inferences about parameters and make forecasts. The data used here is obtained from the Johns Hopkins CSSE Github page where case counts are regularly updated: CSSE GitHub Confirmed cases Number of deaths The data is available as CSV files which can be read in through Python pandas. The SIR model is given by the set of three Ordinary Differential Equations (ODEs) shown below. There are three compartments in this model. Here ‘S’, ‘I’ and ‘R’ refer to the susceptible, infected and recovered portions of the population of size ’N’ such that The assumption here is that once you have recovered from the disease, lifetime immunity is conferred on an individual. This is not the case for a lot of diseases and hence may not be a valid model. λ is the rate of infection and μ is the rate of recovery from the disease. The fraction of people who recover from the infection is given by ‘f’ but for the purpose of this work, ‘f’ is set to 1 here. We end up with an Initial Value Problem (IVP) for our set of ODEs where I(0) is assumed to be known from the case counts at the beginning of the pandemic and S(0) can be estimated as N — I(0). Here we make the assumption that the entire population is susceptible. Our goal is to accomplish the following: Use Bayesian Inference to make estimates about λ and μ Use the above parameters to estimate I(t) for any time ‘t’ Compute R0 As already pointed out, λ is the disease transmission coefficient. This depends on the number of interactions, in unit time, with infectious people. This in turn depends on the number of infectious people in the population. The force of infection or risk at any time ‘t’ is defined as: Also, μ is the fraction of recovery that happens in unit time. The inverse of μ is hence the mean recovery time. The ‘basic reproduction number’ R0 is the average number of secondary cases produced by a single primary case (Examples https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6002118/). R0 is also defined in terms of the λ and μ as the ratio given by The above assumes that S0 is close to 1. When R0>1, we have a proliferation of the disease and we have a pandemic. With the recent efforts to vaccinate the vulnerable, this has become even more relevant to understand. If we vaccinate a fraction ‘p’ of the population to get (1−p)R0<1, we can halt the spread of the disease. The SIRS model, shown below, makes no assumption of lifetime immunity once an infected person has recovered. Therefore, one goes from the recovered compartment to the susceptible compartment. As such, this is probably a better low-fidelity baseline model for COVID-19 where it is suggested that the acquired immunity is short-term. The only additional parameter here is γ which refers to the rate at which immunity is lost and the infected individual moves from the recovered pool to the susceptible pool. For this work, only the SIR model is implemented, and the SIRS model and its variants are left for future work. We can discretize the SIR model using a first-order or a second-order temporal differentiation scheme which can then be passed to PyMC3 which will march the solution forward in time using these discretized equations. The parameters λ and μ can then be fitted using the Monte Carlo sampling procedure. While we can provide the discretization manually with our choice of a higher-order discretization scheme, this quickly becomes cumbersome and error-prone not to mention computationally inefficient in a language like Python. Fortunately, PyMC3 has an ODE module to accomplish this. We can use the DifferentialEquation method from the ODE module which takes as input a function that returns the value of the set of ODEs as a vector, the time steps where the solution is desired, the number of states corresponding to the number of equations and the number of variables we would like to have solved. Even though this is still faster than manual discretization, this method scales poorly with problem size. The recommended best practice is to use the ‘sunode’ module (see below) in PyMC3. For example, the same problem took 5.4 mins using DifferentialEquations vs. 16s with sunode for 100 samples,100 tuning samples and 20 time points. self.sir_model_non_normalized = DifferentialEquation( func = self.SIR_non_normalized, times = self.time_range1:], n_states = 2, n_theta = 2, t0 = 0)def SIR_non_normalized(self, y, t, p): ds = -p[0] * y[0] * y[1] / self.covid_data.N, di = p[0] * y[0] * y[1] / self.covid_data.N — p[1] * y[1] return[ds, di] The syntax for using the sunode module is shown below. While there are some syntactic differences, the general structure is the same as that of DifferentialEquations. import sunodeimport sunode.wrappers.as_theanodef SIR_sunode(t, y, p): return { ‘S’: -p.lam * y.S * y.I, ‘I’: p.lam * y.S * y.I — p.mu * y.I}......sir_curves, _, problem, solver, _, _ = sunode.wrappers.as_theano.solve_ivp( y0={ # Initial conditions of the ODE ‘S’: (S_init, ()), ‘I’: (I_init, ()),}, params={ # Parameters of the ODE, specify shape ‘lam’: (lam, ()), ‘mu’: (mu, ()), ‘_dummy’: (np.array(1.), ())} # currently, sunode throws an error, without this # RHS of the ODE rhs=SIR_sunode, # Time points of th solution tvals=times, t0=times[0],) In order to perform inference on the parameters we seek, we start by selecting reasonable priors for the disease parameters. Based on our understanding of the behavior of the disease phenomenon, a lognormal distribution is a reasonable prior for the disease parameters. Ideally, we want the mean parameter of this lognormal to be in the neighborhood of what we expect the desired parameters to reside. For good convergence and solutions, it is also essential that the data likelihood is appropriate (domain expertise!). It is common to pick one of the following as the likelihood. Normal distribution Lognormal distribution Student’s t-distribution We obtain the Susceptible (S(t)) and Infectious (I(t)) numbers from the ODE solver and then sample for values of λ and μ as shown below. with pm.Model() as model4: sigma = pm.HalfCauchy(‘sigma’, self.likelihood[‘sigma’], shape=1) lam = pm.Lognormal(‘lambda’, self.prior[‘lam’], self.prior[‘lambda_std’]) # 1.5, 1.5 mu = pm.Lognormal(‘mu’, self.prior[‘mu’], self.prior[‘mu_std’]) res, _, problem, solver, _, _ = sunode.wrappers.as_theano.solve_ivp( y0={‘S’: (self.S_init, ()), ‘I’: (self.I_init, ()),}, params={‘lam’: (lam, ()), ‘mu’: (mu, ()), ‘_dummy’: (np.array(1.), ())}, rhs=self.SIR_sunode, tvals=self.time_range, t0=self.time_range[0]) # likelihood distribution mean, these are the predictions from the SIR model ODE solver if(likelihood[‘distribution’] == ‘lognormal’): I = pm.Lognormal(‘I’, mu=res[‘I’], sigma=sigma, observed=self.cases_obs_scaled) elif(likelihood[‘distribution’] == ‘normal’): I = pm.Normal(‘I’, mu=res[‘I’], sigma=sigma, observed=self.cases_obs_scaled) elif(likelihood[‘distribution’] == ‘students-t’): I = pm.StudentT( “I”, nu=likelihood[‘nu’], \ mu=res[‘I’], sigma=sigma, observed=self.cases_obs_scaled) R0 = pm.Deterministic(‘R0’,lam/mu) trace = pm.sample(self.n_samples, tune=self.n_tune, chains=4, cores=4) data = az.from_pymc3(trace=trace) Since developing a model such as this, for estimating the disease parameters using Bayesian inference, is an iterative process we would like to automate away as much as possible. It is probably a good idea to instantiate a class of model objects with various parameters and have automated runs. It is also a good idea to save the trace information, inference metrics such as R̂ (R-hat) along with other metadata information for each run. A file format such as NetCDF can be used for this although it could be as simple as using the Python built-in database module ‘shelve’. The classes for data extraction are not shown here, but their invocations are shown so that you get a sense for the data and the model parameters used here. covid_obj = COVID_data(‘US’, Population=328.2e6)covid_obj.get_dates(data_begin=’10/1/20', data_end=’10/28/20')sir_model = SIR_model_sunode(covid_obj)likelihood = {‘distribution’: ‘normal’, ‘sigma’: 2}prior = {‘lam’: 1.5,‘mu’: 1.5, ‘lambda_std’: 1.5, ‘mu_std’: 1.5 }sir_model.run_SIR_model(n_samples=500, n_tune=500, likelihood=likelihood, prior=prior) These results are purely for illustration purposes and extensive experimentation is needed before meaningful results can be expected from this simulation. The case count for the United States from January to October is shown below (Fig 2). Fig. 2 - Example COVID-19 case count visualization for the US Fig. 3 shows the results of an inference run where the posterior distributions of λ, μ and R0 are displayed. One of the advantages of performing Bayesian inference is that the distributions show the mean value estimate along with the Highest Density Interval (HDI) for quantifying uncertainty. It is a good idea to check the trace (at the very least!) to ensure sampling was done properly. ​ Fig. 3 - Example results of an inference run displaying the Highest Density Interval (HDI) using PyMC3. Suppose you have information regarding the number of infections from various states in the United States. One way to use this data to infer the disease parameters of COVID-19 (e.g. R0) is to sum it all up to estimate a single parameter. This is called a pooled model. However, the problem with this approach is that fine-grained information that might be contained in these individual states or groups is lost. The other extreme would be to estimate an individual parameter R0 per state. This approach results in an unpooled model. However, considering that we are trying to estimate the parameters corresponding to the same virus, there has to be a way to perform this collectively, which brings us to the hierarchical model. This is particularly useful when there isn’t sufficient information in certain states to create accurate estimates. Hierarchical models allow us to share the information from other states using a shared ‘hyperprior’. Let us look at this formulation in more detail using the example for : For a pooled model, we can draw from a single distribution with fixed parameters λ_μ, λ_σ For an unpooled model, we can draw λi for each state from distributions with fixed parameters λ_μi, λ_σi For a hierarchical model, we have a prior that is parameterized by non-constant parameters drawn from other distributions. Here, we draw a λ value for each state, however they are connected through shared hyperprior distributions (with constant parameters) as shown below. Check out course 3 Introduction to PyMC3 for Bayesian Modeling and Inference (https://www.coursera.org/learn/introduction-to-pymc3?specialization=compstats) in the recently-launched Coursera specialization for more details on hierarchical models. Here we plot and use the case count of infections-per-day for two countries, the United States and Brazil. However, there is no limitation on either the choice or number of countries that can be used in a hierarchical model. The cases below are from Mar 1, 2020 to Jan 1, 2021. The graphs seem to follow a similar trajectory, even though the scales on the y-axis are different for these countries. Considering that these cases are from the same COVID-19 virus, this is reasonable. However, in a realistic scenario there are differences to account for, such as the different variants, different geographical structures and social distancing rules, healthcare infrastructure and so on. Fig. 4 - Plot of the number of COVID-19 cases for two countries For a hierarchical model, the code snippet to perform the inference of the disease parameters is given below. with pm.Model() as model4: # narrow std is roughly equivalent to a constant prior parameter, if there are issues with sampling from the prior distribution # make the variance of the mean smaller. Variance of the distribution of the variance parameter seems less relevant in this regard. nsamples = 8000 ntune = 4000 Hyperprior = {“Lambda mean”: 0.75, “Lambda std”: 2, “Mu mean”: 0.75, “Mu std”: 2} Prior = {“Lambda std”: 1.0, “Mu std”: 1.0} Likelihood = {“Name”: “Normal”, “Parameters”: {“std”: 0.01}} prior_lam = pm.Lognormal(‘prior_lam’, Hyperprior[‘Lambda mean’], Hyperprior[‘Lambda std’]) prior_mu = pm.Lognormal(‘prior_mu’, Hyperprior[‘Mu mean’], Hyperprior[‘Mu std’]) prior_lam_std = pm.HalfNormal(‘prior_lam_std’, Prior[‘Lambda std’]) prior_mu_std = pm.HalfNormal(‘prior_mu_std’, Prior[‘Mu std’]) lam = pm.Lognormal(‘lambda’, prior_lam , prior_lam_std, shape=2) mu = pm.Lognormal(‘mu’, prior_mu , prior_mu_std, shape=2) # — — — — — — — — — — ODE model — — — — — — — — # res, _, problem, solver, _, _ = sunode.wrappers.as_theano.solve_ivp( y0={ ‘S’: (S_init, (2,)), ‘I’: (I_init, (2,)),}, params={‘lam’: (lam, (2,)), ‘mu’: (mu, (2,)), ‘_dummy’: (np.array(1.), ())}, rhs=SIR_sunode, tvals=time_range[1:], t0=time_range[0]) I = pm.Normal(‘I’, mu=res[‘I’], sigma=Likelihood[‘Parameters’][‘std’], observed=cases_obs_scaled[1:]) R0 = pm.Deterministic(‘R0’,lam/mu) # if you increase the variance and the distributions looks choppy, increase the tuning sample size to sample the space more effectively # also, increase the total number of samples trace = pm.sample(nsamples, tune=ntune, chains=8, cores=8) data = az.from_pymc3(trace=trace) The sampled posterior distributions are shown below, along with their 94% Highest Density Interval (HDI). Fig. 5 - The sampled posterior distributions along with their 94% Highest Density Interval (HDI). We can also inspect the traceplots for convergence, which shows good mixing in all the variables — a good sign that the sampler has explored the space well. There is good agreement between all the traces. This behavior can be confirmed with the fairly narrow HDI intervals in the plots above. Fig. 6 - The traceplots and density plots for R0 and other variables The table below summarizes the distributions of the various inferred variables and parameters, along with the sampler statistics. While estimates about the variables are essential, this table is particularly useful for informing us about the quality and efficiency of the sampler. For example, the R-hat is all close to or equal to 1.0, indicating good agreement between all the chains. The effective sample size is another critical metric. If this is small compared to the total number of samples, that is a sure sign of trouble with the sampler. Even if the R-hat values look good, be sure to inspect the effective sample size! Fig. 7 - Table of the inferred variable distributions along with the sampling statistics Some general guidelines for modeling and inference: Use at least 5000 samples and 1000 samples for tuning. For the results shown above, I have used: Mean: λ= 1.5, = 1.5, Standard deviation: 2.0 for both parameters. A domain expert and his knowledge is invaluable in setting these parameters. Sample from 3 chains at least. Set target_accept to > 0.85 (depends on the sampling algorithm). If possible, sample in parallel with cores=n, where ’n’ is the number of cores available. Inspect the trace for convergence. Limited time-samples have an impact on inference accuracy, it is always better to have more good quality data. Normalize your data, large values are generally not good for convergence Since the backend for PyMC3 is theano, the Python print statement cannot be used to inspect the value of a variable. Use theano.printing.Print(DESCRIPTIVE_STRING)(VAR) to accomplish this. Initialize stochastic variables by passing a ‘testval’. This is very helpful to check those pesky ‘Bad Energy’ errors, which are usually due to poor choice of likelihoods or priors. Use Model.check_test_point() to verify this. Use step = pm.Metropolis() for quick debugging, this runs much faster but results in a rougher posterior. If the sampling is slow, check your prior and likelihood distributions. A narrow sigma value for a prior distribution can be used to simulate a constant prior and can help debug issues with sampling from the prior distribution. If increasing the variance results in a choppy posterior distribution, increase both the tuning sample size and the number of samples to sample the space more effectively. Although this yielded satisfactory estimates for our parameters, often we run into the issue of the sampler not performing effectively. For future work, there are a few ways to diagnose and improve the modeling process. These are listed, in increasing order of difficulty, below: Increase the tuning size and the number of samples drawn.Decrease the target_accept parameter for the sampler so as to reduce the autocorrelation among the samples. Use the autocorrelation plot to confirm this.Add more samples to the observed data, i.e. increase the sample frequency.Use better priors and hyperpriors for the parameters.Use an alternative parameterization of the model.Incorporate changes such as social-distancing measures into the model. Increase the tuning size and the number of samples drawn. Decrease the target_accept parameter for the sampler so as to reduce the autocorrelation among the samples. Use the autocorrelation plot to confirm this. Add more samples to the observed data, i.e. increase the sample frequency. Use better priors and hyperpriors for the parameters. Use an alternative parameterization of the model. Incorporate changes such as social-distancing measures into the model. You can learn more about these topics at my Coursera specialization (https://www.coursera.org/specializations/compstats) that consists of the following courses: Introduction to Bayesian Statistics (https://www.coursera.org/learn/compstatsintro?specialization=compstats)Bayesian Inference with MCMC (https://www.coursera.org/learn/mcmc?specialization=compstats)Introduction to PyMC3 for Bayesian Modeling and Inference (https://www.coursera.org/learn/introduction-to-pymc3?specialization=compstats) Introduction to Bayesian Statistics (https://www.coursera.org/learn/compstatsintro?specialization=compstats) Bayesian Inference with MCMC (https://www.coursera.org/learn/mcmc?specialization=compstats) Introduction to PyMC3 for Bayesian Modeling and Inference (https://www.coursera.org/learn/introduction-to-pymc3?specialization=compstats) The work by the Priesemann Group The work by the Priesemann Group github.com 2. Work by Demetri Pananos on the PyMC3 website
[ { "code": null, "e": 989, "s": 171, "text": "In this post, we look at how to use PyMC3 to infer the disease parameters for COVID-19. PyMC3 is a popular probabilistic programming framework that is used for Bayesian modeling. Two popular methods to accomplish this are the Markov Chain Monte Carlo (MCM...
Difference between HashMap and ConcurrentHashMap in Java
Following are the notable differences between HashMap and ConcurrentHashMap classes in Java. import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class Tester { public static void main(String[] args) { List<String> arrayList = new ArrayList<>(); arrayList.add("A"); arrayList.add("B"); arrayList.add("C"); Iterator<String> iterator = arrayList.iterator(); System.out.println(arrayList); while (iterator.hasNext()) { if (iterator.next().equals("C")) { //removal is allowed. iterator.remove(); } } System.out.println(arrayList); List<String> copyOnWriteArrayList = new CopyOnWriteArrayList<>(); copyOnWriteArrayList.add("A"); copyOnWriteArrayList.add("B"); copyOnWriteArrayList.add("C"); Iterator<String> iterator1 = copyOnWriteArrayList.iterator(); System.out.println(copyOnWriteArrayList); while (iterator1.hasNext()) { if (iterator1.next().equals("C")) { try{ iterator1.remove(); }catch(UnsupportedOperationException e){ System.out.println("Removal not allowed."); } } } System.out.println(copyOnWriteArrayList); } } [A, B, C] [A, B] [A, B, C] Removal not allowed. [A, B, C]
[ { "code": null, "e": 1155, "s": 1062, "text": "Following are the notable differences between HashMap and ConcurrentHashMap classes in Java." }, { "code": null, "e": 2402, "s": 1155, "text": "import java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport j...
Constructors in C++ - GeeksQuiz
02 Dec, 2021 Predict output of the following program C ew_c_questiongeeksforgeeks new_c_quesgeeksforgeeks geeksforgeeks Depends on terminal configuration See http://stackoverflow.com/questions/17236242/usage-of-b-and-r-in-c Output of following program? C++ Compiler Error Constructor called None of these Runtime Error By default all members of a class are private. Since no access specifier is there for Point(), it becomes private and it is called outside the class when t1 is constructed in main. Point *t1, *t2; // No constructor call t1 = new Point(10, 15); // Normal constructor call t2 = new Point(*t1); // Copy constructor call Point t3 = *t1; // Copy Constructor call Point t4; // Normal Constructor call t4 = t3; // Assignment operator call Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Must Do Coding Questions for Product Based Companies Microsoft Interview Experience for Internship (Via Engage) Difference between var, let and const keywords in JavaScript Array of Objects in C++ with Examples How to Replace Values in Column Based on Condition in Pandas? C Program to read contents of Whole File How to Replace Values in a List in Python? How to Read Text Files with Pandas? Infosys DSE Interview Experience | On-Campus 2021 HackWithInfy - A Coding Competition by Infosys
[ { "code": null, "e": 27219, "s": 27191, "text": "\n02 Dec, 2021" }, { "code": null, "e": 27260, "s": 27219, "text": "Predict output of the following program " }, { "code": null, "e": 27262, "s": 27260, "text": "C" }, { "code": null, "e": 27290, ...
Can we synchronize abstract methods in Java?
An abstract method is the one that does not have a body. It contains only a method signature with a semi colon and, an abstract keyword before it. public abstract myMethod(); To use an abstract method, you need to inherit it by extending its class and provide implementation (body) to it. If a class contains at least one abstract method, you must declare it abstract. Live Demo import java.io.IOException; abstract class MyClass { public abstract void display(); } public class AbstractClassExample extends MyClass{ public void display(){ System.out.println("subclass implementation of the display method"); } public static void main(String args[]) { new AbstractClassExample().display(); } } subclass implementation of the display method Synchronization − If a process has multiple threads running independently at the same time (multi-threading) and if all of them trying to access the same resource an issue occurs. To resolve this, Java provides synchronized blocks/ synchronized methods. If you define a resource (variable/object/array) inside a synchronized block or a synchronized method, if one thread is using/accessing it, other threads are not allowed to access. synchronized (Lock1) { System.out.println("Thread 1: Holding lock 1..."); } No, you can’t synchronize abstract methods in Java. When you synchronize a method that implies that you are synchronizing the code in it, i.e. when one thread is accessing the code of a synchronized method no other thread is allowed to access it. So synchronizing abstract methods doesn’t make sense, if you still try to do so a compile-time error will be generated. import java.io.IOException; public abstract class MyClass { public abstract synchronized void display(); } MyClass.java:3: error: illegal combination of modifiers: abstract and synchronized public abstract synchronized void display(); ^ 1 error
[ { "code": null, "e": 1209, "s": 1062, "text": "An abstract method is the one that does not have a body. It contains only a method signature with a semi colon and, an abstract keyword before it." }, { "code": null, "e": 1237, "s": 1209, "text": "public abstract myMethod();" }, ...
Deploying Keras models using TensorFlow Serving and Flask | by Himanshu Rawlani | Towards Data Science
Often there’s a need to abstract away your machine learning model details and just deploy or integrate it with easy to use API endpoints. For eg., We can provide a URL endpoint using which anyone can make a POST request and they would get a JSON response of what the model has inferred without having to worry about its technicalities. In this tutorial, we will create a TensorFlow Serving server to deploy our InceptionV3 image classification convolutional neural network (CNN) built in Keras. We will then create a simple Flask server which will accept POST request and do some image preprocessing, required for Tensorflow serving server, and return a JSON response. Serving is how you apply machine learning model after you’ve trained it. TensorFlow Serving makes the process of taking a model into production easier and faster. It allows you to safely deploy new models and run experiments while keeping the same server architecture and APIs. Out of the box, it provides integration with TensorFlow, but it can be extended to serve other types of models. Prerequisite: Please create a python virtual environment and install Keras with TensorFlow backend in it. Read more here. Note: All the commands have been executed in python virtual environment on Ubuntu 18.04.1 LTS. Now, inside the same virtual environment run the following commands (use sudo for root permissions): $ apt install curl$ echo "deb [arch=amd64] http://storage.googleapis.com/tensorflow-serving-apt stable tensorflow-model-server tensorflow-model-server-universal" | sudo tee /etc/apt/sources.list.d/tensorflow-serving.list && curl https://storage.googleapis.com/tensorflow-serving-apt/tensorflow-serving.release.pub.gpg | sudo apt-key add -$ apt-get update$ apt-get install tensorflow-model-server$ tensorflow_model_server --versionTensorFlow ModelServer: 1.10.0-devTensorFlow Library: 1.11.0$ python --versionPython 3.6.6 You can upgrade to a newer version of tensorflow-model-server with: $ apt-get upgrade tensorflow-model-server Understanding directory structure, before we get started, will help us in getting a clear picture of where we are at each step. (tensorflow) ubuntu@Himanshu:~/Desktop/Medium/keras-and-tensorflow-serving$ tree -c└── keras-and-tensorflow-serving ├── README.md ├── my_image_classifier │ └── 1 │ ├── saved_model.pb │ └── variables │ ├── variables.data-00000-of-00001 │ └── variables.index ├── test_images │ ├── car.jpg │ └── car.png ├── flask_server │ ├── app.py │ ├── flask_sample_request.py └── scripts ├── download_inceptionv3_model.py ├── inception.h5 ├── auto_cmd.py ├── export_saved_model.py ├── imagenet_class_index.json └── serving_sample_request.py6 directories, 15 files You can get all of these files from my GitHub repository: github.com For this tutorial, we will download and save InceptionV3 CNN, having Imagenet weights, in Keras using download_inceptionv3_model.py. You can download any other model available in keras.applications library (here) or if you have built your own model in Keras then you can skip this step. After executing the above script you should get the following output: $ python download_inceptionv3_model.pyUsing TensorFlow backend.Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.5/inception_v3_weights_tf_dim_ordering_tf_kernels.h596116736/96112376 [==============================] - 161s 2us/step Now we have our InceptionV3 CNN (inception.h5) saved in Keras format. We want to export our model in a format that the TensorFlow server can handle. We do this by executing export_saved_model.py script. TensorFlow provides the SavedModel format as a universal format for exporting models. Under the hood, our Keras model is fully specified in terms of TensorFlow objects, so we can export it just fine using Tensorflow methods. TensorFlow provides a convenience function tf.saved_model.simple_save() which abstracts away some of these details and works fine for most use cases. Output: $ python export_saved_model.pyWARNING:tensorflow:No training configuration found in save file: the model was *not* compiled. Compile it manually. We get this warning because we have downloaded a pre-trained model. We can use this model for inference as is, but if we want to train it further, we need to run the compile() function after loading it. This warning can be safely ignored for now. After executing this script, the following files are saved in my_image_classifier directory: ├── my_image_classifier └── 1 ├── saved_model.pb └── variables ├── variables.data-00000-of-00001 └── variables.index2 directories, 3 files Suppose we want to update our model in the future (maybe because we have collected more training data and trained the model on the updated dataset), we can do so by, Running the same script on the new keras modelUpdating export_path = ‘../my_image_classifier/1’ to export_path = ‘../my_image_classifier/2’ in export_saved_model.py Running the same script on the new keras model Updating export_path = ‘../my_image_classifier/1’ to export_path = ‘../my_image_classifier/2’ in export_saved_model.py TensorFlow Serving will automatically detect the new version of the model, in my_image_classifier directory, and update it in the server. To start TensorFlow Serving server on your local machine, run the following command: $ tensorflow_model_server --model_base_path=/home/ubuntu/Desktop/Medium/keras-and-tensorflow-serving/my_image_classifier --rest_api_port=9000 --model_name=ImageClassifier --model_base_path: This has to be an absolute path else you will get an error saying: Failed to start server. Error: Invalid argument: Expected model ImageClassifier to have an absolute path or URI; got base_path()=./my_image_classifier --rest_api_port: Tensorflow Serving will start a gRPC ModelServer on port 8500 and the REST API will be available on port 9000. --model_name: This will be the name of your Serving server using which you will send a POST request. You can type any name you want here. The serving_sample_request.py script makes a POST request to the TensorFlow Serving server. The input image is passed via command line argument. Output: $ python serving_sample_request.py -i ../test_images/car.pngUsing TensorFlow backend.[["n04285008", "sports_car", 0.998414], ["n04037443", "racer", 0.00140099], ["n03459775", "grille", 0.000160794], ["n02974003", "car_wheel", 9.57862e-06], ["n03100240", "convertible", 6.01581e-06]] TensorFlow Serving server takes slightly more time for responding to the first request as compared to subsequent calls. As we can see, we have performed some image preprocessing steps in serving_sample_request.py (frontend caller). Following are the reasons to create Flask server on top of TensorFlow serving server: When we are providing our API endpoint to frontend team we need to ensure that we don’t overwhelm them with preprocessing technicalities. We might not always have a Python backend server (eg. Node.js server) so using numpy and keras libraries, for preprocessing, might be a pain. If we are planning to serve multiple models then we will have to create multiple TensorFlow Serving servers and will have to add new URLs to our frontend code. But our Flask server would keep the domain URL same and we only need to add a new route (a function). Providing subscription-based access, exception handling and other tasks can be carried out in the Flask app. What we are trying to do is eliminate tight coupling between TensorFlow Serving servers and our Frontend. For this tutorial, we will create a Flask server on the same machine and in the same virtual environment as that of TensorFlow Serving and make use of the installed libraries. Ideally, both should be running on separate machines because a higher number of requests would cause the Flask server to slow down because of the image preprocessing being carried out. Also, a single Flask server might not be sufficient if the number of requests is really high. We may also need a queuing system if we have multiple frontend callers. Nonetheless, we can use this method to develop a satisfactory proof of concept. Prerequisite: Install Flask, in python virtual environment from here. We just need a single app.py file in order to create our Flask server. Go to the directory where you have saved your app.py file and start the Flask server with the following command: $ export FLASK_ENV=development && flask run --host=0.0.0.0 FLASK_ENV=development: This enables debug mode which basically gives you complete error logs. Don’t use this in a production environment. The flask run command automatically executes the app.py file in the current directory. --host=0.0.0.0: This enables you to make requests, to the Flask server, from any other machine. To make a request from a different machine, you will have to specify the IP address of the machine where the Flask server is running in place of localhost. Output: * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)* Restarting with stat* Debugger is active!* Debugger PIN: 1xx-xxx-xx4Using TensorFlow backend. Start the TensorFlow Serving server using the same previous command: $ tensorflow_model_server --model_base_path=/home/ubuntu/Desktop/Medium/keras-and-tensorflow-serving/my_image_classifier --rest_api_port=9000 --model_name=ImageClassifier Here’s a script (auto_cmd.py) to automate starting and stopping of the two servers (TensorFlow Serving and Flask). You can modify this script for more than two servers as well. Remember to change the path at line 10 of auto_cmd.py to make it point to your app.py’s directory. You may also need to change line 6 in order to make it point to your virtual environment’s bin. You can then execute the above script from any directory by executing following in your terminal: $ python auto_cmd.py We make a sample request using the flask_sample_request.py script. The script basically mimics request from the frontend: We take an input image, encode it to base64 format and send it to our Flask server using POST request.Flask server decodes this base64 image and pre-processes it for our TensorFlow Serving server.Flask server then makes a POST request to our TensorFlow serving server and decodes the response.The decoded response is formatted and sent back to the frontend. We take an input image, encode it to base64 format and send it to our Flask server using POST request. Flask server decodes this base64 image and pre-processes it for our TensorFlow Serving server. Flask server then makes a POST request to our TensorFlow serving server and decodes the response. The decoded response is formatted and sent back to the frontend. Output: $ python flask_sample_request.py -i ../test_images/car.png[ [ "n04285008", "sports_car", 0.998414 ], [ "n04037443", "racer", 0.00140099 ], [ "n03459775", "grille", 0.000160794 ], [ "n02974003", "car_wheel", 9.57862e-06 ], [ "n03100240", "convertible", 6.01581e-06 ]] Our flask server currently has only a single route for our single Tensorflow Serving server. We can serve multiple models by creating multiple Tensorflow serving servers on different or same machine. For that we just need to add more routes (functions) to our app.py file and perform required model specific pre-processing in it. We can give these routes to our frontend team to call the models as required. Consider a scenario where we make a POST request using Angular, our Flask server receives OPTIONS header and not POST because, A web application makes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin. CORS (Cross Origin Resource Sharing) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. Read more about CORS here. Hence, Angular doesn’t get back any response from the Flask server. To solve this we have to enable Flask-CORS in our app.py. Know more about it here. And that’s all we need to serve our machine learning model. TensorFlow Serving makes it really easy to integrate machine learning into websites and other applications. With plenty of prebuilt models available in keras (here), it’s possible to develop super useful applications with minimal knowledge of machine learning and deep learning algorithms. If you found this tutorial helpful, please do share it with your friends and leave a clap :-). If you have any queries, feedback or suggestions do let me know in the comments. Also, you can connect with me on Twitter and LinkedIn. There is so much to share with all of you and I’m just getting started. Stay tuned for more!
[ { "code": null, "e": 508, "s": 172, "text": "Often there’s a need to abstract away your machine learning model details and just deploy or integrate it with easy to use API endpoints. For eg., We can provide a URL endpoint using which anyone can make a POST request and they would get a JSON response ...
How to start Service using Alarmmanager in Kotlin Android?
This example demonstrates how to start Service using Alarmmanager in Kotlin Android. Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" android:padding="16sp"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="40dp" android:text="Tutorials Point" android:textAlignment="center" android:textColor="@android:color/holo_blue_light" android:textSize="32sp" android:textStyle="bold" /> <Button android:id="@+id/btnStartService" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:text="Start Service Alarm" /> <Button android:id="@+id/btnStopService" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="Cancel Service" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.kt import android.app.AlarmManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import java.util.* class MainActivity : AppCompatActivity() { private lateinit var btnStart: Button private lateinit var btnStop: Button lateinit var pendingIntent: PendingIntent override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" btnStart = findViewById(R.id.btnStartService) btnStop = findViewById(R.id.btnStopService) btnStart.setOnClickListener { val myIntent = Intent(this@MainActivity, MyAlarmService::class.java) pendingIntent = PendingIntent.getService(this@MainActivity, 0, myIntent, 0) val alarmManager: AlarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager val calendar: Calendar = Calendar.getInstance() calendar.timeInMillis = System.currentTimeMillis() calendar.add(Calendar.SECOND, 3) alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent) Toast.makeText(baseContext, "Starting Service Alarm", Toast.LENGTH_LONG).show() } btnStop.setOnClickListener { val alarmManager: AlarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager alarmManager.cancel(pendingIntent) Toast.makeText(baseContext, "Service Cancelled", Toast.LENGTH_LONG).show() } } } Step 4 − Add the following code to src/MyAlarmService.kt import android.app.Service import android.content.Intent import android.os.IBinder import android.widget.Toast @Suppress("DEPRECATION") class MyAlarmService : Service() { override fun onCreate() { Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show(); super.onCreate() } override fun onBind(intent: Intent?): IBinder? { Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show(); return null } override fun onDestroy() { super.onDestroy() Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show() } override fun onStart(intent: Intent?, startId: Int) { super.onStart(intent, startId) Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show() } override fun onUnbind(intent: Intent?): Boolean { Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show() return super.onUnbind(intent) } } Step 5 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.kotlipapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1147, "s": 1062, "text": "This example demonstrates how to start Service using Alarmmanager in Kotlin Android." }, { "code": null, "e": 1276, "s": 1147, "text": "Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required d...
Efficient Use of TigerGraph and Docker | by David Baker Effendi | Towards Data Science
TigerGraph is my graph database and graph analytics platform of choice as it is fast, scalable, and has an active open-source community. I regularly make use of TigerGraph locally due to my location not having nearby TigerGraph Cloud servers. At the time of writing, the TigerGraph software requirements specify support for the following operating systems: Redhat and Centos versions 6.5–6.9, 7.0–7.4, and 8.0–8.2 Ubuntu 14.04, 16.04, and 18.04 Debian 8 For anyone using operating systems beyond this list, a logical solution would be to make use of containerization: Docker, in the case of this article. In this article we will cover: How to make use of the official TigerGraph and what’s insideStripping the official Docker image of unnecessary bloatModifying the ENTRYPOINT to add: How to make use of the official TigerGraph and what’s inside Stripping the official Docker image of unnecessary bloat Modifying the ENTRYPOINT to add: Running gadmin on startup Run GSQL scripts bound at a certain directory Route the output from a log file to STDOUT 4. Using Docker Compose to run TigerGraph images The official TigerGraph image, running the developer edition, can be obtained by the following command: docker pull docker.tigergraph.com/tigergraph-dev:latest Run with: docker run -d -p 14022:22 -p 9000:9000 -p 14240:14240 --name tigergraph_dev --ulimit nofile=1000000:1000000 -v ~/data:/home/tigergraph/mydata -t docker.tigergraph.com/tigergraph-dev:latest This source gives more in-depth instructions on how the image is constructed, but in summary: A base image of Ubuntu 16.04 is used All required software such as tar, curl, etc. are installed Optional software such as emacs, vim, wget, etc. are installed GSQL 101 and 102 tutorials and the GSQL Algorithms library is downloaded An SSH server, REST++ API, and GraphStudio are the 3 notable ports which can be exposed and used to communicate with the server The total image is close to a 1.8–2.0GB download (version dependent) which puts considerable strain on bandwidth — especially with resource-sensitive use cases like CI/CD. Another notable point is that all one needs to make use of TigerGraph is a GSQL socket connection which can be interfaced with by tools such as Giraffle and pyTigerGraph. I’ve identified two large sources of bloat which are: The optional and unnecessary software e.g. vim and GSQL Tutorial 101 GraphStudio and binaries not necessary for the minimal operation of TigerGraph Developer Edition I’ve replaced the base image ubuntu:16.04 with Bitnami’s MiniDeb image in order to shave off a few megabytes of unnecessary space. This runs Debian Jessie. The next step was to remove unnecessary binaries installed during the apt-get stage of the official image. I’ve kept Vim as the only command-line text editor but binaries such as wget, git, unzip, emacs, etc. are no longer installed. During the TigerGraph installation, the hardware requirements are strictly enforced and the installation will fail if they are not met. Since I want DockerHub runners to automatically build and push my image, I hacked the check such that the low-resource runners can continue to build the image. This is done by replacing the os_utils binary with my version, which makes the check_cpu_number() and check_memory_capacity() functions more lenient. This binary can be found under: /home/tigergraph/tigergraph-${DEV_VERSION}-developer/utils/os_utils This has already reduced the bloat by around 400MB and my DockerHub image reports a compressed size TigerGraph 3.0.0 of 1.52GB (I did notice that downloading these layers indicates that it comes to around 1.62GB). Note: I have attempted to haphazardly delete GraphStudio binaries but this fails the gadmin start script so there will have to be more meticulous adjustments made in order to remove more from TigerGraph, e.g editing the gadmin Python scripts. The final result between the two images once I’ve downloaded and uncompressed them can be seen by calling docker images: The source code for my build can be found here and I encourage anyone with suggestions to contact me! UPDATE (2/11/2020): Thanks to Bruno Šimić for reaching out and building on this work to slim down the TigerGraph Enterprise Edition and share his code with me. The following additional stripping is his work that has been implemented in this image. There appears to be documentation and unnecessary build artifacts (such as many node_modules) under the installation directory. Examples of where these can be found are under: ${INSTALL_DIR}/app/${DEV_VERSION}/document/ ${INSTALL_DIR}/app/${DEV_VERSION}/bin/gui/server/node_modules ${INSTALL_DIR}/app/${DEV_VERSION}/bin/gui/node/lib/node_modules ${INSTALL_DIR}/app/${DEV_VERSION}/gui/server/node_modules/ ${INSTALL_DIR}/app/${DEV_VERSION}/.syspre/usr/share/ ${INSTALL_DIR}/app/${DEV_VERSION}/.syspre/usr/lib/jvm/java-8-openjdk-amd64–1.8.0.171/ Where INSTALL_DIR is /home/tigergraph/tigergraph for TigerGraph Developer Edition v3 and DEV_VERSION is the specific version e.g. 3.0.0. Performing a fresh pull of the TigerGraph Developer Edition v3.0.5 and comparing it to my new v3.0.5 we see the following amount of disk space used: Before we add features let’s have a look at the original ENTRYPOINT: ENTRYPOINT /usr/sbin/sshd && su — tigergraph bash -c “tail -f /dev/null” This does two things: The SSH server is started by running /usr/sbin/ssh .The container is kept alive by running thetail command as user tigergraph. What this does is constantly read output from /dev/null which is also why the container’s STDOUT is empty. The SSH server is started by running /usr/sbin/ssh . The container is kept alive by running thetail command as user tigergraph. What this does is constantly read output from /dev/null which is also why the container’s STDOUT is empty. As a way to improve user experience I’ve added a line that starts gadmin services on the Docker entry point from ENTRYPOINT /usr/sbin/sshd && su - tigergraph bash -c "tail -f /dev/null" to ENTRYPOINT /usr/sbin/sshd && su - tigergraph bash -c "/home/tigergraph/tigergraph/app/cmd/gadmin start all && tail -f /dev/null" A very simple but valuable change! Something that the TigerGraph Docker Image lacks (which other database images such as MySQL, MariaDB, and PostgreSQL has) is a directory named something along the lines of docker-entrypoint-init.d where a user can bind database scripts to run at startup e.g. for schema creation or database population. There are various ways to go about this but I’ve chosen a fairly simple way of implementing this by adding the following line between the gadmin and tail command: How this command works is: The if-command will check if a directory called /docker-entrypoint-initdb.d exists and will not perform the next step unless this is true.The for file in /docker-entrypoint-initdb.d/*.gsql; do line will start a for-each loop of all the files ending with the gsql extension in the entry point folder.The su tigergraph bash -c line will run the GSQL command on the file given by the for-each loop.By appending || continue, the container nor the loop will stop if the script failed to execute. The if-command will check if a directory called /docker-entrypoint-initdb.d exists and will not perform the next step unless this is true. The for file in /docker-entrypoint-initdb.d/*.gsql; do line will start a for-each loop of all the files ending with the gsql extension in the entry point folder. The su tigergraph bash -c line will run the GSQL command on the file given by the for-each loop. By appending || continue, the container nor the loop will stop if the script failed to execute. This will most likely look neater if placed into an entrypoint.sh but this is up to you! The final result now looks something like this: In order to figure out where the logs belong, one can run gadmin log which will return something along the lines of ADMIN : /home/tigergraph/tigergraph/log/admin/ADMIN#1.outADMIN : /home/tigergraph/tigergraph/log/admin/ADMIN.INFOCTRL : /home/tigergraph/tigergraph/log/controller/CTRL#1.logCTRL : /home/tigergraph/tigergraph/log/controller/CTRL#1.outDICT : /home/tigergraph/tigergraph/log/dict/DICT#1.outDICT : /home/tigergraph/tigergraph/log/dict/DICT.INFOETCD : /home/tigergraph/tigergraph/log/etcd/ETCD#1.outEXE : /home/tigergraph/tigergraph/log/executor/EXE_1.logEXE : /home/tigergraph/tigergraph/log/executor/EXE_1.out...etc I’m mostly interested in the admin logs so I will change the tail command to read from /home/tigergraph/tigergraph/log/admin/ADMIN.INFO instead of /dev/null. Now anything written to the admin logs will be piped to the container’s logs automatically. The final product from all three steps are now: Note that I have added a health check which calls the REST++ echo endpoint every 5 seconds to determine if the container is healthy or not. If you use the official image, you would need to SSH into the container to manually start all services: If you would like a GSQL script to run on startup, add the following entry under volumes: - my_script.gsql:/docker-entrypoint-initdb.d/my_script.gsql Note that I have added a health check which calls the REST++ echo endpoint every 5 seconds to determine if the container is healthy or not. This is useful for many applications and, in my use-case, is used to check if the container is ready during integration testing before starting the tests. If you use the official image, you would need to SSH into the container to manually start all services: The default password is “tigergraph” after which you would call the command gadmin start all (v3.0.0 >=)gadmin start (v3.0.0<) GraphStudio can then be found on localhost:14240 on your web browser and Rest++ can be found on localhost:9000. In this article we have: Inspected the official Dockerfile, identified and removed obvious unnecessary files, built a slimmer version of the TigerGraph image saving a considerable amount of disk space, modified the ENTRYPOINT to add additional automation to the container, and used Docker Compose to run this image. If you have any suggestions or thoughts on ways to further reduce the size of the image, then leave a comment, issue, or fork and give a pull request on the GitHub repository for the code in this article. If you would like to see more Docker-related guides for building custom setups for databases such as JanusGraph then leave a comment below. You can find these images on Docker Hub, and I will continue to update this as new versions come out or until TigerGraph makes an official slimmer version. If you would like to join the TigerGraph community and contribute, or start awesome projects and get a deeper look into what’s coming for TigerGraph, then join us on the following platforms: Discord Reddit Twitch If you are interested in seeing some of my other work, then have a look at my personal page at https://davidbakereffendi.github.io/. Credits go to Jon Herke at TigerGraph for his leadership in the community and equipping us to contribute in meaningful ways and Bruno Šimić for sharing his findings in slimming down the TigerGraph Enterprise Edition image which can be found at https://hub.docker.com/r/xpertmind/tigergraph. Some rights reserved
[ { "code": null, "e": 415, "s": 172, "text": "TigerGraph is my graph database and graph analytics platform of choice as it is fast, scalable, and has an active open-source community. I regularly make use of TigerGraph locally due to my location not having nearby TigerGraph Cloud servers." }, { ...
Merge Pandas dataframe with a common column and set NaN for unmatched values
To merge two Pandas DataFrame with common column, use the merge() function and set the ON parameter as the column name. To set NaN for unmatched values, use the “how” parameter and set it left or right. That would mean, merging left or right. At first, let us import the pandas library with an alias − import pandas as pd Let us create DataFrame1 − dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 80, 110, 90] } ) Let us create DataFrame2 dataFrame2 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000] } ) Now, merge DataFrames with common column Car. The left" “displays all the values of the left DataFrame and sets NaN for unmatched values from 2nd DataFrame − mergedRes = pd.merge(dataFrame1, dataFrame2, on ='Car', how ="left") Following is the code import pandas as pd # Create DataFrame1 dataFrame1 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 80, 110, 90] } ) print("DataFrame1 ...\n",dataFrame1) # Create DataFrame2 dataFrame2 = pd.DataFrame( { "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000] } ) print("\nDataFrame2 ...\n",dataFrame2) # merge DataFrames with common column Car and "left" sets NaN for unmatched values from second DataFrame mergedRes = pd.merge(dataFrame1, dataFrame2, on ='Car', how ="left") print("\nMerged data frame with common column...\n", mergedRes) Following is the code − DataFrame1 ... Car Units 0 BMW 100 1 Lexus 150 2 Audi 110 3 Mustang 80 4 Bentley 110 5 Jaguar 90 DataFrame2 ... Car Reg_Price 0 BMW 7000 1 Lexus 1500 2 Tesla 5000 3 Mustang 8000 4 Mercedes 9000 5 Jaguar 6000 Merged data frame with common column... Car Units Reg_Price 0 BMW 100 7000.0 1 Lexus 150 1500.0 2 Audi 110 NaN 3 Mustang 80 8000.0 4 Bentley 110 NaN 5 Jaguar 90 6000.0
[ { "code": null, "e": 1305, "s": 1062, "text": "To merge two Pandas DataFrame with common column, use the merge() function and set the ON parameter as the column name. To set NaN for unmatched values, use the “how” parameter and set it left or right. That would mean, merging left or right." }, { ...
Playlist Classification on Spotify using KNN and Naive Bayes Classifier | by Nev Acar | Towards Data Science
One day, I thought it would be cool if Spotify helped me pick a playlist when I like a song. The idea is to touch on the plus button when my phone is locked and Spotify add it into one of my playlists rather than library so that I don’t go into the app and try to pick a playlist that it suits well. This way, I wouldn’t have to choose a playlist among all of my playlists and I would just leave it to the algorithms. Then, I realized it makes a good side project for a machine learning enthusiast. After all, I started this project to avoid unlocking my phone and think for three seconds which is not the most optimized solution for me as an individual. You can find the Jupyter Notebook on https://github.com/n0acar/spotify-playlist-selection This is actually where everything starts. I found Spotify Web API and Spotipy framework. By the combination of both, we will be able to extract official Spotify data with useful features. spotipy.readthedocs.io developer.spotify.com Before sending a request to Spotify Web API, you need to install and import dependencies below. import spotipyimport spotipy.util as utilfrom spotipy.oauth2 import SpotifyClientCredentials In order to get access to API, you will need special codes created only for your application. Go to https://developer.spotify.com/dashboard/ and click “Create a Client ID” or “Create an App” to get your “Client ID” and “Client Secret”. After that, Redirect URI must be changed to any page you decide on in the settings of your Spotify application. client_id= "YOUR_CLIENT_ID"client_secret= "YOUR_CLIENT_SECRET"redirect_uri='http://google.com/' Next, state your scope from Spotipy documentation and “sp” will be your access key to Spotify data, from now on. username='n.acar'client_credentials_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret) scope = 'user-library-read playlist-read-private'try: token = util.prompt_for_user_token(username, scope,client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri) sp=spotipy.Spotify(auth= token)except: print('Token is not accesible for ' + username) Then, you can do a lot with that sp variable. It is your Spotify object. For example, you can extract your song library, take the data of a playlist or better, all playlists of a user. songLibrary = sp.current_user_saved_tracks()playlist = sp.user_playlist(username, playlist_id='6TXpoloL4A7u7kgqqZk6Lb')playlists = sp.user_playlists(username) To find ID numbers of playlists or tracks, basically use sharing link and get the code out of it. Everything the API provides come in JSON format and you can basically extract the information you need out of that. For various usage of Spotify data, you can go through the documentations of Spotipy and Spotify Web API. There are plenty of methods and data types that might be good use for a project. When human beings listen to a song, they perceive several aspects of it. A person probably does not have trouble determining whether a track is acoustic or electronic. Most of the people having some kind of music sense can say a lot about music that can be hard to get for a computer. However, Spotify API provides some useful features about any track on the platform. Most of them are normalized between 0 and 1 so they are pretty easy to tackle. Below is a comparison of two Spotify playlists called “Classical Essentials” represented by blue and “Get Turnt” (a rap playlist by Spotify) represented by red. From these plots, you can see that these two genres show distinct patterns by the nature of the music. While the rap playlist has higher values in terms of danceability, energy, loudness, speechiness, valence and tempo, the classical music playlist have higher acousticness and instrumentalness values as expected. I used two algorithms which are K-Nearest Neighbors and Naive Bayes Classification. Actually, I only wanted to implement a couple of basic algorithm from scratch and I realized those are the most convenient ones to start with. K-Nearest Neighbors Classification: K -Nearest Neighbor (KNN) algorithm is a classification technique that utilizes the feature similarity between existing and new data based on the notion of distance. Naive Bayes Classification: Naive Bayes Classification is a method which calculates the probability of every feature as if they are independent and determines the outcome with the highest probability based on Baye’s Theorem. The statistical distinction between the two is pretty obvious. I excluded tempo and loudness from my feature list since they didn’t contain much information about the genre and very scattered. I used first 35 songs of the playlists for training and rest of the songs for testing. The testing set might not be the most objective one out of the subjective nature of music genres. Since both playlists are created by Spotify, I thought it’s the safest way to test the algorithms. Luckily, our target is to classify rap and classical music, the statistics don’t make any mistakes and we get 100% accuracy rate. Even if all songs turned out to be in their right category, one classical song was almost going to the wrong bucket upon using KNN. It is called Violin Concerto BWV 1042 in E Major: I. Allegro. It wasn’t even close to a rap song when using Naive Bayes Classification, yet it is still the closest thing to a rap in classical music playlist. At first, I tried to find the closest rap songs in terms of distance which is Crushed Up by Future so it was a bit surprising. Then, I checked the features of this classical song which actually looks a bit faulty to me. (Give it a listen! At least the “instrumentalness” feature should be greater than zero.) Nevertheless, this wasn’t a hard task. To make things more complicated and evaluate the algorithms better, I decided to add one more playlist which is “Rock Save the Queen”. NBC looks more consistent than KNN. That classical song mentioned above is not in classical music playlist anymore because of newcoming rock songs. Still, NBC doesn’t make any mistake. However, in Get Turnt playlist, things are a little bit different. Deciding the genre based on only closest neighbors is not a good idea for rap songs this time. The most confused rap song is “EA” by “Wifisfuneral” and “Robb Bank$” and it ended up in rock bucket. To make things more challenging I added a new playlist, “Coffee Table Jazz”, created by again Spotify. Before showing you the results, I’d like to add updated visualization of the four playlists the algorithms use in the final model. I will refer to these at the final step when I investigate the results. (Rock Save the Queen and Coffee Table Jazz are represented by yellow and orange, respectively.) From these, we clearly see that classical music and jazz music genres are statistically close to each other while the same is true for rock and rap genres. This is why when rock music is introduced, the newcoming songs didn’t cause any confusion of classical songs but damaged the accuracy rate of Get Turnt. The same case occurred when Coffee Table Jazz was introduced to the system. This time, classical music classification by KNN is severely hurt. Knowing that classical music is only confused with jazz, 51% accuracy rate is almost random. This shows that considering only the closest neighbors don’t work to classify the genre. At least, it is safe to say NBC is much better. NBC couldn’t work for classical and jazz music as well as it works for rap and rock. I think this is the case because the way people distinguish classical songs from jazz is classifying the different instruments used traditionally. Even if there is a bit of difference between them in terms of danceability, that is not enough for some of the songs. The other features are almost the same which is expected. Instrumentalness; however, is almost exactly same as it can be seen on the spider graph. Yes, they are obviously both instrumental, yet this is where this feature comes short of human sense. Maybe, Spotify providing another data type of which instruments or types of instruments are specifically used in a song might resolve this problem as well. I think 98.44% accuracy rate is great for the other two playlist. NBC only missed one of the songs from each playlist. They are STARGAZING by Travis Scott which is identified as rock and Distant Past by Everything Everything as rap. (If you listen to them, please share your comments.) The aim of this project is to create undetermined genres of given playlists and classify the new songs accordingly. It is supposed to work for any playlist that has the same type of songs in it. I opt to use four clearly genre-labeled playlists created by Spotify. I used two different algorithms which are KNN and NBC as mentioned in the post. NBC outperformed KNN overall. The challenges this system might encounter is to distinguish two different playlist with very close genres. I also realized that features that Spotify provides might not be enough for some cases. Don’t hesitate to ask questions and give feedback. Music, genres, and overall this work are subjective. I appreciate any comment on the results since the topic is open for discussion. Cheers, Nev Give me a follow for more content and support! Connect with me on Twitter and LinkedIn...
[ { "code": null, "e": 827, "s": 172, "text": "One day, I thought it would be cool if Spotify helped me pick a playlist when I like a song. The idea is to touch on the plus button when my phone is locked and Spotify add it into one of my playlists rather than library so that I don’t go into the app an...
Finding frequency in list of tuples in Python
Many different types of data container can get mixed up in python. A list can have elements each of which is a tuple. In this article we will take such a list and find the frequency of element in the tuples which are themselves elements of a list. We apply a lambda function to count through each of the first element in the tuples present in the list. Then apply a map function to arrive at the total count of the element we are searching for. Live Demo # initializing list of tuples listA = [('Apple', 'Mon'), ('Banana', 'Tue'), ('Apple', 'Wed')] # Given list print("Given list of tuples : " ,listA) # Frequency in list of tuples Freq_res = list(map(lambda i: i[0], listA)).count('Apple') # printing result print("The frequency of element is : ",Freq_res) Running the above code gives us the following result: Given list of tuples : [('Apple', 'Mon'), ('Banana', 'Tue'), ('Apple', 'Wed')] The frequency of element is : 2 We can also implement Counter which will count the number of occurrences of an element. We use a for loop to go through each of the tuple present in the list. Live Demo from collections import Counter # initializing list of tuples listA = [('Apple', 'Mon'), ('Banana', 'Tue'), ('Apple', 'Wed')] # Given list print("Given list of tuples : " ,listA) # Frequency in list of tuples Freq_res = Counter(i[0] for i in listA)['Apple'] # printing result print("The frequency of element is : ",Freq_res) Running the above code gives us the following result − Given list of tuples : [('Apple', 'Mon'), ('Banana', 'Tue'), ('Apple', 'Wed')] The frequency of element is : 2
[ { "code": null, "e": 1310, "s": 1062, "text": "Many different types of data container can get mixed up in python. A list can have elements each of which is a tuple. In this article we will take such a list and find the frequency of element in the tuples which are themselves elements of a list." },...
Delimiters in MySQL?
Delimiters can be used when you need to define the stored procedures, function as well as to create triggers. The default delimiter is semicolon. You can change the delimiters to create procedures and so on. However, but if you are considering multiple statements, then you need to use different delimiters like $$ or //. Here we have a table “GetRecordFromNow” wherein the following are the records − +---------------------+ | YourDateTime | +---------------------+ | 2018-12-07 22:30:18 | | 2018-12-03 22:30:31 | | 2018-12-02 22:30:41 | | 2018-12-01 22:30:56 | | 2018-12-03 22:31:04 | +---------------------+ 5 rows in set (0.00 sec) The delimiter keyword is a type of function in MySQL client. Here is the demo of delimiter that calls the above table using delimiter − mysql> delimiter // mysql> create procedure DisplayALL() −> begin −> select *from GetRecordsFromNow; −> end −> // Query OK, 0 rows affected (0.40 sec) mysql> delimiter ; mysql> call DisplayALL(); +---------------------+ | YourDateTime | +---------------------+ | 2018-12-07 22:30:18 | | 2018-12-03 22:30:31 | | 2018-12-02 22:30:41 | | 2018-12-01 22:30:56 | | 2018-12-03 22:31:04 | +---------------------+ 5 rows in set (0.07 sec) Query OK, 0 rows affected (0.10 sec)
[ { "code": null, "e": 1208, "s": 1062, "text": "Delimiters can be used when you need to define the stored procedures, function as well as to create triggers. The default delimiter is semicolon." }, { "code": null, "e": 1384, "s": 1208, "text": "You can change the delimiters to cre...
LeafletJS - Getting Started
Leaflet.js is an open-source library using which we can deploy simple, interactive, lightweight web maps. Leaflet JavaScript library allows you to use layers such as Tile layers, WMS, Markers, Popups, Vector layers (polylines, polygons, circles, etc.), Image overlays and GeoJSON. Leaflet JavaScript library allows you to use layers such as Tile layers, WMS, Markers, Popups, Vector layers (polylines, polygons, circles, etc.), Image overlays and GeoJSON. You can interact with the Leaflet maps by dragging the map, zooming (by double click or, wheel scroll), using keyboard, using event handling, and by dragging the markers. You can interact with the Leaflet maps by dragging the map, zooming (by double click or, wheel scroll), using keyboard, using event handling, and by dragging the markers. Leaflet supports browsers such as Chrome, Firefox, Safari 5+, Opera 12+, IE 7–11 on desktop and, browsers like Safari, Android, Chrome, Firefox for mobiles. Leaflet supports browsers such as Chrome, Firefox, Safari 5+, Opera 12+, IE 7–11 on desktop and, browsers like Safari, Android, Chrome, Firefox for mobiles. Follow the steps given below to load a map on your webpage − Create a basic HTML page with head and body tags as shown below − <!DOCTYPE html> <html> <head> </head> <body> ........... </body> </html> Include the Leaflet CSS script in the example − <head> <link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" /> </head> Load or include the Leaflet API using the script tag − <head> <script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script> </head> To hold the map, we have to create a container element. Generally, the <div> tag (a generic container) is used for this purpose. Create a container element and define its dimensions − <div id = "sample" style = "width:900px; height:580px;"></div> Leaflet provides several options such as types Control options, Interaction Options, Map State Options, Animation Options, etc. By setting values to these, we can customize the map as desired. Create a mapOptions object (it is created just like a literal) and set values for the options center and zoom, where center − As a value to this option, you need to pass a LatLng object specifying the location where we want to center the map. (Just specify the latitude and longitude values within [] braces) center − As a value to this option, you need to pass a LatLng object specifying the location where we want to center the map. (Just specify the latitude and longitude values within [] braces) zoom − As a value to this option, you need to pass an integer representing the zoom level of the map, as shown below. zoom − As a value to this option, you need to pass an integer representing the zoom level of the map, as shown below. var mapOptions = { center: [17.385044, 78.486671], zoom: 10 } Using the Map class of leaflet API, you can create a map on a page. You can create a map object by instantiating the called Map of the Leaflet API. While instantiating this class, you need to pass two parameters − As a parameter to this option, you need to pass a String variable representing the DOM id or an instance of the <div> element. Here, the <div>element is an HTML container to hold the map. As a parameter to this option, you need to pass a String variable representing the DOM id or an instance of the <div> element. Here, the <div>element is an HTML container to hold the map. An optional object literal with map options. An optional object literal with map options. Create a Map object by passing the id of the <div> element and mapOptions object created in the previous step. var map = new L.map('map', mapOptions); You can load and display various types of maps (tile layers) by instantiating the TileLayer class. While instantiating it you need to pass an URL template requesting the desired tile layer(map) from the service provider, in the form of a String variable. Create the tile layer object as shown below. var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'); Here we have used the openstreetmap. Finally add the layer created in the previous step to the map object using the addlayer() method as shown below. map.addLayer(layer); The following example shows how to load an open street map of Hyderabad city with a zoom value of 10. <!DOCTYPE html> <html> <head> <title>Leaflet sample</title> <link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/> <script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script> </head> <body> <div id = "map" style = "width: 900px; height: 580px"></div> <script> // Creating map options var mapOptions = { center: [17.385044, 78.486671], zoom: 10 } // Creating a map object var map = new L.map('map', mapOptions); // Creating a Layer object var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'); // Adding layer to the map map.addLayer(layer); </script> </body> </html> It generates the following output − Just like open street map, you can load the layers of various service providers such as Open Topo, Thunder forest, Hydda, ESRI, Open weather, NASA GIBS, etc. To do so, you need to pass their respective URL while creating the TileLayer object var layer = new L.TileLayer('URL of the required map'); The following table lists the URL’s and their respective sample maps of the layers provided by Openstreetmap. http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png http://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/ {y}.png http://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png http://tile.openstreetmap.bzh/br/{z}/{x}/{y}.png Print Add Notes Bookmark this page
[ { "code": null, "e": 1904, "s": 1798, "text": "Leaflet.js is an open-source library using which we can deploy simple, interactive, lightweight web maps." }, { "code": null, "e": 2079, "s": 1904, "text": "Leaflet JavaScript library allows you to use layers such as Tile layers, WMS...
Query deeply nested Objects in MongoDB
To query deeply nested objects, use dot(.) notation in MongoDB. Let us create a collection with documents − > db.demo350.insertOne( ... { ... id:101, ... Name: "Chris", ... details: [ ... { ... _id: 1, ... ClientNumber: "10001", ... ClientDetails: [ . ... { ... Name:"David", ... Age:29 ... }, ... { ... Name:"Bob", ... Age:31 ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e553a68f8647eb59e5620b8") } > db.demo350.insertOne( ... { ... id:102, ... Name: "David", ... details: [ ... { ... _id: 2, ... ClientNumber: "10002", ... ClientDetails: [ ... { ... Name:"Carol", ... Age:42 ... }, ... { ... Name:"John", ... Age:37 ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e553a8ff8647eb59e5620b9") } Display all documents from a collection with the help of find() method − > db.demo350.find(); This will produce the following output − { "_id" : ObjectId("5e553a68f8647eb59e5620b8"), "id" : 101, "Name" : "Chris", "details" : [ { "_id" : 1, "ClientNumber" : "10001", "ClientDetails" : [ { "Name" : "David", "Age" : 29 }, { "Name" : "Bob", "Age" : 31 } ] } ] } { "_id" : ObjectId("5e553a8ff8647eb59e5620b9"), "id" : 102, "Name" : "David", "details" : [ { "_id" : 2, "ClientNumber" : "10002", "ClientDetails" : [ { "Name" : "Carol", "Age" : 42 }, { "Name" : "John", "Age" : 37 } ] } ] } Following is how to query deeply nested objects − > db.demo350.find({"details.ClientDetails.Name":"John"}); This will produce the following output − { "_id" : ObjectId("5e553a8ff8647eb59e5620b9"), "id" : 102, "Name" : "David", "details" : [ { "_id" : 2, "ClientNumber" : "10002", "ClientDetails" : [ { "Name" : "Carol", "Age" : 42 }, { "Name" : "John", "Age" : 37 } ] } ] }
[ { "code": null, "e": 1170, "s": 1062, "text": "To query deeply nested objects, use dot(.) notation in MongoDB. Let us create a collection with documents −" }, { "code": null, "e": 2187, "s": 1170, "text": "> db.demo350.insertOne(\n... {\n... id:101,\n... Name: \"Chris\",\n....
Combine date and time column into a timestamp in MySQL?
To combine date and time column into a timestamp, you can use cast() function with concat(). The syntax is as follows − select cast(concat(yourDateColumnName, ' ', yourTimeColumnName) as datetime) as anyVariableName from yourTableName; In the above concept, you will use cast() when your date and time is in string format. The cast() function can be used only for datetime. To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table DateAndTimeToTimestamp −> ( −> Duedate date, −> DueTime time −> ); Query OK, 0 rows affected (0.51 sec) Insert records in the table using insert command. The query is as follows − mysql> insert into DateAndTimeToTimestamp values(date_add(curdate(),interval 2 day),'10:30:02'); Query OK, 1 row affected (0.34 sec) mysql> insert into DateAndTimeToTimestamp values(date_add(curdate(),interval -2 day),'12:20:45'); Query OK, 1 row affected (0.17 sec) mysql> insert into DateAndTimeToTimestamp values(date_add(curdate(),interval 1 day),'01:32:42'); Query OK, 1 row affected (0.21 sec) mysql> insert into DateAndTimeToTimestamp values(date_add(curdate(),interval -1 day),'14:25:58'); Query OK, 1 row affected (0.30 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from DateAndTimeToTimestamp; The following is the output − +------------+----------+ | Duedate | DueTime | +------------+----------+ | 2018-12-16 | 10:30:02 | | 2018-12-12 | 12:20:45 | | 2018-12-15 | 01:32:42 | | 2018-12-13 | 14:25:58 | +------------+----------+ 4 rows in set (0.00 sec) Here is the query to combine date and time column into timestamp − mysql> select concat(Duedate, ' ', DueTime) as timestampDemo from DateAndTimeToTimestamp; The following is the output − +---------------------+ | timestampDemo | +---------------------+ | 2018-12-16 10:30:02 | | 2018-12-12 12:20:45 | | 2018-12-15 01:32:42 | | 2018-12-13 14:25:58 | +---------------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1155, "s": 1062, "text": "To combine date and time column into a timestamp, you can use cast() function with concat()." }, { "code": null, "e": 1182, "s": 1155, "text": "The syntax is as follows −" }, { "code": null, "e": 1298, "s": 1182, ...
Assignment Operators in C
The following table lists the assignment operators supported by the C language − Try the following example to understand all the assignment operators available in C − #include <stdio.h> main() { int a = 21; int c ; c = a; printf("Line 1 - = Operator Example, Value of c = %d\n", c ); c += a; printf("Line 2 - += Operator Example, Value of c = %d\n", c ); c -= a; printf("Line 3 - -= Operator Example, Value of c = %d\n", c ); c *= a; printf("Line 4 - *= Operator Example, Value of c = %d\n", c ); c /= a; printf("Line 5 - /= Operator Example, Value of c = %d\n", c ); c = 200; c %= a; printf("Line 6 - %= Operator Example, Value of c = %d\n", c ); c <<= 2; printf("Line 7 - <<= Operator Example, Value of c = %d\n", c ); c >>= 2; printf("Line 8 - >>= Operator Example, Value of c = %d\n", c ); c &= 2; printf("Line 9 - &= Operator Example, Value of c = %d\n", c ); c ^= 2; printf("Line 10 - ^= Operator Example, Value of c = %d\n", c ); c |= 2; printf("Line 11 - |= Operator Example, Value of c = %d\n", c ); } When you compile and execute the above program, it produces the following result − Line 1 - = Operator Example, Value of c = 21 Line 2 - += Operator Example, Value of c = 42 Line 3 - -= Operator Example, Value of c = 21 Line 4 - *= Operator Example, Value of c = 441 Line 5 - /= Operator Example, Value of c = 21 Line 6 - %= Operator Example, Value of c = 11 Line 7 - <<= Operator Example, Value of c = 44 Line 8 - >>= Operator Example, Value of c = 11 Line 9 - &= Operator Example, Value of c = 2 Line 10 - ^= Operator Example, Value of c = 0 Line 11 - |= Operator Example, Value of c = 2 Print Add Notes Bookmark this page
[ { "code": null, "e": 2165, "s": 2084, "text": "The following table lists the assignment operators supported by the C language −" }, { "code": null, "e": 2251, "s": 2165, "text": "Try the following example to understand all the assignment operators available in C −" }, { "...
Python Program to Count the Number of Occurrences of an Element in the Linked List without using Recursion
When it is required to count the number of occurrences of a specific element in a linked list without using recursion, a method to add elements to the linked list, a method to display the elements of the linked list, and a method to count the occurrences of a value are defined. Below is a demonstration for the same − Live Demo class Node: def __init__(self, data): self.data = data self.next = None class my_linked_list: def __init__(self): self.head = None self.last_node = None def add_value(self, my_data): if self.last_node is None: self.head = Node(my_data) self.last_node = self.head else: self.last_node.next = Node(my_data) self.last_node = self.last_node.next def print_it(self): curr = self.head while curr: print(curr.data) curr = curr.next def count_val(self, key): curr = self.head my_count = 0 while curr: if curr.data == key: my_count = my_count + 1 curr = curr.next return my_count my_instance = my_linked_list() my_list = [56, 43, 70, 67, 89, 91, 70, 23, 46, 70] for elem in my_list: my_instance.add_value(elem) print("The linked list contains the below elements:") my_instance.print_it() key_val = int(input('Enter the data item: ')) count_val = my_instance.count_val(key_val) print('{0} occurs {1} time(s) in the list.'.format(key_val, count_val)) The linked list contains the below elements: 56 43 70 67 89 91 70 23 46 70 Enter the data item: 70 70 occurs 3 time(s) in the list. The ‘Node’ class is created. The ‘Node’ class is created. Another ‘my_linked_list’ class with required attributes is created. Another ‘my_linked_list’ class with required attributes is created. It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’ and last node to ‘None’. It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’ and last node to ‘None’. Another method named ‘add_value’ is defined, that is used to add data to the linked list. Another method named ‘add_value’ is defined, that is used to add data to the linked list. Another method named ‘print_it’ is defined, that iterates over the list, and prints the elements. Another method named ‘print_it’ is defined, that iterates over the list, and prints the elements. Another method named ‘count_val’ is defined that is used to find the frequency of occurrence of a specific element in the linked list. Another method named ‘count_val’ is defined that is used to find the frequency of occurrence of a specific element in the linked list. An object of the ‘my_linked_list’ class is created. An object of the ‘my_linked_list’ class is created. The count_val method is called, to find the frequency of a specific element. The count_val method is called, to find the frequency of a specific element. This output is displayed on the console. This output is displayed on the console.
[ { "code": null, "e": 1341, "s": 1062, "text": "When it is required to count the number of occurrences of a specific element in a linked list without using recursion, a method to add elements to the linked list, a method to display the elements of the linked list, and a method to count the occurrence...
C++ | Inheritance | Question 7 - GeeksforGeeks
28 Jun, 2021 #include<iostream>using namespace std; class Base{public: void show() { cout<<" In Base "; }}; class Derived: public Base{public: int x; void show() { cout<<"In Derived "; } Derived() { x = 10; }}; int main(void){ Base *bp, b; Derived d; bp = &d; bp->show(); cout << bp->x; return 0;} (A) Compiler Error in line ” bp->show()”(B) Compiler Error in line ” cout <x”(C) In Base 10(D) In Derived 10Answer: (B)Explanation: A base class pointer can point to a derived class object, but we can only access base class member or virtual functions using the base class pointer because object slicing happens when a derived class object is assigned to a base class object. Additional attributes of a derived class object are sliced off to form the base class object.Quiz of this Question Pallabi Mondal C++-Inheritance Inheritance C Language C++ Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments fork() in C Command line arguments in C/C++ Substring in C++ Function Pointer in C TCP Server-Client implementation in C C++ | Exception Handling | Question 3 C++ | const keyword | Question 2 C++ | Operator Overloading | Question 5 C++ | new and delete | Question 4 C++ | Virtual Functions | Question 4
[ { "code": null, "e": 23851, "s": 23823, "text": "\n28 Jun, 2021" }, { "code": "#include<iostream>using namespace std; class Base{public: void show() { cout<<\" In Base \"; }}; class Derived: public Base{public: int x; void show() { cout<<\"In Derived \"; ...
Materialize - Quick Guide
Materialize is a UI component library created with CSS, JavaScript, and HTML. Materialize reusable UI components help in constructing attractive, consistent, and functional web pages and web apps while adhering to modern web design principles such as browser portability, device independence, and graceful degradation. Some of its salient features are as follows − In-built responsive designing. In-built responsive designing. Standard CSS with minimal footprint. Standard CSS with minimal footprint. New versions of common user interface controls such as buttons, checkboxes, and text fields adapted to follow Material Design concepts. New versions of common user interface controls such as buttons, checkboxes, and text fields adapted to follow Material Design concepts. Enhanced and specialized features such as cards, tabs, navigation bars, toasts, and so on. Enhanced and specialized features such as cards, tabs, navigation bars, toasts, and so on. Free to use and requires jQuery JavaScript library to function properly. Free to use and requires jQuery JavaScript library to function properly. Cross-browser, and can be used to create reusable web components. Cross-browser, and can be used to create reusable web components. Materialize has in-built responsive designing so that the website created using Materialize will redesign itself as per the device size. Materialize classes are created in such a way that the website can fit any screen size. The websites created using Materialize are fully compatible with PC, tablets, and mobile devices. Materialize is by design very minimal and flat. It is designed considering the fact that it is much easier to add new CSS rules than to overwrite the existing CSS rules. It supports shadows and bold colors. The colors and shades remain uniform across various platforms and devices. And most important of all, it is absolutely free to use. There are two ways to use Materialize − Local Installation − You can download the materialize.min.css and materialize.min.js files on your local machine and include it in your HTML code. CDN Based Version − You can include the materialize.min.css and materialize.min.js files into your HTML code directly from the Content Delivery Network (CDN). Go to https://materializecss.com/getting-started.html to download the latest version available. Go to https://materializecss.com/getting-started.html to download the latest version available. Then, put the downloaded materialize.min.js file in a directory of your website, e.g. /js and materialize.min.css in /css. Then, put the downloaded materialize.min.js file in a directory of your website, e.g. /js and materialize.min.css in /css. Include the css and js file in your HTML file as follows. <!DOCTYPE html> <html> <head> <title>The Materialize Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="materialize.min.js"></script> </head> <body> <div class="card-panel teal lighten-2"><h3>Hello World!</h3></div> </body> </html> It will produce the following result. You can include the materialize.min.js and materialize.min.css files into your HTML code directly from the Content Delivery Network (CDN). cdnjs.cloudflare.com provides content for the latest version. We are using cdnjs.cloudflare.com CDN version of the library throughout this tutorial. Rewrite the above example using materialize.min.css and materialize.min.js from cdnjs.cloudflare.com CDN. <!DOCTYPE html> <html> <head> <title>The Materialize Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body> <div class="card-panel teal lighten-2"><h3>Hello World!</h3></div> </body> </html> It will produce the following result. Materialize supports a rich set of color classes. These color classes are inspired and developed considering the colors used in marketing, road signs, and sticky notes. red pink purple deep-purple indigo blue light-blue cyan teal green light-green lime yellow amber orange deep-orange brown grey blue-grey black white transparent Following is the list of lightness/darkness classes, which can be used to vary the color applied. lighten-1 lighten-2 lighten-3 lighten-4 lighten-5 darken-1 darken-2 darken-3 darken-4 accent-1 accent-2 accent-3 accent-4 The following example demonstrates how to use the above classes to render the background or to change the color of the text. In case of background, add the classes as such and in case of text, suffix '-text' to color class and prefix 'text-' to lightning class. <!DOCTYPE html> <html> <head> <title>The Materialize Colors Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body> <h2>Color Theme Demo</h2> <hr/> <div class="card-panel"> <div class="card-panel red lighten-2"> <h1>Red Colored Theme</h1> </div> <span class="red-text text-darken-2"> <h2>Red Colored Text</h2> </span> <ul> <li class="red lighten-5"><p>Using red lighten-5</p></li> <li class="red lighten-4"><p>Using red lighten-4</p></li> <li class="red lighten-3"><p>Using red lighten-3</p></li> <li class="red lighten-2"><p>Using red lighten-2</p></li> <li class="red lighten-1"><p>Using red lighten-1</p></li> <li class="red"><p>Using red</p></li> <li class="red darken-1"><p>Using red darken-1</p></li> <li class="red darken-2"><p>Using red darken-2</p></li> <li class="red darken-3"><p>Using red darken-3</p></li> <li class="red darken-4"><p>Using red darken-4</p></li> <li class="red accent-1"><p>Using red accent-1</p></li> <li class="red accent-2"><p>Using red accent-2</p></li> <li class="red accent-3"><p>Using red accent-3</p></li> <li class="red accent-4"><p>Using red accent-4</p></li> </ul> </div> </body> </html> Verify the result. Materialize provides a 12 column fluid responsive grid. It uses the row and column style classes to define rows and columns respectively. Specifies a padding-less container to be used for responsive columns. This class is mandatory for responsive classes to be fully responsive. Specifies a column with sub-classes. col has several sub-classes meant for different types of screens. Following is a list of column-level styles for small screen devices, typically smartphones. s1 Defines 1 of 12 columns with width as 08.33% s2 Defines 2 of 12 columns with width as 16.66%. s3 Defines 3 of 12 columns with width as 25.00%. s4 Defines 4 of 12 columns with width as 33.33%. s12 Defines 12 of 12 columns with width as 100%. Default class for small screen phones. Following is a list of column-level styles for medium screen devices, typically tablets. m1 Defines 1 of 12 columns with width as 08.33% m2 Defines 2 of 12 columns with width as 16.66%. m3 Defines 3 of 12 columns with width as 25.00%. m4 Defines 4 of 12 columns with width as 33.33%. m12 Defines 12 of 12 columns with width as 100%. Default class for medium screen phones. Following is a list of column-level styles for large screen devices, typically laptops. l1 Defines 1 of 12 columns with width as 08.33% l2 Defines 2 of 12 columns with width as 16.66%. l3 Defines 3 of 12 columns with width as 25.00%. l4 Defines 4 of 12 columns with width as 33.33%. l12 Defines 12 of 12 columns with width as 100%. Default class for large screen devices. Each subclass determines the number of columns of the grid to be used based on the type of a device. Consider the following HTML snippet. <div class="row"> <div class="col s2 m4 l3"> <p>This text will use 2 columns on a small screen, 4 on a medium screen, and 3 on a large screen.</p> </div> </div> Default columns to be used are 12 on a device, if a sub-class is not mentioned in the class attribute of an HTML element. <!DOCTYPE html> <html> <head> <title>The Materialize Grids Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body> <div class="teal"> <h2>Mobile First Design Demo</h2> <p>Resize the window to see the effect!</p> </div> <hr/> <div class="row"> <div class="col m1 grey center">1</div> <div class="col m1 center">2</div> <div class="col m1 grey center">3</div> <div class="col m1 center">4</div> <div class="col m1 grey center">5</div> <div class="col m1 center">6</div> <div class="col m1 center grey">7</div> <div class="col m1 center">8</div> <div class="col m1 center grey">9</div> <div class="col m1 center">10</div> <div class="col m1 center grey">11</div> <div class="col m1 center">12</div> </div> <div class="row"> <div class="col m4 l3 yellow"> <p>This text will use 12 columns on a small screen, 4 on a medium screen (m4), and 3 on a large screen (l3).</p> </div> <div class="col s4 m8 l9 grey"> <p>This text will use 4 columns on a small screen (s4), 8 on a medium screen (m8), and 9 on a large screen (l9).</p> </div> </div> </body> </html> Verify the result. Materialize has several utility classes useful for day-to-day designing needs. Color utility classes − For example, .red, .green, .grey and so on Color utility classes − For example, .red, .green, .grey and so on Alignment utility classes − For example, .valign-wrapper, .left-align, .right-align, .center-align, .left, .right Alignment utility classes − For example, .valign-wrapper, .left-align, .right-align, .center-align, .left, .right Hiding Content utility classes as per device size − For example, .hide, .hide-on-small-only, .hide-on-med-only, .hide-on-med-and-down, .hide-on-med-and-up and .hide-on-large-only Hiding Content utility classes as per device size − For example, .hide, .hide-on-small-only, .hide-on-med-only, .hide-on-med-and-down, .hide-on-med-and-up and .hide-on-large-only Formatting utility classes − For example, truncate, hoverable Formatting utility classes − For example, truncate, hoverable <!DOCTYPE html> <html> <head> <title>The Materialize Example<!/title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"><!/script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <h2>Materialize Utilities</h2> <hr/> <h3>Color Utilities Demo</h3> <div class="red"> <p>The latest versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all support many HTML5 features and Internet Explorer 9.0 will also have support for some HTML5 functionality.</p> </div> <div class="green"> <p>The mobile web browsers that come pre-installed on iPhones, iPads, and Android phones all have excellent support for HTML5.<!/p> </div> <h3>Alignment Utilities Demo</h3> <div class="card-panel valign-wrapper"> <p class="valign">Vertically Aligned Text</p> </div> <div class="card-panel"> <div><p class="left-align">Left Aligned Text</p></div> <div><p class="right-align">Right Aligned Text</p><!/div> <div><p class="center-align">Center Aligned Text</p></div> <div> <h3>Hide Utilities Demo</h3> <div class="hide"> <p>Hidden on all devices</p> </div> <div class="hide-on-small-only"> <p>Hidden on mobile devices</p> </div> <h3>Formatting Utilities Demo</h3> <div class="card-panel"> <p class="truncate">The latest versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all support many HTML5 features and Internet Explorer 9.0 will also have support for some HTML5 functionality.<!/p> </div> <div class="card-panel hoverable"> <p>The mobile web browsers that come pre-installed on iPhones, iPads, and Android phones all have excellent support for HTML5.</p> </div> <h3>Center Utility Demo</h3> <div class="card-panel center"> <img src="html5-mini-logo.jpg" alt="html5"> </div> </body> </html> Verify the result. Materialize has several classes to make images and videos responsive to different sizes. responsive-img − It makes an image to resize itself based on the screen size. responsive-img − It makes an image to resize itself based on the screen size. video-container − For responsive container having embedded videos. video-container − For responsive container having embedded videos. responsive-video − Makes HTML5 videos responsive. responsive-video − Makes HTML5 videos responsive. <!DOCTYPE html> <html> <head> <title>The Materialize Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <h2>Materialize Media Examples</h2> <hr/> <h3>Images Demo</h3> <div class="card-panel"> <img src="html5-mini-logo.jpg" alt="" class="responsive-img"> </div> <div class="card-panel"> <img src="html5-mini-logo.jpg" alt="" class="circle responsive-img"> </div> <h3>Responsive Embeded Video Demo</h3> <div class="video-container"> <iframe width="540" height="200" src="http://www.youtube.com/embed/Q8TXgCzxEnw?rel=0" frameborder="0" allowfullscreen></iframe> </div> <div class="video-container"> <video width="300" height="200" controls autoplay> <source src="http://www.tutorialspoint.com/html5/foo.ogg" type="video/ogg" /> <source src="http://www.tutorialspoint.com/html5/foo.mp4" type="video/mp4" /> Your browser does not support the video element. </video> </div> </body> </html> Verify the result. Materialize has several special classes to display containers as paper-like cards with shadow. z-depth-0 Removes the shadow of elements having z-depth by default. z-depth-1 Styles a container for any HTML content with 1px bordered shadow. Adds z-depth of 1. z-depth-2 Styles a container for any HTML content with 2px bordered shadow. Adds z-depth of 2. z-depth-3 Styles a container for any HTML content with 3px bordered shadow. Adds z-depth of 3. z-depth-4 Styles a container for any HTML content with 4px bordered shadow. Adds z-depth of 4. z-depth-5 Styles a container for any HTML content with 5px bordered shadow. Adds z-depth of 5. <!DOCTYPE html> <html> <head> <title>The Materialize Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> <style> div { width : 200px; height : 200px; } </style> </head> <body class="container"> <h2>Materialize Shadow Examples</h2> <hr/> <div class="card-panel"> <p><b>TODO:</b> Learn HTML5</p> </div> <div class="z-depth-1"> <p><b>TODO:</b> Learn HTML5</p> </div> <div class="z-depth-2"> <p><b>TODO:</b> Learn HTML5</p> </div> <div class="z-depth-3"> <p><b>TODO:</b> Learn HTML5</p> </div> <div class="z-depth-4"> <p><b>TODO:</b> Learn HTML5</p> </div> <div class="z-depth-5"> <p><b>TODO:</b> Learn HTML5</p> </div> </body> </html> Verify the result. Materialize can be used to display different types of tables using various styles over table. None Represents a basic table without any border. stripped Displays a stripped table. bordered Draws a table with a border across rows. highlight Draws a highlighted table. centered Draws a table with all the text center aligned in the table. responsive-table Draws a responsive table to show a horizontal scrollbar, if the screen is too small to display the content. <!DOCTYPE html> <html> <head> <title>The Materialize Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> <style> div { width : 200px; height : 200px; } </style> </head> <body class="container"> <h2>Tables Demo</h2> <hr/> <h3>Simple Table</h3> <table> <thead> <tr><th>Student</th><th>Class</th><th>Grade</th></tr> </thead> <tbody> <tr><td>Mahesh Parashar</td><td>VI</td><td>A</td></tr> <tr><td>Rahul Sharma</td><td>VI</td><td>B</td></tr> <tr><td>Mohan Sood</td><td>VI</td><td>A</td></tr> </tbody> </table> <h3>Stripped Table with borders</h3> <table class="striped bordered"> <thead> <tr><th>Student</th><th>Class</th><th>Grade</th></tr> </thead> <tbody> <tr><td>Mahesh Parashar</td><td>VI</td><td>A</td></tr> <tr><td>Rahul Sharma</td><td>VI</td><td>B</td></tr> <tr><td>Mohan Sood</td><td>VI</td><td>A</td></tr> </tbody> </table> <hr/> <h3>Centered Table</h3> <table class="centered"> <thead> <tr><th>Student</th><th>Class</th><th>Grade</th></tr> </thead> <tbody> <tr><td>Mahesh Parashar</td><td>VI</td><td>A</td></tr> <tr><td>Rahul Sharma</td><td>VI</td><td>B</td></tr> <tr><td>Mohan Sood</td><td>VI</td><td>A</td></tr> </tbody> </table> <h3>Responsive table</h3> <table class="responsive-table"> <thead> <tr> <th>Student</th><th>Class</th><th>Data #1</th> <th>Data #2</th><th>Data #3</th><th>Data #4</th> <th>Data #5</th><th>Data #6</th><th>Data #7</th> <th>Data #8</th><th>Data #9</th><th>Data #10</th> </tr> </thead> <tbody> <tr> <td>Mahesh Parashar</td><td>VI</td><td>10</td> <td>11</td><td>12</td><td>13</td><td>14</td><td>15</td> <td>16</td><td>17</td><td>19</td><td>20</td> </tr> <tr> <td>Rahul Sharma</td><td>VI</td><td>10</td> <td>11</td><td>12</td><td>13</td><td>14</td><td>15</td> <td>16</td><td>17</td><td>19</td><td>20</td> </tr> <tr><td>Mohan Sood</td><td>VI</td><td>10</td> <td>11</td><td>12</td><td>13</td><td>14</td><td>15</td> <td>16</td><td>17</td><td>19</td><td>20</td> </tr> </tbody> </table> </body> </html> Verify the result. Materialize uses Roboto 2.0 as a standard font. It can be overridden using the following CSS style. html { font-family: GillSans, Calibri, Trebuchet, sans-serif; } Following are the examples of headings, blockquotes and free-flow but responsive text. <!DOCTYPE html> <html> <head> <title>The Materialize Typography Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <h2>Typography Demo</h2> <hr/> <h3>Headings</h3> <div class="card-panel"> <h1>Heading 1</h1> <h2>Heading 2</h2> <h3>Heading 3</h3> <h4>Heading 4</h4> <h6>Heading 6</h6> </div> <h3>Block Quotes</h3> <div class="card-panel"> <blockquote> The latest versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all support many HTML5 features and Internet Explorer 9.0 will also have support for some HTML5 functionality. </blockquote> </div> <h3>Responsive free-flow text</h3> <div class="card-panel"> <p class="flow-text"> The latest versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all support many HTML5 features and Internet Explorer 9.0 will also have support for some HTML5 functionality. </p> </div> </body> </html> Verify the result. Materialize badge component is an onscreen notification, which can be a number or an icon. It is generally used to emphasize the number of items. badge Identifies an element as an MDL badge component. Required for span element. new Adds a "new" class to a badge component gives it a background. Following are the examples of using badges in different ways. <!DOCTYPE html> <html> <head> <title>The Materialize Badges Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <h2>Badges Demo</h2> <hr/> <h3>Badges in List</h3> <div class="collection"> <a href="#" class="collection-item">Inbox<span class="badge">12</span></a> <a href="#" class="collection-item">Unread<span class="new badge">4</span></a> <a href="#" class="collection-item">Sent</a> <a href="#" class="collection-item">Outbox<span class="badge">14</span></a> </div> <h3>Badges in dropdowns</h3> <ul id="dropdown" class="dropdown-content"> <li><a href="#">Inbox<span class="badge">12</span></a></li> <li><a href="#!">Unread<span class="new badge">4</span></a></li> <li><a href="#">Sent</a></li> <li><a href="#">Outbox<span class="badge">14</span></a></li> </ul> <a class="btn dropdown-button" href="#" data-activates="dropdown">Dropdown<i class="mdi-navigation-arrow-drop-down right"></i></a> <h3>Badges in Navigation</h3> <nav> <div class="nav-wrapper"> <a href="" class="brand-logo">TutorialsPoint</a> <ul id="nav-mobile" class="right hide-on-med-and-down"> <li><a href="">Inbox</a></li> <li><a href="">Unread<span class="new badge">4</span></a></li> <li><a href="#">Sent</a></li> <li><a href="#">Outbox</a></li> </ul> </div> </nav> </body> </html> Verify the result. Materialize provides different CSS classes to apply various predefined visual and behavioral enhancements to the buttons. Following table mentions the available classes and their effects. btn Sets button or anchor as a Materialize button, required. Sets raised display effect to a button. btn-floating Creates a circular button. btn-flat Sets flat display effect to a button, default. btn-large Creates large buttons. disabled Creates a disabled button. type="submit" Represents an anchor or button as a primary button. waves-effect Sets ripple click effect, can be used in combination with any other classes. The following example demonstrates the use of mdl-button classes to show different types of buttons. <!DOCTYPE html> <html> <head> <title>The Materialize Buttons Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <div class="card-panel"> <h5>Raised Buttons</h5> <button class="btn waves-effect waves-teal">Add</button></td> <button class="btn waves-effect waves-teal"><i class="material-icons left">add</i>Add</button></td> <button class="btn waves-effect waves-teal"><i class="material-icons right">add</i>Add</button></td> <button class="btn waves-effect waves-teal disabled">Add</button></td> </div> <div class="card-panel"> <h5>Flat Buttons</h5> <button class="btn-flat waves-effect waves-teal">Add</button></td> <button class="btn-flat waves-effect waves-teal disabled" ><i class="material-icons left">add</i>Add</button></td> </div> <div class="card-panel"> <h5>Floating Buttons</h5> <a class="btn-floating waves-effect waves-light red"><i class="material-icons">add</i></a> <a class="btn-floating waves-effect waves-light red disabled" ><i class="material-icons">add</i></a> </div> <div class="card-panel"> <h5>Primary Buttons</h5> <button class="btn waves-effect waves-light red" type="submit">Send<i class="material-icons right">send</i></button> <button class="btn waves-effect waves-light red disabled" type="submit" >Cancel<i class="material-icons right">cancel</i></button> </div> <div class="card-panel"> <h5>Large Buttons</h5> <a class="btn-floating btn-large waves-effect waves-light red"><i class="material-icons">add</i></a> <a class="btn-floating btn-large waves-effect waves-light red disabled"><i class="material-icons">add</i></a> </div> </body> </html> Verify the result. Materialize provides various CSS classes to create a nice breadcrumb in an easy way. The following table mentions the available classes and their effects. nav-wrapper Sets the nav component as breadcrumb/nav bar wrapper. breadcrumb Sets the anchor element as breadcrumb. Last anchor element is active, while rest are shown as greyed out. The following example demonstrates the use of breadcrumb classes to showcase the navigation bar. <!DOCTYPE html> <html> <head> <title>The Materialize BreadCrumb Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <nav> <div class="nav-wrapper"> <div class="col s12"> <a href="#" class="breadcrumb">Home</a> <a href="#" class="breadcrumb">Technology</a> <a href="#" class="breadcrumb">HTML5</a> </div> </div> </nav> </body> </html> Verify the result. Materialize provides different CSS classes to apply various predefined visual and behavioral enhancements to display various types of cards. Following table mentions the available classes and their effects. card Identifies div element as a Materialize card container. Required on "outer" div. card-content Identifies div as a card content container and is required on "inner" div. card-title Identifies div as a card title container and is required on "inner" title div. card-action Identifies div as a card actions container and assigns appropriate text characteristics to actions text. Required on "inner" actions div; content goes directly inside the div with no intervening containers. card-image Identifies div as a card image container and is required on "inner" div. card-reveal Identifies div as a revealed text container. activator Identifies div as a revealed text container and image to be revealer. Used to show contextual information related to image. card-panel Identifies div as a simple card with shadows and padding. card-small Identifies div as a small sized card. Height − 300px; card-medium Identifies div as a medium sized card. Height − 400px; card-larger Identifies div as a large sized card. Height − 500px; The following example showcases the use of card classes to showcase various types of cards. <!DOCTYPE html> <html> <head> <title>The Materialize Cards Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <div class="row"> <div class="col s12 m6"> <div class="card blue-grey lighten-4"> <div class="card-content"> <span class="card-title"><h3>Learn HTML5</h3></span> <p>HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide Web.</p> </div> <div class="card-action"> <button class="btn waves-effect waves-light blue-grey"><i class="material-icons">share</i></button> <a class="right blue-grey-text" href="http://www.tutorialspoint.com">www.tutorialspoint.com</a> </div> </div> </div> <div class="col s12 m6"> <div class="card blue-grey lighten-4"> <div class="card-image"> <img src="html5-mini-logo.jpg"> </div> <div class="card-content"> <p>HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide Web.</p> </div> <div class="card-action"> <button class="btn waves-effect waves-light blue-grey"><i class="material-icons">share</i></button> <a class="right blue-grey-text" href="http://www.tutorialspoint.com">www.tutorialspoint.com</a> </div> </div> </div> </div> <div class="row"> <div class="col s12 m6"> <div class="card blue-grey lighten-4"> <div class="card-image waves-effect waves-block waves-light"> <img class="activator" src="html5-mini-logo.jpg"> </div> <div class="card-content activator"> <p>Click the image to reveal more information.</p> </div> <div class="card-reveal"> <span class="card-title grey-text text-darken-4">HTML5<i class="material-icons right">close</i></span> <p>HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide Web.</p> </div> <div class="card-action"> <button class="btn waves-effect waves-light blue-grey"><i class="material-icons">share</i></button> <a class="right blue-grey-text" href="http://www.tutorialspoint.com">www.tutorialspoint.com</a> </div> </div> </div> </div> <div class="row"> <div class="col s12 m3"> <div class="card-panel teal"> <span class="white-text">Simple Card</span> </div> </div> <div class="col s12 m3"> <div class="card small teal"> <span class="white-text">Small Card</span> </div> </div> <div class="col s12 m3"> <div class="card medium teal"> <span class="white-text">Medium Card</span> </div> </div> <div class="col s12 m3"> <div class="card large teal"> <span class="white-text">Large Card</span> </div> </div> </div> </body> </html> Verify the result. Materialize provides a special component called Chip, which can be used to represent a small set of information. For example, a contact, tags, etc. chip Set the div container as a chip. The following example demonstrates the use of chip class to showcase creating various types of tags. <!DOCTYPE html> <html> <head> <title>The Materialize Chips Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <div class="chip"> <img alt="HTML5" src="html5-mini-logo.jpg">HTML 5 </div> <div class="chip"> HTML 5<i class="material-icons">close</i> </div> </body> </html> Verify the result. Materialize provides special classes to represent various types of collections, where a collection represents a group of related information items. collection Sets the div or ul container as a collection. collection-item Sets the a or li item as a collection item. active Shows the a or li item as an active collection item. with-header Marks the collection to have a header. collection-header Sets the a or li item as a collection header. avatar Sets the a or li item as an avatar item. dismissible Enables the collection items to be swiped away. Works on touch screen devices only. Following example demonstrates the use of collection classes to showcase creating various types of collection. <!DOCTYPE html> <html> <head> <title>The Materialize Collections Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <h3>Simple Collection</h3><hr/> <ul class="collection"> <li class="collection-item">HTML 5</li> <li class="collection-item">JQuery</li> <li class="collection-item">JavaScript</li> <li class="collection-item">CSS</li> </ul> <h3>Collection of Links</h3><hr/> <div class="collection"> <a href="#" class="collection-item">HTML 5</a> <a href="#!" class="collection-item active">JQuery</a> <a href="#!" class="collection-item">JavaScript</a> <a href="#!" class="collection-item">CSS</a> </div> <h3>Collection with Header</h3><hr/> <ul class="collection with-header"> <li class="collection-header"><h3>Front End Technologies</h3></li> <li class="collection-item">HTML 5</li> <li class="collection-item">JQuery</li> <li class="collection-item">JavaScript</li> <li class="collection-item">CSS</li> </ul> <h3>Collection with Secondary Content</h3><hr/> <ul class="collection"> <li class="collection-item"><div>HTML 5<a href="#!" class="secondary-content"><i class="material-icons">cloud</i></a></div></li> <li class="collection-item"><div>JQuery<a href="#!" class="secondary-content"><i class="material-icons">cloud</i></a></div></li> <li class="collection-item"><div>JavaScript<a href="#!" class="secondary-content"><i class="material-icons">cloud</i></a></div></li> <li class="collection-item"><div>CSS<a href="#!" class="secondary-content"><i class="material-icons">cloud</i></a></div></li> </ul> <h3>Collection with Avatar</h3><hr/> <ul class="collection"> <li class="collection-item avatar"> <img alt="HTML5" src="html5-mini-logo.jpg" class="circle"> <span class="title">HTML5</span> <p>HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and XHTML 1.1.<br/> HTML5 is a standard for structuring and presenting content on the World Wide Web.</p> <a href="#!" class="secondary-content"><i class="material-icons">grade</i></a> </li> <li class="collection-item avatar"> <i class="material-icons circle green">insert_chart</i> <span class="title">HighCharts</span> <p></p> <a href="#!" class="secondary-content"><i class="material-icons">grade</i></a> </li> </ul> <h3>Collection with dismissible content</h3><hr/> <ul class="collection"> <li class="collection-item dismissable">HTML 5</li> <li class="collection-item dismissable">JQuery</li> <li class="collection-item dismissable">JavaScript</li> <li class="collection-item dismissable">CSS</li> </ul> </body> </html> Verify the result. Materialize provides special classes to represent various types of collections where a collection represents a group of related information items. page-footer Sets the div container as a footer. footer-copyright Sets the div container as a footer-copyright container. Following example demonstrates the use of footer classes to showcase a sample footer. <html> <head> <title>The Materialize Collections Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <footer class="page-footer"> <div class="row"> <div class="col s12 m6 l6"> <h5 class="white-text">Footer Content</h5> </div> <div class="col"> <ul> <li><a href="#" class="grey-text text-lighten-4 right">Help</a></li> <li><a href="#" class="grey-text text-lighten-4 right">Privacy and Terms</a></li> <li><a href="#" class="grey-text text-lighten-4 right">User Agreement</a></li> </ul> </div> </div> <div class="footer-copyright"> <div class="container"> © 2016 Copyright Information <a class="grey-text text-lighten-4 right" href="#!">Links</a> </div> </div> </footer> </body> </html> Verify the result. Materialize has a very beautiful and responsive CSS for form designing. Following CSS are used − input-field Sets the div container as an input field container. Required. validate Adds validation styles to an input field. active Shows an input with active style. materialize-textarea Used to style a text-area. Text-areas will auto resize to the text inside. filled-in Shows a checkbox with filled box style. Following example demonstrates the use of input classes to showcase a sample form. <html> <head> <title>The Materialize Form Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <div class="row"> <form class="col s12"> <div class="row"> <div class="input-field col s6"> <i class="material-icons prefix">account_circle</i> <input placeholder="Username" value="Mahesh" id="name" type="text" class="active validate" required> <label for="name">Username</label> </div> <div class="input-field col s6"> <label for="password">Password</label> <input id="password" type="password" placeholder="Password" class="validate" required> </div> </div> <div class="row"> <div class="input-field col s12"> <input placeholder="Email" id="email" type="email" class="validate"> <label for="email">Email</label> </div> </div> <div class="row"> <div class="input-field col s12"> <i class="material-icons prefix">mode_edit</i> <textarea id="address" class="materialize-textarea"></textarea> <label for="address">Address</label> </div> </div> <div class="row"> <div class="input-field col s12"> <input placeholder="Comments (Disabled)" id="comments" type="text" disabled> <label for="comments">Comments</label> </div> </div> <div class="row"> <div class="input-field col s12"> <p> <input id="married" type="checkbox" checked="checked"> <label for="married">Married</label> </p> <p> <input id="single" type="checkbox" class="filled-in" > <label for="single">Single </label> </p> <p> <input id="dontknow" type="checkbox" disabled="disabled"> <label for="dontknow">Don't know (Disabled)</label> </p> </div> </div> <div class="row"> <div class="input-field col s12"> <p> <input id="male" type="radio" name="gender" value="male" checked> <label for="male">Male</label> </p> <p> <input id="female" type="radio" name="gender" value="female" checked> <label for="female">Female </label> </p> <p> <input id="dontknow1" type="radio" name="gender" value="female" disabled> <label for="dontknow1">Don't know (Disabled)</label> </p> </div> </div> </form> </div> </body> </html> Verify the result. Materialize provides CSS for numerous types of input controls. Following table details the same. Select Various types of selects inputs Switches Various types of switches File Various types of file inputs Range Various types of range inputs Date Picker Date Picker Character Counter Character Counter The following example demonstrates different types of select options. <html> <head> <title>The Materialize Selects Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> <script> $(document).ready(function() { $('select').material_select(); }); </script> </head> <body class="container"> <div class="row"> <form class="col s12"> <div class="row"> <label>Materialize Select</label> <select> <option value="" disabled selected>Select Fruit</option> <option value="1">Mango</option> <option value="2">Orange</option> <option value="3">Apple</option> </select> </div> <div class="row"> <label>Materialize Multi Select</label> <select multiple> <option value="" disabled selected>Select Fruit</option> <option value="1">Mango</option> <option value="2">Orange</option> <option value="3">Apple</option> </select> </div> <div class="row"> <label>Select with Optgroup</label> <select> <optgroup label="Fruits"> <option value="1">Mango</option> <option value="2">Orange</option> <option value="3">Apple</option> </optgroup> <optgroup label="Vegs"> <option value="4">Brinjal</option> <option value="5">Potato</option> <option value="6">Tomato</option> </optgroup> </select> </div> <div class="row"> <label>Select with images</label> <select class="icons"> <option value="" disabled selected>Select Technology</option> <option value="1" data-icon="html5-mini-logo.jpg" class="circle">HTML</option> <option value="2">JavaScript</option> <option value="3">CSS</option> </select> </div> <div class="row"> <label>Browser default Select</label> <select class="browser-default"> <option value="" disabled selected>Select Fruit</option> <option value="1">Mango</option> <option value="2">Orange</option> <option value="3">Apple</option> </select> </div> <div class="row"> <label>Disabled Materialize Select </label><label>Disabled Materialize Select</label> <select disabled> <option value="" disabled selected>Select Fruit</option> <option value="1">Mango</option> <option value="2">Orange</option> <option value="3">Apple</option> </select> </div> <div class="row"> <label>Disabled Browser default Select </label> <select class="browser-default" disabled> <option value="" disabled selected>Select Fruit</option> <option value="1">Mango</option> <option value="2">Orange</option> <option value="3">Apple</option> </select> </div> </form> </div> </body> </html> Verify the result. The following example demonstrates different types of switches. A checkbox is styled as a switch by applying class switch on its parent div container. <html> <head> <title>The Materialize Switches Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <div class="row"> <form class="col s12"> <div class="row"> <label>Materialize Switch</label> <div class="switch"><label>Off <input type="checkbox" checked><span class="lever"></span>On</label></div> </div> <div class="row"> <label>Materialize Disabled Switch</label> <div class="switch"><label>Off<input disabled type="checkbox"><span class="lever"></span>On</label></div> </div> </form> </div> </body> </html> Verify the result. The following example demonstrates different types of File Upload Controls. <html> <head> <title>The Materialize File Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <div class="row"> <form class="col s12"> <div class="row"> <label>Materialize File Input</label> <div class="file-field input-field"> <div class="btn"> <span>Browse</span> <input type="file"> </div> <div class="file-path-wrapper"> <input class="file-path validate" type="text" placeholder="Upload file"> </div> </div> </div> <div class="row"> <label>Materialize Multi File Input</label> <div class="file-field input-field"> <div class="btn"> <span>Browse</span> <input type="file" multiple> </div> <div class="file-path-wrapper"> <input class="file-path validate" type="text" placeholder="Upload multiple files"> </div> </div> </div> </form> </div> </body> </html> Verify the result. The following example demonstrates Materialize Range control. <html> <head> <title>The Materialize Range Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <div class="row"> <form class="col s12"> <div class="row"> <label>Materialize Range</label> <p class="range-field"> <input type="range" id="test" min="0" max="100" /> </p> </div> </form> </div> </body> </html> Verify the result. The following example demonstrates Materialize DatePicker control. <html> <head> <title>The Materialize Range Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <div class="row"> <form class="col s12"> <div class="row"> <label>Materialize DatePicker</label> <input type="date" class="datepicker"> </div> </form> </div> </body> </html> Verify the result. The following example demonstrates Materialize Character Counter control. Setting the length to input text or text area activates this control. <html> <head> <title>The Materialize DatePicker Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <div class="row"> <form class="col s12"> <div class="row"> <div class="input-field col s6"> <input id="name" type="text" length="10"> <label for="name">Enter Name</label> </div> </div> <div class="row"> <div class="input-field col s6"> <textarea id="comments" class="materialize-textarea" length="120"></textarea> <label for="comments">Comments</label> </div> </div> </form> </div> </body> </html> Verify the result. Materialize supports the following popular icon libraries − Font Awesome Icons Google Material Icons Bootstrap Icons To use an icon, put the name of the icon in the class of an HTML <i> element. To control the size of an icon, you can use the following classes − tiny Draws an icon of very small size. 1rem. small Draws an icon of small size. 2rem medium Draws an icon of medium size. 4rem. large Draws an icon of large size. 6rem. <html> <head> <title>The Materialize Icons Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css"> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> </head> <body class="container"> <h2>Icons Demo</h2> <hr/> <h3>Font Awesome Icon Demo</h3> <i class="fa fa-cloud tiny"></i> <i class="fa fa-cloud"></i> <i class="fa fa-cloud small"></i> <i class="fa fa-cloud medium"></i> <i class="fa fa-cloud large"></i> <h3>Google Material Design Icon Demo</h3> <i class="material-icons tiny">cloud</i> <i class="material-icons small">cloud</i> <i class="material-icons">cloud</i> <i class="material-icons medium">cloud</i> <i class="material-icons large">cloud</i> <h3>Bootstrap Icon Demo</h3> <i class="glyphicon glyphicon-cloud tiny"></i> <i class="glyphicon glyphicon-cloud"></i> <i class="glyphicon glyphicon-cloud small"></i> <i class="glyphicon glyphicon-cloud medium"></i> <i class="glyphicon glyphicon-cloud large"></i> </body> </html> Verify the result. Materialize provides various CSS classes to create a nice navigation bar in an easy way. The following table mentions the available classes and their effects. nav-wrapper Sets the nav component as nav bar/breadcrumb wrapper. brand-logo Sets the anchor element as the main logo. nav-mobile Sets the ul element as a navigation bar. The following example demonstrates the use of navbar classes to showcase various navigation bar. <html> <head> <title>The Materialize NavBar Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> <script> $( document ).ready(function()){ $(".dropdown-button").dropdown(); }); </script> </head> <body class="container"> <div class="row" style="width:560px;"> <div class="col s12 m12 l12"> <h5>Right Aligned Nav Bar</h5> <nav> <div class="nav-wrapper"> <a href="#" class="brand-logo">TutorialsPoint</a> <ul id="nav-mobile" class="right hide-on-med-and-down"> <li><a href="#">HTML5</a></li> <li><a href="#">CSS</a></li> <li><a href="#">JavaScript</a></li> </ul> </div> </nav> </div> </div> <div class="row" style="width:560px;"> <div class="col s12 m12 l12"> <h5>Left Aligned Nav Bar</h5> <nav> <div class="nav-wrapper"> <a href="#" class="brand-logo right">TutorialsPoint</a> <ul id="nav-mobile" class="left hide-on-med-and-down"> <li><a href="#">HTML5</a></li> <li><a href="#">CSS</a></li> <li><a href="#">JavaScript</a></li> </ul> </div> </nav> </div> </div> <div class="row" style="width:560px;"> <div class="col s12 m12 l12"> <h5>Center Aligned Nav Bar</h5> <nav> <div class="nav-wrapper"> <a href="#" class="brand-logo center">TutorialsPoint</a> <ul id="nav-mobile" class="right hide-on-med-and-down"> <li><a href="#">Java</a></li> </ul> </div> </nav> </div> </div> <div class="row" style="width:560px;"> <div class="col s12 m12 l12"> <h5>Nav Bar with Active link</h5> <nav> <div class="nav-wrapper"> <a href="#" class="brand-logo right">TutorialsPoint</a> <ul id="nav-mobile" class="left hide-on-med-and-down"> <li><a href="#">HTML5</a></li> <li><a href="#">CSS</a></li> <li class="active"><a href="#">JavaScript</a></li> </ul> </div> </nav> </div> </div> <div class="row" style="width:560px;"> <div class="col s12 m12 l12"> <h5>Nav Bar with dropdown menu</h5> <ul id="javaDropDown" class="dropdown-content"> <li><a href="#!">JSF</a></li> <li><a href="#!">JSP</a></li> <li class="divider"></li> <li><a href="#!">Servlets</a></li> </ul> <nav> <div class="nav-wrapper"> <a href="#" class="brand-logo center">TutorialsPoint</a> <ul id="nav-mobile" class="right hide-on-med-and-down"> <!-- Dropdown Trigger --> <li><a class="dropdown-button" href="#!" data-activates="javaDropDown">Java<i class="material-icons right">arrow_drop_down</i></a></li> </ul> </div> </nav> </div> </div> <div class="row" style="width:560px;"> <div class="col s12 m12 l12"> <h5>Nav Bar with Links and Icons</h5> <nav> <div class="nav-wrapper"> <a href="#" class="brand-logo right">TutorialsPoint</a> <ul id="nav-mobile" class="left hide-on-med-and-down"> <li><a href="#"><i class="material-icons left">search </i>HTML5</a></li> <li><a href="#"><i class="material-icons right">view_module</i>CSS</a></li> <li><a href="#">JavaScript</a></li> </ul> </div> </nav> </div> </div> </body> </html> Verify the result. Materialize provides various CSS classes to create a nice pagination bar in an easy way. The following table mentions the available classes and their effects. pagination Sets the ul element as a pagination component. The following example demonstrates the use of navbar classes to showcase a pagination bar. <html> <head> <title>The Materialize Pagination Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <div class="row" style="width:560px;"> <div class="col s12 m12 l12" > <h5>Materialize Pagination</h5> <ul class="pagination"> <li class="disabled"><a href="#!"><i class="material-icons">chevron_left </i></a></li> <li class="active"><a href="#!">1</a></li> <li class="waves-effect"><a href="#!">2</a></li> <li class="waves-effect"><a href="#!">3</a></li> <li class="waves-effect"><a href="#!">4</a></li> <li class="waves-effect"><a href="#!">5</a></li> <li class="waves-effect"><a href="#!"><i class="material-icons">chevron_right</i></a></li> </ul> </div> </div> </body> </html> Verify the result. Materialize provides various CSS classes to apply various predefined visual and behavioral enhancements to display various types of preloaders or progress bars. The following table mentions the available classes and their effects. progress Identifies an element as a progress component. Required for div element. determinate Sets the basic Materialize behavior to progress indicator. indeterminate Sets animation to progress indicator. Following is an example of using preloaders in different ways. <html> <head> <title>The Materialize Preloader Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <h4>Default Preloader</h4> <div class="progress"> <div class="determinate" style="width: 50%"></div> </div> <h4>Indeterminate Preloader</h4> <div class="progress"> <div class="indeterminate"></div> </div> <h4>Circular Preloader</h4> <div class="preloader-wrapper big active"> <div class="spinner-layer spinner-blue-only"> <div class="circle-clipper left"> <div class="circle"></div> </div> <div class="gap-patch"> <div class="circle"></div> </div> <div class="circle-clipper right"> <div class="circle"></div> </div> </div> </div> </body> </html> Verify the result. Materialize provides various CSS classes to apply various predefined visual and behavioral enhancements to display various types of accordions. The following table mentions the available classes and their effects. collapsible Identifies an element as a materialize collapsible component. Required for ul element. collapsible-header Sets div as a section header. collapsible-body Sets div as a section content container. popout Creates a popout collapsible. active Opens a section. expandable Marks a collapsible component as expandable. accordion Marks a collapsible component as accordion. Following is an example of using accordions in different ways. <html> <head> <title>The Materialize Collapsible Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <h4>Simple Accordion</h4> <ul class="collapsible" data-collapsible="accordion"> <li> <div class="collapsible-header"><i class="material-icons">filter_drama</i>First Section</div> <div class="collapsible-body"><p>This is first section.</p></div> </li> <li> <div class="collapsible-header"><i class="material-icons">place</i>Second Section</div> <div class="collapsible-body"><p>This is second section.</p></div> </li> <li> <div class="collapsible-header"><i class="material-icons">whatshot</i>Third Section</div> <div class="collapsible-body"><p>This is third section.</p></div> </li> </ul> <h4>Popout Accordion</h4> <ul class="collapsible popout" data-collapsible="accordion"> <li> <div class="collapsible-header"><i class="material-icons">filter_drama</i>First Section</div> <div class="collapsible-body"><p>This is first section.</p></div> </li> <li> <div class="collapsible-header"><i class="material-icons">place</i>Second Section</div> <div class="collapsible-body"><p>This is second section.</p></div> </li> <li> <div class="collapsible-header"><i class="material-icons">whatshot</i>Third Section</div> <div class="collapsible-body"><p>This is third section.</p></div> </li> </ul> <h4>Accordion with Preselected Section</h4> <ul class="collapsible" data-collapsible="accordion"> <li> <div class="collapsible-header"><i class="material-icons">filter_drama</i>First Section</div> <div class="collapsible-body"><p>This is first section.</p></div> </li> <li> <div class="collapsible-header active"><i class="material-icons">place</i>Second Section</div> <div class="collapsible-body"><p>This is second section.</p></div> </li> <li> <div class="collapsible-header"><i class="material-icons">whatshot</i>Third Section</div> <div class="collapsible-body"><p>This is third section.</p></div> </li> </ul> <h4>Expandables</h4> <ul class="collapsible" data-collapsible="expandable"> <li> <div class="collapsible-header"><i class="material-icons">filter_drama</i>First Section</div> <div class="collapsible-body"><p>This is first section.</p></div> </li> <li> <div class="collapsible-header"><i class="material-icons">place</i>Second Section</div> <div class="collapsible-body"><p>This is second section.</p></div> </li> <li> <div class="collapsible-header"><i class="material-icons">whatshot</i>Third Section</div> <div class="collapsible-body"><p>This is third section.</p></div> </li> </ul> </body> </html> Verify the result. Materialize provides various special methods to show unobtrusive alerts to the users. Materialize provides a term toast for them. Following is the syntax to show a dialog as a toast. Materialize.toast(message, displayLength, className, completeCallback); Where, message − Message to be displayed to the user. displayLength − Duration of the message after which it will disappear. className − Style class to be applied to the toast. For example, 'rounded'. completeCallback − Callback method to be called once toast is dismissed. For tooltip, Materialize provides the following CSS classes. tooltipped Identifies a component to have a tooltip. data-position Position of the tooltip; bottom, top, left, or right. data-delay Sets the duration of the tooltip after which it will disappear. data-tooltip Sets the tooltip contents. Following example demonstrates the use of toasts and tooltips. <html> <head> <title>The Materialize Dialogs Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> <script> function showToast(message, duration){ Materialize.toast(message, duration); } function showToast1(message, duration){ Materialize.toast('<i>'+ message + '</i>', duration); } function showToast2(message, duration){ Materialize.toast(message, duration, 'rounded'); } function showToast3(message, duration){ Materialize.toast('Hello World!', duration, '', function toastCompleted(){ alert('Toast dismissed!'); }); } </script> </head> <body class="container"> <h4>Toasts</h4> <a class="btn" onclick="showToast('Hello World!', 3000)">Normal Alert!</a> <a class="btn" onclick="showToast1('Hello World!', 3000)">Italic Alert!</a> <a class="btn" onclick="showToast2('Hello World!', 3000)">Rounded Alert!</a> <br/><br/> <a class="btn" onclick="showToast3('Hello World!', 3000)">Callback Alert!</a> <h4>Tooltips</h4> <a class="btn tooltipped" data-position="bottom" data-delay="50" data-tooltip="I am in bottom!">Bottom</a> <a class="btn tooltipped" data-position="left" data-delay="50" data-tooltip="I am in left!">Left</a> <a class="btn tooltipped" data-position="right" data-delay="50" data-tooltip="I am in right!">Right</a> <a class="btn tooltipped" data-position="top" data-delay="50" data-tooltip="I am in top!">Top</a> </body> </html> Verify the result. Materialize provides dropdown CSS class to make a ul element as a dropdown and add the id of the ul element to the data-activates attribute of the button or anchor element. The following table mentions the available classes and their effects. dropdown-content Identifies ul as a materialize dropdown component. Required for ul element. data-activates id of the dropdown ul element. Following is an example of using a dropdown. <!DOCTYPE html> <html> <head> <title>The Materialize Dropdowns Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <h3>Drop Down Demo</h3> <ul id="dropdown" class="dropdown-content"> <li><a href="#">Inbox<span class="badge">12</span></a></li> <li><a href="#!">Unread<span class="new badge">4</span></a></li> <li><a href="#">Sent</a></li> <li class="divider"></li> <li><a href="#">Outbox<span class="badge">14</span></a></li> </ul> <a class="btn dropdown-button" href="#" data-activates="dropdown">Mail Box<i class="mdi-navigation-arrow-drop-down right"></i></a> </body> </html> Verify the result. Materialize provides tabs CSS class to make a ul element as a tab. The following table mentions the available classes and their effects. tabs Identifies ul as a materialize tab component. Required for ul element. active Makes a tab active. Following is an example of using a tab. <!DOCTYPE html> <html> <head> <title>The Materialize Tabs Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <h3>Tabs Demo</h3> <div class="row"> <div class="col s12"> <ul class="tabs"> <li class="tab col s3"><a href="#inbox">Inbox</a></li> <li class="tab col s3"><a class="active" href="#unread">Unread</a></li> <li class="tab col s3 disabled"><a href="#outbox">Outbox (Disabled)</a></li> <li class="tab col s3"><a href="#sent">Sent</a></li> </ul> </div> <div id="inbox" class="col s12">Inbox</div> <div id="unread" class="col s12">Unread</div> <div id="outbox" class="col s12">Outbox (Disabled)</div> <div id="sent" class="col s12">Sent</div> </div> </body> </html> Verify the result. Materialize uses Waves, an external library, to create ink effect outlined in Material Design. Following table mentions the available classes and their effects. waves-effect Applies a wave effect on the control. waves-light Applies a white colored wave effect. waves-red Applies a red colored wave effect. waves-green Applies a green colored wave effect. waves-yellow Applies a yellow colored wave effect. waves-orange Applies an orange colored wave effect. waves-purple Applies a purple colored wave effect. waves-teal Applies a teal colored wave effect. Following is an example of using wave effects on buttons. <!DOCTYPE html> <html> <head> <title>The Materialize Waves Effects Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <h3>Waves Effects Demo</h3> <div class="collection waves-color-demo"> <div class="collection-item"> <code class=" language-markup">Default</code> <a href="#!" class="waves-effect btn secondary-content">Click Me!</a> </div> <div class="collection-item"> <code class=" language-markup">waves-light</code> <a href="#!" class="waves-effect waves-light btn secondary-content">Click Me!</a> </div> <div class="collection-item"> <code class=" language-markup">waves-red</code> <a href="#!" class="waves-effect waves-red btn secondary-content">Click Me!</a> </div> <div class="collection-item"> <code class=" language-markup">waves-yellow</code> <a href="#!" class="waves-effect waves-yellow btn secondary-content">Click Me!</a> </div> <div class="collection-item"> <code class=" language-markup">waves-orange</code> <a href="#!" class="waves-effect waves-orange btn secondary-content">Click Me!</a> </div> <div class="collection-item"> <code class=" language-markup">waves-purple</code> <a href="#!" class="waves-effect waves-purple btn secondary-content">Click Me!</a> </div> <div class="collection-item"> <code class=" language-markup">waves-green</code> <a href="#!" class="waves-effect waves-green btn secondary-content">Click Me!</a> </div> <div class="collection-item"> <code class=" language-markup">waves-teal</code> <a href="#!" class="waves-effect waves-teal btn secondary-content">Click Me!</a> </div> </div> </body> </html> Verify the result. Print Add Notes Bookmark this page
[ { "code": null, "e": 2506, "s": 2187, "text": "Materialize is a UI component library created with CSS, JavaScript, and HTML. Materialize reusable UI components help in constructing attractive, consistent, and functional web pages and web apps while adhering to modern web design principles such as br...
Math.Atan2() Method in C#
The Math.Atan2() method in C# is used to return the angle whose tangent is the quotient of two specified numbers. Following is the syntax − public static double Atan2 (double val1, double val2); Above, val1 is the y coordinate, whereas val2 is the x coordinate. Let us now see an example to implement Math.Atan2() method − using System; public class Demo { public static void Main(){ double val1 = 3.0; double val2 = 1.0; double angle, radians; radians = Math.Atan2(val1, val2); angle = radians * (180/Math.PI); Console.WriteLine("Result = "+angle); } } This will produce the following output − Result = 71.565051177078 Let us see another example to implement Math.Atan2() method − using System; public class Demo { public static void Main(){ double val1 = 0; double val2 = 5; double angle, radians; radians = Math.Atan2(val1, val2); angle = radians * (180/Math.PI); Console.WriteLine("Result = "+angle); } } This will produce the following output − Result = 0
[ { "code": null, "e": 1176, "s": 1062, "text": "The Math.Atan2() method in C# is used to return the angle whose tangent is the quotient of two specified numbers." }, { "code": null, "e": 1202, "s": 1176, "text": "Following is the syntax −" }, { "code": null, "e": 1257,...
How to convert an array to Set and vice versa in Java?
Array is a container which can hold a fix number of entities, which are of the same type. Each entity of an array is known as element and, the position of each element is indicated by an integer (starting from 0) value known as index. import java.util.Arrays; public class ArrayExample { public static void main(String args[]) { Number integerArray[] = new Integer[3]; integerArray[0] = 25; integerArray[1] = 32; integerArray[2] = 56; System.out.println(Arrays.toString(integerArray)); } } [25, 32, 56] Whereas a Set object is a collection (object) stores another objects, it does not allow duplicate elements and allows at most null value. The Arrays class of the java.util package provides a method known as asList(). This method accepts an array as an argument and, returns a List object. Use this method to convert an array to Set. import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class ArrayToSet { public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array to be created ::"); int size = sc.nextInt(); String [] myArray = new String[size]; for(int i=0; i<myArray.length; i++){ System.out.println("Enter the element "+(i+1)+" (String) :: "); myArray[i]=sc.next(); } Set<String> set = new HashSet<>(Arrays.asList(myArray)); System.out.println("Given array is converted to a Set"); System.out.println("Contents of set ::"+set); } } Enter the size of the array to be created :: 4 Enter the element 1 (String) :: Ram Enter the element 2 (String) :: Rahim Enter the element 3 (String) :: Robert Enter the element 4 (String) :: Rajeev Given array is converted to a Set Contents of set ::[Robert, Rahim, Rajeev, Ram] The Set object provides a method known as toArray(). This method accepts an empty array as argument, converts the current Set to an array and places in the given array. Use this method to convert a Set object to an array. import java.util.HashSet; import java.util.Set; public class SetToArray { public static void main(String args[]){ Set<String> set = new HashSet<String>(); set.add("Apple"); set.add("Orange"); set.add("Banana"); System.out.println("Contents of Set ::"+set); String[] myArray = new String[set.size()]; set.toArray(myArray); for(int i=0; i<myArray.length; i++){ System.out.println("Element at the index "+(i+1)+" is ::"+myArray[i]); } } } Contents of Set ::[Apple, Orange, Banana] Element at the index 1 is ::Apple Element at the index 2 is ::Orange Element at the index 3 is ::Banana
[ { "code": null, "e": 1297, "s": 1062, "text": "Array is a container which can hold a fix number of entities, which are of the same type. Each entity of an array is known as element and, the position of each element is indicated by an integer (starting from 0) value known as index." }, { "cod...
Types of Sorting Algorithm in R Programming - GeeksforGeeks
17 Jun, 2021 There are multiple ways by which data can be sorted in the R language. It’s up to the data Analyst to consider the most suitable method based upon the structure of the data. There are multiple algorithms for performing sorting on the data in the R programming language. Below different types of sorting function have been discussed. A sample of 10 random numbers between 1 to 100 from an array is used. We are going to discuss the following sorting algorithm: Bubble Sort Insertion Sort Selection Sort Merge Sort Quick Sort In this algorithm, two adjacent elements are compared and swapped if the criteria are met. In bubble sort, in each iteration, the largest element is brought to the end of the array(in case of increasing) by swapping elements, hence the name of the algorithm is bubble sort. To understand the bubble sort algorithm in detail please refer to Bubble Sort. R # function to sort the array using bubble sortbubble_sort <- function(x){ # calculate the length of array n <- length(x) # run loop n-1 times for (i in 1 : (n - 1)) { # run loop (n-i) times for (j in 1 : (n - i)) { # compare elements if (x[j] > x[j + 1]) { temp <- x[j] x[j] <- x[j + 1] x[j + 1] <- temp } } } x} # take 10 random numbers between 1 - 100arr <- sample(1 : 100, 10) # sort the array and store the result# in sorted_arraysorted_array <- bubble_sort(arr) # print sorted_arraysorted_array Output: [1] 2 19 26 68 74 76 80 81 82 91 In this sorting algorithm, sorted and unsorted elements are compared, and the unsorted element is placed in its correct position after each iteration. In this algorithm, the first element is assumed to be sorted and the second element is stored separately as a key element that needs to be sorted. The key is then compared with the sorted element. If the sorted element is greater than the key element, their places are swapped, and the key element becomes the first element. To understand the Insertion sort algorithm in detail please refer to Insertion Sort. R # insertion sort function to sort arrayinsertion_sort <- function(x){ # calculate the length of array n <- length(x) # outer loop for (i in 2 : (n)) { # store first element as key key = x[i] j = i - 1 # compare key with elements for # its correct position while (j > 0 && x[j] > key) { x[j + 1] = x[j] j = j - 1 } # Place key at its correct position x[j + 1] = key } # return sorted array x} # take sample arrayarr <- sample(1 : 100, 10) # call insertion sort functionsorted_arr <- insertion_sort(arr) # print sorted arraysorted_arr Output: [1] 10 27 30 41 58 77 80 89 90 85 This sorting algorithm is widely used in the R language. Here, the smallest element from the unsorted list is pushed to the start of the list at every iteration. To understand the Selection sort algorithm in detail please refer to Selection Sort. R # function to sort array using selection sortselection_sort <- function(x){ # length of array n <- length(x) for (i in 1 : (n - 1)) { # assume element at i is minimum min_index <- i for (j in (i + 1) : (n)) { # check if element at j is smaller # than element at min_index if (x[j] < x[min_index]) { # if yes, update min_index min_index = j } } # swap element at i with element at min_index temp <- x[i] x[i] <- x[min_index] x[min_index] <- temp } x} # take sample inputarr <- sample(1 : 100, 10) # sort arraysorted_arr <- selection_sort(arr) # print arraysorted_arr Output [1] 6 16 21 28 31 48 57 73 85 99 This is a divide and conquers algorithm. We divide the array into two parts from mid, sort those two array,s and merge them. The entire process is done recursively. To understand the Merge sort algorithm in detail please refer to Merge Sort. R # function to merge two sorted arraysmerge <- function(a, b) { # create temporary array temp <- numeric(length(a) + length(b)) # take two variables which initially points to # starting of the sorted sub arrays # and j which points to starting of starting # of temporary array astart <- 1 bstart <- 1 j <- 1 for(j in 1 : length(temp)) { # if a[astart] < b[bstart] if((astart <= length(a) && a[astart] < b[bstart]) || bstart > length(b)) { # insert a[astart] in temp and increment # astart pointer to next temp[j] <- a[astart] astart <- astart + 1 } else { temp[j] <- b[bstart] bstart <- bstart + 1 } } temp} # function to sort the arraymergeSort <- function(arr) { # if length of array is greater than 1, # then perform sorting if(length(arr) > 1) { # find mid point through which # array need to be divided mid <- ceiling(length(arr)/2) # first part of array will be from 1 to mid a <- mergeSort(arr[1:mid]) # second part of array will be # from (mid+1) to length(arr) b <- mergeSort(arr[(mid+1):length(arr)]) # merge above sorted arrays merge(a, b) } # else just return arr with single element else { arr }} # take sample inputarr <- sample(1:100, 10) # call mergeSort functionresult <- mergeSort(arr) # print resultresult Output [1] 6 8 16 19 21 24 35 38 74 90 This is a divide and conquers algorithm. It picks an element as a pivot and partitions the given array around the picked pivot. Pivot can be random. To understand the Merge sort algorithm in detail please refer to Quick Sort. R # function to sort the valuesquickSort <- function(arr) { # Pick a number at random random_index <- sample(seq_along(arr), 1); pivot <- arr[random_index] arr <- arr[-random_index] # Create array for left and right values. left <- c() right <- c() # Move all smaller and equal values to the # left and bigger values to the right. # compare element with pivot left<-arr[which(arr <= pivot)] right<-arr[which(arr > pivot)] if (length(left) > 1) { left <- quickSort(left) } if (length(right) > 1) { right <- quickSort(right) } # Return the sorted values. return(c(left, pivot, right))} # take sample arrayarr <- sample(1:100, 10) # call quickSort functionresult <- quickSort(arr) # print resultresult Output: [1] 13 18 21 38 70 74 80 83 95 99 akshaysingh98088 surinderdawra388 R-Arrays 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 Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to Change Axis Scales in R Plots? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? R - if statement How to filter R DataFrame by values in a column? How to import an Excel File into R ? Time Series Analysis in R
[ { "code": null, "e": 26597, "s": 26569, "text": "\n17 Jun, 2021" }, { "code": null, "e": 27057, "s": 26597, "text": "There are multiple ways by which data can be sorted in the R language. It’s up to the data Analyst to consider the most suitable method based upon the structure of...
HTML | DOM Input Email Placeholder Property - GeeksforGeeks
16 Apr, 2019 The DOM Input Email Placeholder Property is used to set or return the value of a placeholder attribute of an Email Field. The placeholder attribute specifies a short hint that describes the expected value of a input field / textarea. The short hint is displayed in the field before the user enters a value. Syntax: It is used to return the placeholder property.emailObject.placeholder emailObject.placeholder It is used to set the placeholder property.emailObject.placeholder = text emailObject.placeholder = text Property Value: text: It defines a short hint that describes a expected value of the Email Field. Return Value: It returns a string value which represents a short hint that describes the expected value of the Email Field. Example-1: This example illustrates how to return the property. <!DOCTYPE html> <html> <head> <title> HTML DOM Input Email placeholder Property </title> </head> <body STYLE="TEXT-ALIGN:CENTER;"> <h1> GeeksforGeeks</h1> <h2>DOM Input Email placeholder Property</h2> E-mail: <input type="email" id="email" name="myGeeks" placeholder="careers@geeksforgeeks.org"> <BR><br> <button onclick="myGeeks()"> Click Here! </button> <p id="GFG" style="font-size:20px;color:green;"></p> <!-- Script to access input element with type email attribute --> <script> function myGeeks() { <!--return the placeholder Property --> var em = document.getElementById("email").placeholder; document.getElementById("GFG").innerHTML = em; } </script> </body> </html> Output:Before clicking on the button:After clicking on the button: Example-2 : This example illustrates how to set the property. <!DOCTYPE html> <html> <head> <title> HTML DOM Input Email placeholder Property </title> </head> <body STYLE="TEXT-ALIGN:CENTER;"> <h1> GeeksforGeeks</h1> <h2>DOM Input Email placeholder Property</h2> E-mail: <input type="email" id="email" name="myGeeks" placeholder="careers@geeksforgeeks.org"> <BR><br> <button onclick="myGeeks()"> Click Here! </button> <p id="GFG" style="font-size:20px;color:green;"></p> <!-- Script to access input element with type email attribute --> <script> function myGeeks() { <!--setting the multiple Property --> var em = document.getElementById("email").placeholder = "Input Your Email Address"; document.getElementById("GFG").innerHTML = "The value of the placeholder attribute was changed to :" + em; } </script> </body> </html> Output:Before clicking on the button:After clicking on the button: Supported Browsers: The browser supported by DOM input Email placeholder Property are listed below: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. shubham_singh HTML-DOM HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form HTML Cheat Sheet - A Basic Guide to HTML Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26544, "s": 26516, "text": "\n16 Apr, 2019" }, { "code": null, "e": 26851, "s": 26544, "text": "The DOM Input Email Placeholder Property is used to set or return the value of a placeholder attribute of an Email Field. The placeholder attribute specifies a sho...
First negative integer in every window of size k | Practice | GeeksforGeeks
Given an array A[] of size N and a positive integer K, find the first negative integer for each and every window(contiguous subarray) of size K. Example 1: Input : N = 5 A[] = {-8, 2, 3, -6, 10} K = 2 Output : -8 0 -6 -6 Explanation : First negative integer for each window of size k {-8, 2} = -8 {2, 3} = 0 (does not contain a negative integer) {3, -6} = -6 {-6, 10} = -6 Input : N = 8 A[] = {12, -1, -7, 8, -15, 30, 16, 28} K = 3 Output : -1 -1 -7 -15 -15 0 Your Task: You don't need to read input or print anything. Your task is to complete the function printFirstNegativeInteger() which takes the array A[], its size N and an integer K as inputs and returns the first negative number in every window of size K starting from the first till the end. If a window does not contain a negative integer , then return 0 for that window. Expected Time Complexity: O(N) Expected Auxiliary Space: O(K) Constraints: 1 <= N <= 105 -105 <= A[i] <= 105 1 <= K <= N 0 purubhargava01120 hours ago vector<long long> printFirstNegativeInteger(long long int input[], long long int n, long long int k) { long long j = 0 ; long long i = 0 ; queue<long long> q ; vector<long long> ans ; while(j < n){ if(j - i + 1 == k ){ if(input[j] < 0){ q.push(j) ; } if(q.size() and !(q.front() >= i and q.front() <= j)){ q.pop() ; } if(q.size() == 0){ ans.push_back(0) ; } if(q.size() and q.front() >= i and q.front() <= j){ ans.push_back(input[q.front()]) ; } i += 1 ; } else { if(input[j] < 0 ){ q.push(j) ; } } j += 1 ; } return ans ; } 0 utkarshrdce2 days ago /* negIdx stores the index of the first element of the window which was just previously processed as soon as you arrive at this element, update negIdx to i (the current index) if the element is negative check if negIdx lies in the window of size k, and fill the answer */ vector<long long> printFirstNegativeInteger(long long int A[], long long int N, long long int K) { vector<long long> ans; int negIdx = N; int j = N - 1; for (j = N - 1; j > N - K; j--) { if (A[j] < 0) negIdx = j; } // as soon as you arrive at this element, update negIdx if the element is negative while (j >= 0) { if (A[j] < 0) negIdx = j; if (j + K - 1 >= negIdx) ans.push_back(A[negIdx]); else ans.push_back(0); j--; } reverse(ans.begin(), ans.end()); return ans; } 0 yashpaneliya This comment was deleted. +1 jainatishay0725 days ago Python Solution If You like that please vote upward def printFirstNegativeInteger( arr, n, k): res=[] q=[] i,j=0,0 while j<n: if arr[j]<0: q.append(arr[j]) if j-i+1<k: j+=1 elif j-i+1==k: if len(q)==0: res.append(0) else: res.append(q[0]) if arr[i]==q[0]: q.pop(0) i+=1 j+=1 return res 0 thakuraditya6216 days ago public long[] printFirstNegativeInteger(long A[], int N, int K) { // O((n-k+1)*k) or // O(NK) boolean flag; long[] ans = new long[N-K+1]; int l = 0; for(int i = 0; i < (N-K + 1); i++){ flag = false; for(int j = 0; j < K ; j++){ if(A[i+j] < 0){ ans[l++] = A[i+j]; flag = true; break; } } if(!flag){ ans[l++] = 0; } } return ans; // ----------------------------------------------------------------------------------- // nNext Approch Using Queue // O(N) and O(K) Queue<Long> q=new LinkedList<>(); long[]ans=new long[N-K+1]; for(int i=0;i<K-1;i++){ q.add(A[i]); } for(int i=K-1,j=0;i<N && j<N-K+1;i++,j++){ if(q.size()==K){ q.remove(); q.add(A[i]); }else if(q.size()<K) q.add(A[i]); while(!q.isEmpty() && q.peek()>=0){ q.remove(); } if(q.isEmpty()) ans[j]=0; else ans[j] = q.peek(); } return ans; //------------------------------------------------------------------------- // O(N) and O(1) int nIdx = 0; long nEmnt ; long []ans = new long [N-K+1]; int j=0; for(int i = K-1; i < N; i++){ while((nIdx < i) && (nIdx <= i - K || A[nIdx] > 0) ){ nIdx++; } // Check if a negative element is // found, otherwise use 0 if (A[nIdx] < 0) { nEmnt = A[nIdx]; ans[j++] = nEmnt; } else { nEmnt = 0; ans[j++] = nEmnt; } } return ans; } +3 sidvas581 week ago //Learnt from Aditya Verma's vid vector<long long int> v; list<long long int> l; long long int i=0,j=0; while(j<n) { if(arr[j]<0) l.push_back(arr[j]); if(j-i+1<k) j++; else if(j-i+1==k) { if(l.size()==0) v.push_back(0); else { v.push_back(l.front()); if(arr[i]==l.front()) l.pop_front(); } i++; j++; } } return v; +2 kunalwalia20011 week ago C++ Solution With Complexity O(n) and O(1) without extra space vector<long long> printFirstNegativeInteger(long long int A[], long long int N, long long int K) { int firstNegativeIndex = 0; int firstNegativeElement; vector<long long int> ans; // skip out of window and +ve elements for(int i = K-1;i<N;i++){ while((firstNegativeIndex < i) && (firstNegativeIndex <= i-K || A[firstNegativeIndex] > 0)){ firstNegativeIndex++; } // check if -ve element is found or not if(A[firstNegativeIndex] < 0){ firstNegativeElement = A[firstNegativeIndex]; ans.push_back(firstNegativeElement); }else { ans.push_back(0); } } return ans; } 0 shrustis1762 weeks ago C++ solution using Sliding Window vector<long long> printFirstNegativeInteger(long long int A[], long long int N, long long int K) { queue<long long>q; vector<long long>v; int i=0,j=0; while(j<N) { if(A[j] < 0) q.push(A[j]); if(j-i+1 < K) j++; else if(j-i+1 == K) { if(q.empty()) v.push_back(0); else { v.push_back(q.front()); if(A[i] == q.front()) q.pop(); } i++; j++; } } return v;} +1 anshjaiswal202 weeks ago Easy Java Solution class Compute { public long[] printFirstNegativeInteger(long a[], int n, int k) { Queue<Long> q=new LinkedList<>(); long[]ans=new long[n-k+1]; for(int i=0;i<k-1;i++){ q.add(a[i]); } for(int i=k-1,j=0;i<n && j<n-k+1;i++,j++){ if(q.size()==k){ q.remove(); q.add(a[i]); }else if(q.size()<k)q.add(a[i]); while(!q.isEmpty() && q.peek()>=0){ q.remove(); } if(q.isEmpty())ans[j]=0; else ans[j]=q.peek(); } return ans; }} 0 pankajsingh852013 weeks ago vector<long long> printFirstNegativeInteger(long long int A[], long long int N, long long int K) { vector<long long> ans; queue<int> q; for(int i=0;i<K;i++) { if(A[i]<0) { q.push(i); } } if(q.empty()) ans.push_back(0); else ans.push_back(A[q.front()]); for(int i=1;i<=N-K;i++) { if(A[K+i-1]<0) q.push(K+i-1); while(!q.empty()) { int j = q.front(); if(j>=i and j<=K+i-1) { ans.push_back(A[j]); break; } else { q.pop(); } } if(q.empty())ans.push_back(0); } return ans; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 383, "s": 238, "text": "Given an array A[] of size N and a positive integer K, find the first negative integer for each and every window(contiguous subarray) of size K." }, { "code": null, "e": 396, "s": 385, "text": "Example 1:" }, { "code": null, ...
Packaging in Python: Tools and Formats | by Martin Thoma | Towards Data Science
A virtual environment is an isolated Python environment. It has it’s own installed site-packages which can be different from the systems site-packages. Don’t worry, we will go into more detail later. After reading this article, you will understand what the following tools are and which problems they solve: pip, pyenv, venv, virtualenv, pipx, pipenv, pip-tools, setup.py, requirements.txt, requirementst.in, Pipfile, Pipfile.lock, twine, poetry, flint, and hatch. For this article, you need to distinguish two types of (packaged) code: Libraries are imported by other libraries or applications. Libraries do not run on their own; they are always run by an application. Examples for libraries in Python are Numpy, SciPy, Pandas, Flask, Django, click, Applications are executed. Examples for applications in Python are awscli, Jupyter (the notebooks), any website created with Flask or Django. You can further distinguish those, e.g. libraries and frameworks. Or command line applications, applications with graphical user interfaces, services, and many more. But for this article, we only need to distinguish between libraries and applications. Please note that some applications also contain code that can be imported or some libraries have a part of the functionality shipped as an application. In those cases, you can either use them as a library (including their code in your project) or as an application (just executing them). You are in command. Python has pip as a default package manager. You use it like this: pip install mpu When you run it, you should see this message: Collecting mpu Using cached https://files.pythonhosted.org/packages/a6/3a/c4c04201c9cd8c5845f85915d644cb14b16200680e5fa424af01c411e140/mpu-0.23.1-py3-none-any.whlInstalling collected packages: mpuSuccessfully installed mpu-0.23.1 In order to be able to show you both, the output and what I’ve inserted, I start the line which contains the command I’ve entered with $ : $ pip install mpuCollecting mpu Using cached https://files.pythonhosted.org/packages/a6/3a/c4c04201c9cd8c5845f85915d644cb14b16200680e5fa424af01c411e140/mpu-0.23.1-py3-none-any.whlInstalling collected packages: mpuSuccessfully installed mpu-0.23.1 This $ is called the prompt. Within Python, the prompt is >>> : $ python>>> import mpu>>> mpu.__file__'/home/moose/venv/lib/python3.7/site-packages/mpu/__init__.py' This command shows you where the package mpu was installed to. By default, this is the systems Python location. This means that all Python packages share the same set of installed libraries. We have Python 3.6 installed, but the application requires Python 3.8. We cannot upgrade our systems Python version, e.g. because we’re missing administrator privileges or because other things would break. Pyenv allows you to install any Python version you want. You can also easily switch between Python environments with pyenv : $ python --versionPython 3.6.0$ pyenv global 3.8.6$ python --versionPython 3.8.6$ pip --versionpip 20.2.1 from /home/math/.pyenv/versions/3.8.6/lib/python3.8/site-packages/pip (python 3.8) For more information, read my article A Beginner’s Guide to Python Development. For detailed installation instructions, go directly to the official pyenv website. You typically don’t only use bare Python. As developers, we stand on the shoulders of giants — the whole ecosystem of freely available software. In the beginning of Python, people just copied files. A Python file, when imported, is also called a module. If we have multiple Python files in one folder with an __init__.py , they can import each other. This folder is then called a package. Packages can contain other packages — subfolders which also have an __init__.py and are then called sub-packages. Copying files and folders is inconvenient. If the author of that code makes an update, I might need to update dozens of files. I need to know that there is an update in the first place. I might need to install hundreds of dependencies as well. Doing that by copy-and-paste would be hell. We need a more convenient way to distribute the packages. A packaging system needs three core components: Package Format: The simplest format in Python is called a source distribution. It is essentially a ZIP file that has a certain structure. One essential part of this file is the possibility to specify dependencies of the package. It should also contain other metadata, such as the name of the package, the author, and license information. Package manager: A program that installs packages. pip installs packages in Python. Software repository: A central place where package managers can look for packages. In the Python ecosystem, pypi.org is THE public one. I’m not even aware of other public ones. You can create private ones, of course. As mentioned, we need a way to specify metadata and dependencies. This is done with the setup.py file. It typically looks like this: from setuptools import setupsetup( name="my_awesome_package", version="0.1.0", install_requires=["requests", "click"]) There are many more version specifiers you can use, for example: numpy>3.0.0 # 3.0.1 is acceptable, but not 3.0.0numpy~=3.1 # 3.1 or later, but not version 4.0 or later.numpy~=3.1.2 # 3.1.2 or later, but not version 3.2.0 or later. In order to create the source distribution, we run $ python setup.py sdist I don’t like the setup.py file so much, because it is code. For metadata, I prefer to use a configuration file. Setuptools allows to use a setup.cfg file. You still need a setup.py, but it can be reduced to: from setuptools import setupsetup() And then you have the setup.cfg file as follows. There is documentation about the setup.cfg format. [metadata]name = my_awesome_packageauthor = Martin Thomaauthor_email = info@martin-thoma.demaintainer = Martin Thomamaintainer_email = info@martin-thoma.de# keep in sync with my_awesome_package/__init__.pyversion = 0.23.1description = Martins Python Utilitieslong_description = file: README.mdlong_description_content_type = text/markdownkeywords = utility,platforms = Linuxurl = https://github.com/MartinThoma/mpudownload_url = https://github.com/MartinThoma/mpulicense = MIT# https://pypi.org/pypi?%3Aaction=list_classifiersclassifiers = Development Status :: 3 - Alpha Environment :: Console Intended Audience :: Developers Intended Audience :: Information Technology License :: OSI Approved :: MIT License Natural Language :: English Operating System :: OS Independent Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 Programming Language :: Python :: 3.9 Topic :: Software Development Topic :: Utilities[options]packages = find:python_requires = >=3.7install_requires = requests click[tool:pytest]addopts = --doctest-modules --ignore=docs/ --durations=3 --timeout=30doctest_encoding = utf-8[pydocstyle]match_dir = mpuignore = D105, D413, D107, D416, D212, D203, D417[flake8]max-complexity=10max_line_length = 88exclude = tests/*,.tox/*,.nox/*,docs/*ignore = H301,H306,H404,H405,W503,D105,D413,D103[mutmut]backup = Falserunner = python -m pytesttests_dir = tests/[mypy]ignore_missing_imports = True You want to upload packages securely to PyPI. You need to authenticate and you want to be certain that nobody tampers with your package. Install twine via pip install twine and you can upload your distribution files: twine upload dist/* You want to install youtube-downloader which needs the library requests in version 1.2.3 and vimeo-downloader which needs the library requests in version 3.2.1 . Hence the library requests is a dependency of both applications. Both applications need to be executed with Python 3.8. That is a problem as both applications store requests in the same site-packages directory. Once you install one version, the other one is gone. You need two different environments to run those two applications. A Python environment is the python executable, pip, and the set of installed packages. Different environments are isolated from each other and thus don’t influence each other. We solve this dependency conflict by creating a virtual environment. We call it virtual because they actually share the Python executable and other things like the shells' environment variables. Python has the venv module which happens to be executable as well. You can create and use a fresh virtual environment like this: $ python -m venv my-fresh-venv$ source my-fresh-venv/bin/activate(my-fresh-venv)$ pip --versionpip 20.1.1 from /home/moose/my-fresh-venv/lib/python3.8/site-packages/pip (python 3.8) The environment is called “fresh” because there is nothing in it. Everything you install after source-ing the activate script will be installed in this local directory. This means when you install youtube-downloader in one such virtual environment and vimeo-downloader in another, you can have both. You can go out of a virtual environment by executing deactivate . If you want more details, I recommend to read Python Virtual Environments: A Primer. You would still need to switch between the virtual environments all the time which is inconvenient. pipx automatically installs packages into their own virtual environment. It also automatically executes the applications within that environment 😍 Note: This only makes sense for applications! You need libraries within the same environment as your application. So don’t ever install libraries with pipx. Install applications (and indirectly the libraries) with pipx. As an application developer, I want to be certain that my application keeps working. I want to be independent of potential breaking changes of third party software I use. For example, think about the youtube-downloader which needed requests in version 1.2.3. At some point, probably during development, that version of requests was likely the latest version. Then the development of the youtube-downloader was stopped, but requests kept changing. Give the exact version you want to install: numpy==3.2.1scipy==1.2.3pandas==4.5.6 However, this has a problem of its own if you do it in setup.py . You will force this version upon other packages in the same environment. Python is pretty messy here: Once another package installs one of your dependencies in another version in the same environment, it’s simply overwritten. Your dependencies might still work, but you don’t get the expected version. For applications, you can pin the dependencies like this in the setup.py and tell your users to use pipx to install them. This way you and your users can be happy 💕 For libraries, you cannot do this. By definition, libraries are included by other code. Code that potentially includes a lot of libraries. If all of them pinned their dependencies, it would be very likely to get a dependency conflict. This makes library development hard if the developed library itself has several dependencies. It’s common practice to NOT pin dependencies in the setup.py file, but instead create a flat text file with pinned dependencies. PEP 440 defined the format or requirements files in 2013. It’s usually called requirements.txt or requirements-dev.txt and typically looks like this: numpy==3.2.1scipy==1.2.3pandas==4.5.6 You can also specify locations where the packages can be downloaded (e.g. not only the name but a git repository) according to PEP 440. Packages within a requirements.txt (including their dependencies) can be installed with $ pip install -r requirements.txt Imagine you write code which depends on the packages foo and bar . Those two packages might themselves have dependencies as well. Those dependencies are called transitive dependencies of your code. They are indirect dependencies. The reason why you need to care is the following. Assume there are multiple versions of foo and bar published. foo and bar happened to both have exactly one dependency: fizz Here is the situation: foo 1.0.0 requires fizz==1.0.0foo 1.2.0 requires fizz>=1.5.0, fizz<2.0.0foo 2.0.0 requires fizz>=1.5.0, fizz<3.0.0bar 1.0.0 requires fizz>2.0.0bar 1.0.1 requires fizz==3.0.0fizz 1.0.0 is availablefizz 1.2.0 is availablefizz 1.5.0 is availablefizz 2.0.0 is availablefizz 2.0.1 is availablefizz 3.0.0 is available You might be tempted to just say “I need foo==2.0.0 and bar==1.0.0 . There are two problems: Dependency satisfaction can be hard: The client needs to figure out that those two requirements can (only) be satisfied by fizz==2.0.0 orfizz==2.0.1 . This can be time-consuming as Python source distributions are not well designed and do not expose this information well (example discussion). The dependency resolver actually needs to download the package to find the dependencies.Breaking transitive change: The packages foo and bar could not state their dependencies. You install them and things work, because you happen to have foo==2.0.0 , bar==1.0.0 , fizz==2.0.1 . But after a while, fizz==3.0.0 is released. Without telling pip what to install, it will install the latest version of fizz . Nobody tested that before as it didn’t exist. Your user is the first one and it breaks for them 😢 Dependency satisfaction can be hard: The client needs to figure out that those two requirements can (only) be satisfied by fizz==2.0.0 orfizz==2.0.1 . This can be time-consuming as Python source distributions are not well designed and do not expose this information well (example discussion). The dependency resolver actually needs to download the package to find the dependencies. Breaking transitive change: The packages foo and bar could not state their dependencies. You install them and things work, because you happen to have foo==2.0.0 , bar==1.0.0 , fizz==2.0.1 . But after a while, fizz==3.0.0 is released. Without telling pip what to install, it will install the latest version of fizz . Nobody tested that before as it didn’t exist. Your user is the first one and it breaks for them 😢 You need to figure out the transitive dependencies as well and tell pip exactly what to install. To do so, I start either with a setup.py or a requirements.in file. The requirements.in file contains what I know must be fulfilled — it’s pretty similar to the setup.py file. In contrast to the setup.py file it is a flat text file. Then I use pip-compile from pip-tools to find the transitive dependencies. It will generate a requirements.txt file which looks like this: ## This file is autogenerated by pip-compile# To update, run:## pip-compile setup.py#foo==2.0.0 # via setup.pybar==1.0.0 # via setup.pyfizz==2.0.1 # via foo, bar Typically, I have the following: setup.py: Defining abstract dependencies and known minimum versions / maximum versions. requirements.txt: One version combination that I know works on my machine. For web services where I control the installation, this is also used to install the dependencies via pip install -r requirements.txt requirements-dev.in: Development tools I use. Things like pytest, flake8, flake8 plugins, mypy, black ... see my static code analysis post. requirements-dev.txt: The exact version of the tools I use + their transitive dependencies. Those are also installed in the CI pipeline. For applications, I also include the requirements.txt file in here. Please note that I create a combined requirements-dev.txt which includes the requirements.txt . If I would install the requirements.txt before the requirements-dev.txt, it could change the version. That would mean I would not test against exactly the same package versions. If I would install the requirements.txt after the requirements-dev.txt , I could break something for the dev tools. Hence I create one combined file viapip-compile --output-file requirements-dev.txt requirements.txt You can also add --generate-hashes if you want to be certain it’s exactly the same. Packages like cryptography have code written in C. If you install the source distribution of cryptography, you need to be able to compile that code. You might not have a compile like gcc installed and compiling takes quite a bit of time. Package creators can also upload built distributions, e.g. as wheels files. This prevents you from having to compile stuff yourself. It is done like this: $ pip install wheels$ python setup.py bdist_wheel For example, NumPy does this: The Python ecosystem is very strongly attached to setuptools. No matter how good setuptools are, there will always be features people are missing. But we couldn’t change the build system for quite a while. PEP 517 and PEP 518 specified thepyproject.toml file format. It looks like this: [build-system]requires = ["poetry-core>=1.0.0"]build-backend = "poetry.core.masonry.api" Yes, it’s not much. It tells pip what is necessary to build your package. But it was a good step towards more flexibility. Other tools, like poetry and black, used this file for their configuration to the pyproject.toml , similar as flake8 , pytest , pylint and many more allow you to add configuration to the setup.cfg . The tools in this section are relatively wide-spread, but as of today, they don’t really solve any issue that one of the tools from above doesn’t solve. They might be more convenient to use than others. The 3rd party tool virtualenv existed before the core module venv. They are not completely identical, but for me, venv was always good enough. I’m happy if somebody can show me a problem to which virtualenv (and not venv) is the solution 🙂 virtualenvwrapper extends virtualenv. Pipenv is a tool for dependency management and packaging. It introduces two new files: Pipfile: A TOML file. Its content is similar in thought to the one of requirements.in : Abstract dependencies. Pipfile.lock: A TOML file. Its content is similar in thought to the one of requirements.txt : Pinned concrete dependencies, including transitive dependencies. Essentially, it wraps venv. Poetry is a tool for dependency management and packaging. It combines a lot of tools, but it’s core functionality is identical to pipenv. The main difference is that it uses pyproject.toml and poetry.lock instead of Pipfile and Pipfile.lock . A detailed comparison between poetry and pipenv was written by Frost Ming. The projects poetry wraps or replaces are: Scaffolding: poetry new project-name vs cookie-cutter Building Distributions: poetry build vs python setup.py build sdist_build Dependency Management: poetry add foobar vs manually editing the setup.py / requirements.txt file. Poetry will then create a virtual environment, a poetry.lock file which is identical in concept to the Pipfile.lock and update the pyproject.toml . You can see an example of that below. They use their own dependency section which will not be compatible with anything else. I hope they move to PEP 631 (see issue for updates). Upload to PyPI: poetry publish vs twine upload dist/* Bump version: poetry version minor vs manually editing setup.py / setup.cfg or using bumpversion . ⚠️ Although poetry generates an __init__.py in the scaffolding which contains a version, poetry version does not change that! It goes away from the de-facto standard setup.py / setup.cfg for specifying dependencies. Instead, poetry expects dependencies to be within it’s configuration: [tool.poetry]name = "mpu"version = "0.1.0"description = ""authors = ["Martin Thoma <info@martin-thoma.de>"]license = "MIT"[tool.poetry.dependencies]python = "^3.8"awscli = "^1.18.172"pydantic = "^1.7.2"click = "^7.1.2"[tool.poetry.dev-dependencies] I hope that they will also implement PEP 621 and PEP 631 which gives metadata and dependencies an official place under the [project] section. Let’s see, maybe they change that. Some people like to have one tool which does everything. I rather go with the Unix philosophy: Make each program do one thing well. To do a new job, build afresh rather than complicate old programs by adding new “features”. As poetry combines a lot of tools, it’s also important what it doesn’t do: Package management: You still need pip. And pip supports pyproject.toml. Scaffolding: Cookiecutter has a lot of templates. I created two myself: one for typical Python projects and one for Flake8 plugins. Setup.py: You might not need to create one yourself, but poetry creates a setup.py file for you. Just look at the distribution file. I should also point out that poetry has a super nice CLI and a visually pleasing website. Hatch also aims to replace quite a lot of tools: Scaffolding: hatch new project-name vs cookie-cutter Bump version: hatch grow minor vs manually editing setup.py / setup.cfg or using bumpversion Running pytest: hatch test vs pytest Create a virtual environment: hatch env my-venv vs python -m venv my-venv Installing packages: hatch install package vs pip install package I had a couple of errors when I tried hatch. Flit is a way to put Python packages and modules on PyPI. It is a 3rd party replacement for setuptools. In that sense, it’s similar to setuptools + twine or a part of poetry. Conda is the package manager of Anaconda. It is way more powerful than pip and can build/install code of arbitrary languages. With the pyproject.toml , I wonder if conda will be necessary in future 🤔 easy_install : That is the oldest way to install stuff in Python. It is similar to pip , but you cannot (easily) uninstall things that were installed with easy_install distutils : Although it’s core Python, it’s not used anymore. setuptools is more powerful and installed everywhere. distribute : I’m not sure if that ever was a thing? pyvenv : Deprecated in favor of venv . pip is Pythons package manager. It goes to the Python package index PyPI.org to install your packages and their dependencies. Abstract dependencies can be denoted with setup.py, requirements.in, Pipfile, or pyproject.toml. You only need one. Concrete dependencies can be denoted with requirements.txt, Pipfile.lock, or poetry.lock. You only need one. Building packages is done with setuptools or with poetry. Uploading packages is done with twine or poetry. Virtual environments are created with venv or with poetry / pipenv / hatch / conda pipx is cool if you want to install applications. Don’t use it for libraries.
[ { "code": null, "e": 371, "s": 171, "text": "A virtual environment is an isolated Python environment. It has it’s own installed site-packages which can be different from the systems site-packages. Don’t worry, we will go into more detail later." }, { "code": null, "e": 636, "s": 371,...
TypeScript class - GeeksforGeeks
14 Nov, 2019 In terms of OOPs(Object Oriented Programming), a class is a blueprint which is used for creating objects. A class is a collection of objects having common properties.It contains methods,constructors,blocks,nested classes,interfaces etc. Objects are basically the entities that have some properties like an object in the real world(chair, table etc).Typescript is an open source programming language which is built over Javascript, also known as Superset of Javascript. Typescript has more features as when compared to the Javascript. It supports Object Oriented programming features like classes, Interface, Polymorphism etc. Syntax to declare a class: // typescript codeclass class_name{ field; method;} The above code when passed into a typescript compiler will get converted into the javascript code shown below. We are free to use any name instead of class_name. // code converted to javascriptvar class_name = /** @class */ (function () { function class_name() { } return class_name;}()); Note: The typescript code is saved using the .ts extension.Let’s see some typescript examples too: // typescript codeclass Student { studCode: number; studName: string; constructor(code: number, name: string) { this.studName = name; this.studCode = code; } getGrade() : string { return "A+" ; }} The example declare a Student class which has two fields that is studCode and studName and a constructor which is special type of function which is responsible for variable or object initialization. Here it is parameterized constructor(already having the parameters). And this keyword which refers to the current instance of the class. getGrade() is a simple function which returns a string.The above typescript code will be converted into the javascript code as shown below: // converted javascript codevar Student = /** @class */ (function () { function Student(code, name) { this.studName = name; this.studCode = code; } Student.prototype.getGrade = function () { return "A+"; }; return Student;}()); ObjectsAn object is an instance of class which contains set of key value pairs. It’s value may be scalar values or functions or even array of other objects.Syntax of an Object looks like the code below: // simple object code in javascriptlet object_name = { key1: “value”, key2: function() { //functions }, key3:[“content1”, “content2”] //collection }; An object can contain scalar value, functions and structures like arrays and tuples.Let’s see with simple example: // simple javascript codelet person = { fName:"Mukul", lName:"Latiyan", Hello:function() { } //Type template } person.Hello = function() { console.log("Hello "+person.fName)} person.Hello() Output: // typescript object examplevar person = { fname:"Mukul", lname:"Latiyan" }; var hello = function(obj: { fname:string, lname :string }) { console.log("first name :"+obj.fname) console.log("last name :"+obj.lname) } hello(person) Output:For creating Instance Objects.To create an instance of the class, use with the new keyword followed by the class name. To allocates memory for objects with the help new during runtime. Like: let object_name = new class_name([ arguments ]) In order to create an instance of an object we can do something like the code below. let obj = new Student(); Accessing Attributes and Functions:A class’s attributes and functions can be accessed by the object. With the help of ‘ . ’ dot notation or bracket notation([”]) we access the data members of a class. //accessing an attribute obj.field_name or obj['field_name'] //accessing a function obj.function_name() Consider the code below: // typescript codeclass Car { //field engine:string; //constructor constructor(engine:string) { this.engine = engine } //function display():void { console.log("Function displays Engine is : "+this.engine) } } //create an object var o1 = new Car("geeks") //access the field console.log("Reading attribute value Engine as : "+o1.engine) //access the functiono1.disp() After compilation this code will be converted into the javascript shown below: // converted javascript codevar Car = /** @class */ (function () { //constructor function Car(engine) { this.engine = engine; } //function Car.prototype.display = function () { console.log("Function displays Engine is : " + this.engine); }; return Car;}());//create an object var o1 = new Car("geeks");//access the field console.log("Reading attribute value Engine as : " + o1.engine);//access the functiono1.disp(); Output: shubham_singh TypeScript 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 How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page? How to set the default value for an HTML <select> element ? File uploading in React.js Node.js fs.readFileSync() Method How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 25829, "s": 25801, "text": "\n14 Nov, 2019" }, { "code": null, "e": 26455, "s": 25829, "text": "In terms of OOPs(Object Oriented Programming), a class is a blueprint which is used for creating objects. A class is a collection of objects having common properti...
Tryit Editor v3.7
Tryit: Using the var() function
[]
How To Collaborate On Your Locally Hosted Jupyter Notebook | by Kurtis Pykes | Towards Data Science
Some while back I received a call from a good friend that is learning about Data Science and wanted some help. As we are often taught about Jupyter Notebooks when learning Data Science, it was not surprise that he was using a Jupyter Notebook, but this instantly stomped me. How are we going to collaborate on a Notebook? We ended up doing a zoom call and he gave me authorization to control his screen, but the latency was turning me crazier than the problem at hand. Fast-forward 2 months, the tables have turned, I am now the one in need. I reached out to a Senior Data Scientist (we will call him Billy for this article) and told him of my woes: Billy: That’s fine, Do you want to do some pair programming? Me: Yes please that would be great. ** Sigh of relief ** Billy: Are you using Google Colabs? Note: Turns out Colab is super easy to collaborate on. Me: No, I am using Jupyter Notebooks locally Billy: That’s fine. We can use Ngrok! Me: Ah yes, Sure! I will be totally honest... I had no clue what Ngrok was, but I had faith in my googling skills. Ngrok exposes local servers behind NATs and firewalls to the public internet over secure tunnels. Subsequently, we are able to provide our local server to the port of a web server and this enables us to get the local address we specified — If this makes no sense to you, don’t worry about it. All I am saying is that we will obtain a public URL of our locally hosted Jupyter Notebook that we can share and use to collaborate. Setting up Ngrok consist of 3 simple steps: Sign Up Sign Up You can easily make a free account by clicking on “Sign Up”. Just fill in your credentials and you’re fired up — Link to sign up page here 2. Download Download Ngrok that is suitable for your operating system then Unzip it once it’s downloaded. Note: On Linux or Mac OS X you can unzip ngrok from a terminal with the following command. On Windows, just double click ngrok.zip to extract it. unzip /path/to/ngrok.zip 3. Connect your Account The next step is simply authenticating your Ngrok agent, which only needs to be done once as the Authtoken is saved in the default configuration file. Your authentication token can be accessed by going to Authentication on the side bar then Your Authtoken — See image below. I prefer the command line set up which includes simply telling Ngrok your authentication token. ./ngrok authtoken 1g3Zd5XeTdmRTYIvOZmGVBW3hAH_2873ypJDaDf6ybyUzmSUj Great! You are now all set up, but now you must learn to share your Jupyter Notebook. For Jupyter Notebooks to be accessed remotely we must make some adjustments to our Jupyter Notebook configuration, and for extra security, we will add a password. jupyter notebook --generate-config This will return the link address to the configuration file of your Jupyter Notebook. Writing default config to: C:\Users\Kurtis\.jupyter\jupyter_notebook_config.py Copy the link address and run the following command echo "NotebookApp.allow_remote_access = True" >> C:\Users\Kurtis\.jupyter\jupyter_notebook_config.py Then we add a password... jupyter notebook password We now have everything required to run and connect our Jupyter Notebook so that it could be shared remotely. Tip: In the next part we’ll need two separate terminals connected to our remote because once we run jupyter, it will occupy a window with logging. You can either open a second terminal and ssh into it again, or you can use a tool like tmux to manage them within a single terminal. (Source: ArtificialSoph Github) Open your Jupyter Notebook by typing jupyter notebook in your terminal. jupyter notebook After we’ve accessed our Jupyter Notebook we tell Ngrok what port our web server is listening on. The above image highlights the port. Thence we would tell Ngrok the port is 8888. ngrok http [port] -host-header="localhost:[port]" Your results should look like the one displayed below Copy the forwarding address and share it with whoever you want to collaborate with — if you followed our steps and set up a password then you’ll have to tell them the password. Great, now you can collaborate! Magnificent! Now you don’t have to be stomped or put up with bad latency (because you’ve shared your screen on zoom) whenever you need to collaborate with someone on a Jupyter Notebook on their local machine (or yours for that matter) — You now know how to share your Jupyter Notebook and work on a different machine. I enjoy connecting with people, I am most reachable on LinkedIn — Connect and stay up to date with anything new I am learning (and feel free to share what you’re learning too).
[ { "code": null, "e": 494, "s": 172, "text": "Some while back I received a call from a good friend that is learning about Data Science and wanted some help. As we are often taught about Jupyter Notebooks when learning Data Science, it was not surprise that he was using a Jupyter Notebook, but this in...
Building an ETL pipeline with Airflow and ECS | by Daniel Da Costa | Towards Data Science
ETL is an automated process that takes raw data, extracts and transforms the information required for analysis, and loads it to a data warehouse. There are different ways to build your ETL pipeline, on this post we’ll be using three main tools: Airflow: one of the most powerful platforms used by Data Engineers for orchestrating workflows. AWS ECS/Fargate: a container management service that makes it easy to run, stop, and manage your containers. AWS s3: AWS simple storage service. The architecture that we will be building follows the schema bellow: First of all, you will need to have an ETL script ready to deploy. In this post, we will be using a Python script that reads from S3, transforms the data, and save it back to S3. You can check the full code here. Since we will be using a container-based application, we need to build our Docker Image containing all prerequisites to run the ETL job and configuration. Here is an example of my Dockerfile: FROM python:3.7-slimENV APP_DIR /ml-pipelineRUN mkdir -p ${APP_DIR}WORKDIR ${APP_DIR}COPY . .RUN apt-get updateRUN apt-get install libgomp1RUN pip install -r requirements.txtENV READ_BUCKET=ml-sls-deploy-prdENV READ_DATA_PATH=dataENV READ_MODELS_PATH=modelsENV WRITE_BUCKET=ml-sls-deploy-prd-resultsENV WRITE_DATA_PATH=resultsCMD ["python", "main.py"] To upload your image to your ECS repository, you will need to store it in a registry like Docker Hub, for example. I used Amazon ECR, AWS's fully managed container service. First, you will need to create a Repository on ECR. Second, you will need to push your container image to the repository, using the following set of commands. ECS is a container orchestration service provided by AWS. ECS has two launch types that can define how the compute resources will be managed: The traditional EC2 launch type, where it utilizes EC2 underneath to power its compute resources. Fargate removes the responsibility of provisioning, configuring, and managing the EC2 instances by allowing AWS to manage the EC2 instances. The Fargate billing is described by Nathan Peck in EC2 or AWS Fargate?: With the AWS Fargate launch type, billing is based on how many CPU cores, and gigabytes of memory your task requires, per second. You only ever pay for what your task uses, no more paying for EC2 capacity that goes unused. One of the use cases of Fargate is for small workloads, a small test environment; that's exactly what we are looking for! If you want to dig deep on which launch type of ECS to choose you can check this post: ECS or Fargate? The main steps for creating your cluster are: Create a Cluster: Choose Network only. This configuration is built using Fargate Tasks: the Fargate launch type allows you to run your containerized applications without the need to manage EC2 instances, you pay for running tasks. When you run a task, Fargate launches the containers for you. Task Definition: The creation of your container blueprint. You’ll need to create a Task Role: IAM Role that tasks can use to make API requests to authorized AWS services; Since our container is reading and writing to/from s3, it will need these permissions. You will also need to create a Task Execution Role: an IAM that helps pulling images from your docker register, we are using ECR here. Add a Container: You’ll need to deploy your container to ECS Fargate. You may use here our Docker Image created in section ETL. We won’t go through all the steps on how to create your own ECS cluster, since there are many tutorials on how to do it on the internet. I recommend that you follow this tutorial. Nowadays, Airflow is used to solve a variety of data ingestion, preparation, and consumption problems. The platform allows you to build you own ETL for integrating data between disparate systems, you can use it to build simple workflows or even to orchestrate complex ML workflows. Airflow also counts on a huge open source community! One of the main benefits of using Airflow is that is designed as a configuration-as-code: Airflow pipelines are defined in Python, allowing us to build pipelines in a very simple way. In this post, we will be using Docker for deploying airflow on our local computer. You will just need to set up your Dockerfile as follows: FROM puckel/docker-airflowWORKDIR /airflowRUN pip install boto3 We will need to install the boto3 library inside our container so that we can configure our AWS credentials in Airflow. After building the docker image, we will create a volume that maps the directory on our local machine where we’ll hold DAG definitions and the locations where Airflow reads them on the container with the following command: docker run -d -p 8080:8080 -v /path/to/dags/on/your/local/machine:/usr/local/airflow/dags {your-image} You can go now to your localhost:8080 to access your Airflow UI! OBS: If you'd like to host it directly on the cloud you may use AWS's new service: Amazon Managed Workflows for Apache Airflow. You can check more about it here. You will need do set yours AWS credentials through the Airflow UI. Go to Admin > Connection > Create Create a connection called aws_credentials of type Amazon Web Services. Put your AWS_ACCESS_KEY_ID on Login and your AWS_SECRET_ACCESS_KEY on Password: We will be creating a DAG with the following characteristics: schedule_interval: Our DAG will be run manually through the Airflow UI interface, ECS Operator: We will be using this operator to run our task defined in AWS ECS. Environment Variables: We will need to define some local variables containing information from our ECS Cluster and Task Definition. These environment variables are created directly on the Airflow UI. Go to Admin > Variables and create the following variables: Once everything is set up, you will just have to run your DAG! Congratulations! You have just created your ETL pipeline using Airflow and ECS. Running an ETL pipeline is often troublesome. We need to provision and manage the backend infrastructure, making it as reliable as possible. The architecture described in this post makes it easy to run ETL workflows as quickly as possible and sufficiently reliable for some use cases. You can check the full code in here!
[ { "code": null, "e": 417, "s": 172, "text": "ETL is an automated process that takes raw data, extracts and transforms the information required for analysis, and loads it to a data warehouse. There are different ways to build your ETL pipeline, on this post we’ll be using three main tools:" }, { ...
JavaScript | Text Formatting - GeeksforGeeks
05 Jun, 2020 JavaScript has many inbuilt features to format the text. Texts are the strings in javascript. There are many formatting styles like making text uppercase, lowercase, bold, italic. Each formatting style is given below with the example. Making text UpperCase: It is used to convert the string to uppercase. Javascript let text = "geeks for geeks"console.log("text before formatting is " + text);text.toUpperCase()console.log("text after formatting is " + text); Output: Making text LowerCase: It is used to convert the string to lowercase. Javascript let text = "GEEKS FOR GEEKS"console.log("text before formatting is " + text);text.toLowerCase()console.log("text after formatting is " + text); Output: Use of Substr: It is used to take the substring from the string. The first parameter is the index from which the string has to start and the second parameter is the length of substring. Note: Please note that the second parameter is not the index. Javascript let text = "GEEKS FOR GEEKS"text = text.substr(10, 5)console.log("substring is " + text); Output: Use of repeat: Use of repeat is done when we need to repeat a particular string or substring to be printed in a particular number of times. Javascript let text = 'geeks for geeks ';console.log(`string is repeated 2 times: ${text.repeat(2)}`); Output: Use of trim: It is used to remove the extra spaces around the string. Note: It does not remove the spaces from between the text and words. Javascript let txt = ' geeks for geeks ';console.log(`string with no trailing spaces, ${txt.trim()}`); Output: JavaScript-Misc JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 Open URL in New Tab using JavaScript ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24488, "s": 24460, "text": "\n05 Jun, 2020" }, { "code": null, "e": 24723, "s": 24488, "text": "JavaScript has many inbuilt features to format the text. Texts are the strings in javascript. There are many formatting styles like making text uppercase, lowercas...
Cells with Odd Values in a Matrix in C++
Suppose there are n and m which are the dimensions of a matrix. These are initialized by zeros. And indices are given where indices[i] = [ri, ci]. For each pair of [ri, ci] we have to increment all cells in row ri and column ci by 1. The output will be the number of cells with odd values in the matrix after applying the increment to all indices. To solve this, we will follow these steps − Initialize odd := 0, and x := row count of the matrix create a matrix mat for i in range 0 to xr = input[i, 0], c = input[i, 1],for j in range 0 to m – 1mat[r, j] := mat[r, j] + 1for j in range 0 to n – 1mat[j, c] := mat[j, c] + 1 r = input[i, 0], c = input[i, 1], for j in range 0 to m – 1mat[r, j] := mat[r, j] + 1 mat[r, j] := mat[r, j] + 1 for j in range 0 to n – 1mat[j, c] := mat[j, c] + 1 mat[j, c] := mat[j, c] + 1 for i in range 0 to n – 1for j := 0 to m – 1odd := odd + mat[i, j] bitwise or with 1 for j := 0 to m – 1odd := odd + mat[i, j] bitwise or with 1 odd := odd + mat[i, j] bitwise or with 1 return odd Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int oddCells(int n, int m, vector<vector<int>>& in) { int odd = 0; int x = in.size(); vector < vector <int> > mat(n, vector <int>(m)); for(int i = 0; i < x ;i++){ int r = in[i][0]; int c = in[i][1]; for(int j = 0; j < m; j++){ mat[r][j]++; } for(int j = 0; j < n; j++){ mat[j][c]++; } } for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++)odd += mat[i][j] & 1; } return odd; } }; main(){ Solution ob; vector<vector<int>> c = {{0,1},{1,1}}; cout << ob.oddCells(2,3,c); } 2 3 {{0,1},{1,1}} 6
[ { "code": null, "e": 1410, "s": 1062, "text": "Suppose there are n and m which are the dimensions of a matrix. These are initialized by zeros. And indices are given where indices[i] = [ri, ci]. For each pair of [ri, ci] we have to increment all cells in row ri and column ci by 1. The output will be ...
What is the difference between MySQL TINYINT(2) vs TINYINT(1)?
The number 2 and 1 in TINYINT(2) vs TINYINT(1) indicate the display width. There is no difference between tinyint(1) and tinyint(2) except the width. If you use tinyint(2) or even tinyint(1), the difference is the same. You can understand the above concept using zerofill option. tinyint(1) zerofill tinyint(2) zerofill Let us create a table. The query to create a table is as follows − mysql> create table tinyIntDemo -> ( -> Number1 tinyint(1) zerofill, -> Number2 tinyint(2) zerofill -> ); Query OK, 0 rows affected (0.62 sec) Insert record in the table using insert command. The query is as follows − mysql> insert into tinyIntDemo values(1,1); Query OK, 1 row affected (0.12 sec) Display records from the table using select command. The query is as follows − mysql> select *from tinyIntDemo; The following is the output. Spot the difference between both in the below result − +---------+---------+ | Number1 | Number2 | +---------+---------+ | 1 | 01 | +---------+---------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1212, "s": 1062, "text": "The number 2 and 1 in TINYINT(2) vs TINYINT(1) indicate the display width. There is no difference between tinyint(1) and tinyint(2) except the width." }, { "code": null, "e": 1342, "s": 1212, "text": "If you use tinyint(2) or even ti...
Default flow of traffic (ASA) - GeeksforGeeks
22 Nov, 2021 Prerequisite – Adaptive security appliance (ASA) ASA is a Cisco security device that can perform a firewall capability with VPN capabilities, routing support, antivirus capability, and many other features. Security levels – ASA uses a security level associated with a routable interface. Remember, the ASA interface is by default in routed mode i.e operating at layer 3. These interfaces are assigned security levels which are numbers ranging from 0 to 100. The bigger the number, the more will be the trust to the network connected to that ASA interface. On the basis of security levels, ASA takes action (whether to permit or deny the packet). Also, note that we can assign names to the ASA interface like inside, outside, or DMZ. As soon as we assign these names to an interface, it automatically assigns a security level to itself. For example, if we have assigned a name inside to an interface, it will assign 100 (Security level) to itself i.e most trusted network. If we assign the name Outside or DMZ or any other name to an interface, it will assign security level 0 to automatically. These are default values and can be changed. It is a good practice to give security level 100 (maximum) to inside (most trusted network), 0(least) to outside (untrusted or public network), and 50 to DMZ (organization public device network). Note – It is not mandatory to assign a name (INSIDE, OUTSIDE, or DMZ) to the ASA interface but it is good practice to assign these names as they are simple and meaningful. Default Flow of traffic – Note that if the traffic is inspected then the state of the packet will be kept i.e connection table will be maintained therefore the replies will be allowed (from an untrusted network) while if the action on the traffic is pass, only the traffic will be passed and no connection table is maintained. By default, ASA allows a flow of traffic from higher security levels to lower security levels. If the traffic is initiated by the devices in higher security levels, then it will be passed to go through the firewall to reach the devices in lower security levels like outside or DMZ. And if the (TCP or UDP) traffic is initiated from a higher security level then the replies (for higher security level) from lower security level (outside or DMZ) are allowed. This is due to default stateful inspection (which means a state of the packet will be maintained in the connection table). But if the traffic is of ICMP that is to be sent from higher security level to lower security level then it will reach the lower security level device and the lower security level will also send echo reply but the firewall (ASA) will drop it as only TCP and UDP traffic is inspected by default. If we want ICMP traffic to be inspected by the ASA then we have to do it manually by the command. asa(config)#fixup protocol ICMP Also, if the lower security level (outside or DMZ) wants to send any traffic (TCP, UDP, or ICMP) to the higher security level then it is denied by the ASA firewall due to its default policy. To allow it, an access list can be used. Also, note that when we give security level 50 to DMZ, 100 to inside, and 0 to outside, then the traffic will be allowed from DMZ to outside but DMZ devices still not be able to reach inside devices. Also, by default, if two interfaces have the same security level then the traffic will not be allowed. But the traffic can be allowed manually (between the two interfaces having the same security level) by the command asa(config)#same-security-traffic permit inter-interface tanwarsinghvaibhav Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments RSA Algorithm in Cryptography Data encryption standard (DES) | Set 1 Socket Programming in Python Types of Network Topology UDP Server-Client implementation in C TCP 3-Way Handshake Process Differences between IPv4 and IPv6 Socket Programming in Java Hamming Code in Computer Network Types of area networks - LAN, MAN and WAN
[ { "code": null, "e": 24461, "s": 24433, "text": "\n22 Nov, 2021" }, { "code": null, "e": 24668, "s": 24461, "text": "Prerequisite – Adaptive security appliance (ASA) ASA is a Cisco security device that can perform a firewall capability with VPN capabilities, routing support, anti...
A Gentle Implementation of Reinforcement Learning in Pairs Trading | by Wai | Towards Data Science
This covers topics from concepts to implementation of RL in cointegration pair trading based on 1-minute stock market data. For the Reinforcement Learning here we use the N-armed bandit approach. The code is expandable so you can plug any strategies, data API or machine learning algorithms into the tool if you follow the style. Takeaway:1. Expandable infrastructure with data fetching utility2. Combined techniques of python code structuring3. General concept and theories across coding, econometrics, and reinforcement learning topics github.com Tiingo is a financial research platform that provides data including news, fundamentals and prices. We can extract the intraday stock market data through its REST IEX API that retrieves TOPS data (top of book, last sale data and top bid and ask quotes) from the IEX Exchange. For example, simply paste this link in your browser: https://api.tiingo.com/iex/aapl/prices?startDate=2019-01-02&endDate=2019-01-02&resampleFreq=5min&token=ef79e455ba9b04c3df719407e34f05e1b051b4d6 and you will get a list of historical 5-minute intraday prices for AAPL as of 2019–01–02 in JSON format: [{"date":"2019-01-02T14:30:00.000Z","open":154.74,"high":155.52,"low":154.58,"close":154.76},{"date":"2019-01-02T14:35:00.000Z","open":154.8,"high":155.0,"low":154.31,"close":154.645},{"date":"2019-01-02T14:40:00.000Z","open":154.67,"high":154.94,"low":154.25,"close":1... To automate the task we will need functions that can get standardised intraday data within a specified historical window for a list of stocks. Limitations Up to 1-minute frequency for historical data For each request for each stock, the maximum no.of samples retrieved is not consistent, i.e. you may get data up to few days only even if you specify a window with 365 days The no. of samples for each day is not consistent (i.e. it may also gives you the prices after the market opening hours) Not fast enough (maybe it’s just my problem) Solutions Fetch 1 stock for 1 date at a time Truncate the samples by a fixed no. of observations, i.e. assume there are 391 1-minute prices for each date Asynchronous I/O Pandas also provides relevant tools to extract data from not only Tiingo but also other data providers, but it seems that they only extract daily data. Note that subject to your subscription and the corresponding limits on requests, the API data is free. However, you should be aware of the usage when you use the code and avoid challenging the limits. First of all, you need a Tiingo API token. Simply sign-up for an account and you will find your token in here. These are the major functions which are located in Data/API.py inside the code: We need a function that can give us the url to retrieve the intraday data for a specific stock [ticker], date [target_date], frequency [freq], given that your token [token] is valid. You can imagine we could dynamically call this function to retrieve the data date-by-date so that we can standardize the format easily across a series of fetching. We need a function that can give us the url to retrieve the intraday data for a specific stock [ticker], date [target_date], frequency [freq], given that your token [token] is valid. You can imagine we could dynamically call this function to retrieve the data date-by-date so that we can standardize the format easily across a series of fetching. 2. Pandas read_json allows us to read the fetched JSON data into a Series or DataFrame. We can wrap this inside the class: 3. The functions above are defined under the class Tiingo in Data/API.py. The code will repeat the fetching based on the key inputs: start date, end date, the target attributes (i.e. ‘date’ and ‘close’) and a list of stocks and output a combined dataframe Asynchronous I/O The implementation above is constrained and slow. Every time when we start a fetch, the program will open the API connection, request for the data from the server and wait for it’s response before closing the connection. After all the progress repeats until the final url is fetched. Let’s check how big is the difference with AsyncIO. The code below fetches 1-minute prices between 2018–01–01 and 2018–01–31 for GOOG and FB. 391 samples for each date, around 15,600 observations in total. All settings are configured in the config dictionary but let’s ignore that for the time being. The result below shows that with AsyncIO it is about 17 times faster than the normal fetching. According to the python documentation: asyncio is a library to write concurrent code using the async/await syntax. asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web-servers, database connection libraries, distributed task queues, etc. Unlike parallel programming, AsyncIO is single-thread. A simple idea is, it pipelines the assigned tasks in a single-event handler which organizes the distribution of tasks so that multiple tasks can start running while the others are idle. To illustrate the concept, let’s have a look into an official example: The keyword async def above defines the corresponding function as a coroutine which can suspend or resume executions. Whenever a task is working-in-progress inside under the keyword await, the process control is passed back to the event controller (loop) which allocate and start the process for another task. To put it simply, it does not waste the waiting time. In our code we also have something similar. The _fetch_hist_async will create an event loop to controls the process of fetch_data_async which is the underlying task that fetches the intraday prices. When await is encountered, the control is returned to the event loop which triggers another fetching request even if the previous one is yet to be finished. Ideally we should set up a database to store the prices. For simplicity let’s save the prices in .csv under the directory STATICS/PRICE: Let’s skip the Part 2 which covers the boring code and structure and do some analysis. But I still recommend you to go to the end of this article and read that and have a concept about the skeleton first if you are interested. Pairs trading is a market neutral strategy. As described by Gatev et al. (2006): “The concept of pairs trading is disarmingly simple. Find two stocks whose prices have moved together historically. When the spread between them widens, short the winner and buy the loser. If history repeats itself, prices will converge and the arbitrageur will profit. “ It summarises the strategy into two stages: In the formulation period we measure the price relationship between stocks and identify stock pairs in scope.In the subsequent trading period the relationship is being monitored and traded upon pre-defined rules. In the formulation period we measure the price relationship between stocks and identify stock pairs in scope. In the subsequent trading period the relationship is being monitored and traded upon pre-defined rules. To put it simply, it trades on the mean-reverting spreads. The question is, how do we estimate or verify the price dynamics between the stock pair? Krauss (2017) summarises the common approaches in pairs trading strategies into five categories: distance approach, cointegration approach, time series approach, stochastic control approach, and other approaches such as machine learning, principal components analysis, and copula. This article will demonstrate the use of the classical Engle and Granger (1987) cointegration approach in a combination of reinforcement learning algorithms for pairs trading. The idea here is linked to a concept in time series analysis called stationarity. It is more often referred to the weak-form (or covariance) stationarity in financial time series with the following criteria: Expected value of random variable x, i.e. E[x(t)], is independent of time tVariance Var(x(t)) is a time-independent positive and finite constantCovariance Cov(x(t),x(s)) is finite and related to the time difference t-s, but neither t nor s Expected value of random variable x, i.e. E[x(t)], is independent of time t Variance Var(x(t)) is a time-independent positive and finite constant Covariance Cov(x(t),x(s)) is finite and related to the time difference t-s, but neither t nor s Usually, x(t) is regarded as the logarithmic price return (or differences), not the price level. If a time series becomes stationary after first differencing, it is so called integrated of order one I(1). Although stock prices could also be mean-reverting, they rarely oscillate, i.e. they are trended and non-stationary (random walk) due to mixed effects of continuous economic drivers and market activities. Therefore, some people may profit from directional bets, but this is not our focus. What we actually want is to find a pair of stocks which the price differences or spreads are consistently stationary (and cointegrated). I have extracted 1-minute prices from 2018–01–01 to 2018–07–30 for 21 US stocks. All prices are saved in STATICS/PRICE in .csv format. Let’s take the first 70% of the time series and do some analyses. Pearson Correlation Here we calculate the price (not return) correlations. The highest correlations sit on PEP, PG, JNJ, and KO. From the economical perspective, they should be grouped into two pairs: JNJ-PG and KO-PEP. Note that high correlation does not necessarily imply cointegration. See the detail below. Marginal Distribution If we look into the their marginal distributions, the linear relationship should be somewhat recognized. We can also found some clusters as well which maybe useful but for the time being let’s avoid further data mining which is not our main focus. Price Charts Let’s create a function to plot the prices and spreads for a sample period. Prices are re-based to 1 at the beginning of the sample. Note that the 2nd subplot will depict the trading range specified by a symmetric trade threshold (th) and stop_loss (stop): Cointegration Test The following codes calculate the p-value for the cointegration test, and the null hypothesis is no cointegration. So if the p-value is small, the probability of observing a cointegrated relationship should be relatively high. Note that the test below is for the whole time series. During the training we should test and trade based on selected samples. The following results show that, even their correlations are comparable, the probabilities of finding a cointegrated relationship are very different. Sometimes we could find a correlated but not cointegrated price relationship. For example, if two stock prices go up together over time, they are positively correlated. However, if these two stocks trend up in different speeds, the price spread will keep growing rather than oscillating at the equilibrium and hence is non-stationary. Let me illustrate this point with an experiment. The code below simulates two highly correlated stock prices by Geometric Brownian Motion (GBM) and Cholesky Decomposition, each contains 1,000 samples. As you can see, although the correlations are high, the p-value is very large. Let’s plot these time series: The spread as shown in the bottom sub-plot is trending rather than mean-reverting. Engle and Granger (1987) defines a two-step identification: The elements of the cointegrated time series should have the same integration orderTheir linear combination should yield a variable with a lower integration order The elements of the cointegrated time series should have the same integration order Their linear combination should yield a variable with a lower integration order In our case, cointegration exists in stochastic trend components when more than one I(1) non-stationary and exogenous variables (so that they are theoretically independent to each other) exactly offset each other, giving a stationary linear combination and a long-run equilibrium. More specifically, two I(1) logarithmic stock prices x(1,t) and x(2,t) are cointegrated if a cointegration coefficient b exists, giving a stationary time series y(t) (i.e. I(0)): where a is simply a constant, and y(t) is our target trading spread. Apparently, we can simply use the ordinary least squares (OLS) method to estimate the spread and the coefficient b which is the hedge ratio by regressing x(1,t) against x(2,t). The original idea was based on the Granger representation theorem and represented in form of an error-correction model (ECM). However, based on an idea in Stock (1987) called super-consistency, the OLS estimator is easier to implement and expected to have a better performance in estimating cointegrated relationship due to the faster convergence to the true regression coefficient. The most common approach to test for cointegration is to check whether the residuals from the above regression are stationary by using Dickey Fuller (DF) or Augmented Dickey Fuller (ADF) test for unit root. Unit Root and Dickey-Fuller (DF) Test Unit root is a characteristic of random process. Consider a process with autoregression in order 1 (an AR(1) process): e(t) is a white noise and 0 < c ≤ 1. If the process is non-stationary nor purely random, then the hypothetical value of c is equal to 1 (i.e. the root of the equation is 1 and thus the process is I(1)). For instance, this could imply that the price today equals the price yesterday plus a random value. Dickey and Fuller (1979) shows that the t-statistics in this case does not follow a t-distribution, so the testing is inconsistent. To solve this problem we can change model above to: and test the null hypothesis of (c-1)=0. This is the so-called Dickey-Fuller test. We may also add an intercept or trend term and test for the null hypothesis that the their coefficients equal to zero, depending on the assumption. Augmented Dickey-Fuller (ADF) Test If we expand the autoregression process into an order of p (i.e. AR(p)): then we can apply the Augmented Dickey-Fuller test with this formulation: and test the null hypothesis of: In section 2.3 we have already seen the strategy class EGCointegration and the implementation is consistent with the above explanation. Note that the testing here is based on statsmodels.tsa.stattools.coint, and there is another function statsmodels.tsa.stattools.adfuller in the same library that is used to unit root testing. The difference is that: coint is effectively the Engle-Granger two-step cointegration test. It tests for the residuals of an estimated cointegrating pairs (2 time series inputs) with I(1), while adfuller tests the unit roots of a univariate process (1 time series input) In most cases the two tests should yield the same conclusion, but coint is more intuitive for our implementation. I benefited a lot from this series and took some ideas during the development of the code. Definitely recommend. The fundamental of reinforcement learning consists of two main components: agent and environment. The environment is represented by different states with a predefined state space, while the agent learns a policy determining what actions to perform out of the action space. In a full reinforcement learning problem, the learning cycle of an agent could be summarized into the following phases: make observations of the environment stateperform action accordingly based on the existing policyreceive the corresponding reward attributed to the action performedupdate the policy make observations of the environment state perform action accordingly based on the existing policy receive the corresponding reward attributed to the action performed update the policy As an example, imagine a puppy (agent) is learning how to react to his master’s commands (environment). It is a lazy dog that only knows how to perform the following actions: a. Sit b. Stand c. Do nothing In order to train the puppy his master keeps giving him a set of orders (states) regularly, including “sit”, “stand”, and “jump”. If he reacts correctly, his master will give him some dog food (reward). At the beginning, the puppy does not really understand what his master wants i.e. he has no idea (policy) how to “map” the orders properly to the desired actions. However, occasionally he could react in the right way and get the reward, and gradually build the connection between them (update the policy). After many trials he finally knows that he should sit/stand whenever he hears the word “sit” or “stand”. But no matter how many times his master asks him to “jump”, he completely does not know what to do. He tried a few times to sit or stand in this case, but could not get any reward. Eventually the puppy chooses c. Do nothing for the “jump” command because compared with other actions, this option is much less exhausting (so less negative reward). Reinforcement Learning v.s. Supervised Learning In supervised learning, the algorithm learns from instructions. Every instance has an estimation target to compare in order to calculate the cost of discrepancy, and the algorithm is updated by minimising the cost through iteration, so the process is somewhat “instructed” by the target output which tells what is the correct outcome. However, in reinforcement learning, the policy is learned by evaluations. There is no such absolute target in the samples to compare with. The agent could only learn by evaluating the feedback continuously, i.e. it keeps picking an action and evaluating the corresponding rewards in order to adjust the policies, retaining the most desirable outcomes. Therefore, the process flow is much more complicated. When we apply reinforcement learning in trading, we need to ask ourselves what exactly the agent is learning to perform, and be careful in defining the elements especially the state and action spaces. N-Armed Bandit Question: In the above picture, there is a 2-armed slot machine. Which arm is the best to pull in order to maximize our reward? Answer: The Right Arm since the expected reward is greater than pulling the Left Arm’s. But how does a machine learn to solve this puzzle? From the perspective of RL, this is the simplest setting in RL problem, and the task above could be summarized by the following spaces: State space: None Action space: [Left] or [Right] Reward: [1] or [0] In the training process, the RL algorithm will repeat the task above (pulling the arm) and evaluate the rewards obtained and update it’s policy recursively. Eventually, by evaluating the policy weights it should be able to give a conclusion of which arm is the best to pull. See a better explanation in this post. Contextual Bandit The contextual bandit problem is an expansion of the n-armed bandit. As shown in the picture above, given that there is not only 1 but 3 slot machines, we need to consider that for a particular machine (state) which arm is the best to pull. Now the setting becomes: State space: [Machine A], [Machine B], [Machine C] Action space: [Left] or [Right] Reward: [1] or [0] What exactly we would like the machine to learn to perform? Following the idea of For each pair of time series, it learns to maximize the expected trading profit [reward] by selecting the best combination of historical window, trading window, trade threshold, and stop lost [action]. In other words, we formulate it as an N-Armed Bandit problem (stateless): State space: [None] (Fixed by a dummy state — transaction_cost) Action space: [historical window], [trading window], [trading threshold], [stop loss], [confidence level] Reward: [mean return] Now we are good to go. Here are the implementation: Load relevant configs and price dataStandardize and separate them into training and testing setsCreate the state space and action spaceCreate and build the networkCreate the learning object and perform the trainingExtract the record from the learning object and perform testing analysis Load relevant configs and price data Standardize and separate them into training and testing sets Create the state space and action space Create and build the network Create the learning object and perform the training Extract the record from the learning object and perform testing analysis Pair: JNJ-PGData period: 2018–01–01 to 2018–07–30Frequency: 1-minuteStates: None (fixed by setting it to the fixed transaction cost of 0.1%)Actions: — i. Historical window: 60 to 600 minutes, 60-minute step — ii. Trade window: 120 to 1200 minutes, 120-minute step — iii. Trade threshold: (+/-)1 to 5, price step is 1 — iv. Stop loss: (+/-)1 to 2 on top of trade threshold, price step is 0.5 — v. Confidence level: 90% or 95%Profit taking level: 0Reward: mean return (if it is cointegrated, otherwise it is set to the transaction cost)Trade quantity: 1 spread per buy / sell signalCalibration prices: standardizedTrading prices: actualOthers: assume trading at closing price After a trial run I found that the probability output for Boltzmann exploration could go up to 1. To mitigate the impact of extraordinarily high returns the mean reward is capped at 10. From the training result the mean reward is positive despite it is capped: The following test trade across every minute using the optimal action obtained from the training result, excluding the maximum possible historical window and trading window: Alternatively, we can also use Zipline and Pyfolio for more sophisticated back-testing. Although the result seems promising, in the real world the situation is complicated by numerous factors such as bid-ask spread, delay in execution, margin, interest, fractional shares etc. However, our objective here is to give an example of how to combine various techniques in developing a systematical trading tool with a structured machine learning components. I hope this is an enjoyable page to you. The execution is governed by the config (dictionary). This component allows us to encapsulate a lot of executions and tidy up the code. It can also be used as a carrier of additional parameters. For instance, in the previous section, the instantiation of API.Tiingo takes the config as an input set it to an attribute. When it calls the underlying functions, the input parameters such as start date, end date, token, no. of sample per day and data frequency will be extracted from the config. Currently only a single config is implemented. Ideally, we should implement multiple configs for different components. Using the PyYAML package the code can recognize the fields in .yaml /.yml file and convert the format automatically: - Empty field: loaded into None- True/False: loaded into Boolean field True or False- 1.0: loaded into float 1.0- 1: loaded into integer 1- string: loaded into ‘string’- [1, 2, 3]: loaded into list [1, 2, 3]- 2018–01–01: loaded into datetime.date(2018, 1, 30)- Finally, if we put this into the yaml file: Folder: Folder A: Math Notes Folder B: [Memo, Magazines] the package can recognize the indentation and load it into a dictionary: {'Folder A': 'Math Notes', 'Folder B': ['Memo', 'Magazines']} Check the UTIL/FileIO.py for the reading and writing functions: For this we have already covered the main detail so I am gonna skip this. If you would like to add another API I would suggest you to simply make another class, with the same interface as fetch in the class Tiingo. In ./STRATEGY each module contains a strategy category, each strategy should be represented by one class. The class is inherited from an abstract base class which requires it to implement the following: process(): called by the machine learning script during training or testingreward: properties that define the RL reward (i.e. trade profit)record: any other attributes to be stored during the training process(): called by the machine learning script during training or testing reward: properties that define the RL reward (i.e. trade profit) record: any other attributes to be stored during the training Inside the package we can find a strategy class EGCointegration which takes price data x and y and other parameters during the instantiation. When the underlying functions need a sample data set, they will call the get_sample function to perform the sampling from its data attributes. During the training phase, in each iteration we will need to calibrate the p-value and coefficients to decide whether and how a pair trading should be triggered. These executions are embedded in the same class. when the process is called, the object will automatically perform the sampling from its data attributes and run the calibration. Based on the calibrated result the function will get a reward and record and set them to the corresponding attributes. See more about cointegration and its testing in Part 3. These components are highly integrated and governed not only by the config but also the tailor-made agent which control the whole ML process which is highly automated. Many ML algorithms were hard-coded. That means if the logic needs to be fine tuned, the code has to be amended which is a bit inconvenient. Here, although the design is a bit complicated, if you can understand the style you will be able to expand it in any way you want. Recently, Google has released an open-source library for reinforcement learning (RL) called TF-Agents. Feel free to check this out. Some concepts are similar, but the main focus of our code is on the automation so you may use that as a foundation if you would like to build a new one. 2.4.1 Basic Building Blocks Agent It is the main body that runs and control the processes in ML. In RL, it has another layer of implication: in general it is the component that receives the states of the environment and makes decision on what action to take accordingly. The Agent class is meant to be inherited by the machine learning class. It should be initiated with a Network object and a config dictionary. Major functions include: - docking: attach the Network input and output layers- assign_network: assign new Network to the Agent object and connect - set_session: set TensorFlow - get_counter: extract the parameters from config and get a dictionary of StepCounter objects for looping or increments such as varying probability- save_model / restore_model: save and restore model in / from .ckpt file- process: abstract method to be implemented for training or testing Network A typical way of building a TensorFlow neural network is something like this inside which the layers and the parameters in each of them are hard-coded: Alternatively we could also build a function that repeats the above process, forfeiting the flexibility in setting the layer arguments. If you want to build a ML system or something with GUI with flexibility in customizing the detail for each layer (i.e. layer type, layer inputs, layer arguments) while preserving the automaticity, here comes a suggestion: The two functions on the left are under the class Network. build_layers: it takes a dictionary layer_dict as an input and construct the network by sequentially adding layers selected from the TFLayer class as shown on the right hand side. As long as for each layer the parameters are properly defined, this function can be called recursively to add layers on top of the existing final layer in the current network. Every layer is set to the attribute of the Network object so their name must be unique.add_layer_duplicates: similar to build_layers, it takes a layer_dict as an input, and require an input of n_copy which specify how many copies of the layer(s) prescribed by the layer_dict should be added on top of the existing network. New names will be created for the duplicated layers by concatenating the layer name and the number of that layer among the copies. build_layers: it takes a dictionary layer_dict as an input and construct the network by sequentially adding layers selected from the TFLayer class as shown on the right hand side. As long as for each layer the parameters are properly defined, this function can be called recursively to add layers on top of the existing final layer in the current network. Every layer is set to the attribute of the Network object so their name must be unique. add_layer_duplicates: similar to build_layers, it takes a layer_dict as an input, and require an input of n_copy which specify how many copies of the layer(s) prescribed by the layer_dict should be added on top of the existing network. New names will be created for the duplicated layers by concatenating the layer name and the number of that layer among the copies. For example: The steps to create a network: Initiate an Network object. This has to be instantiated by the first input layer which is the tf.placeholder in this example.Build the network based on layer_dict1. It specifies 2 layers: an ‘one_hot’ layer which is actually tf.one_hot with 5 outputs, and a ‘coint1’ layer which is tf.contrib.layers.fully_connected with 10 outputs. The input arguments of the tf.contrib.layers.fully_connected are defined by the key ‘layer_para’.Expand the network by adding copies of layer prescribed by layer_dict2. The layer ‘coint2’ with 10 outputs is added to the current network for 3 times. Initiate an Network object. This has to be instantiated by the first input layer which is the tf.placeholder in this example. Build the network based on layer_dict1. It specifies 2 layers: an ‘one_hot’ layer which is actually tf.one_hot with 5 outputs, and a ‘coint1’ layer which is tf.contrib.layers.fully_connected with 10 outputs. The input arguments of the tf.contrib.layers.fully_connected are defined by the key ‘layer_para’. Expand the network by adding copies of layer prescribed by layer_dict2. The layer ‘coint2’ with 10 outputs is added to the current network for 3 times. Therefore, the Network object N now should have 6 attributes in total. Each of them is a layer with predefined properties: Since the construction of the network is based on the layer dictionary, automation comes into ply if the generation of such dictionary is streamlined, and we no longer need to hard code the network every time when we build something new. Space Basically it refers to a sample space object. It takes a dictionary of list as an input and create the sample space by making full combinations across list elements. For example, for the following sample space: space_dict = {'dice': [1, 2, 3, 4, 5, 6], 'coin': ['H', 'T']}S = Space.states_dict S contains all combinations of ‘dice’ and ‘coin’, 12 elements in total. It contains the necessary functions that convert the sample from dictionary to a single index, list of indices, or one_hot array and vice versa that could fit the purpose of adapting different kind of input or output carriers in TensorFlow. StepCounter During training, some parameters are incremental such as the current step in for loop, or the learning rate is set to be variable. We may even want to add a buffer before the actual step is triggered (i.e. the learning rate start to drop after 100 loops). Instead of hard coding these in the script, we can have a step counter to perform the above. The counter also incorporates the ability to buffer pre-train steps. For example, the actual counting value starts to change only after 100 buffering steps. 2.4.2 Processors A Processor class should take an Agent object as an input for initiation. When the process is called it will extract relevant parameters from the Agent object, including the attached config dictionary, and attach any output to the data dictionary which is an attribute of the Agent. We can actually create another object to carry these attributes but for simplicity let’s not overload the structure in here. State Space and Action Space Both of them inherit the parent class Space and are used to generate state samples or action samples. Based on the method specified in config they can output the samples in different forms (i.e. index/one hot/dictionary) or different ways (with/without exploration) serving different purposes such as network training or taken as the input of the process function in the Strategy object. Reward Engine It takes an engine object which contain a process methods. In our example it will be an EGCointegration object. Exploration This article gives a very good introduction to the exploration methods in reinforcement learning. The purpose of this object is to explore possible actions. The selected method will return an action index to the data carrier in the Agent object. The exploration is implemented when the process function in the ActionSpace is called. Experience Buffer This leverages the Experience Replay implementation in this article. The purpose is to store the samples and results along the training process, and re-sample from the buffer to allow the agent to re-learn from the history. Recorder Last but not least, I created a Recorder class which can be used to keep track of the records stored in the data dictionary inside the Agent object. We can select the field we would like it to store by specifying the key names in the RecorderDataField field in the config file: RecorderDataField: [NETWORK_ACTION, ENGINE_REWARD] 2.4.3 ML Algorithms With the components described above, we can tailor make any class that takes these building blocks and create a running procedure. This is the only part that needs to be customized for different purpose, but still the logic is pretty standardized for similar cases. For example, in this project I have created a ContextualBandit class which can actually perform either N-Armed bandit or contextual bandit running, subject to the number of state. If we would like to run it for N-Armed bandit problem we could just specify a state space with a single fixed state (dummy). __init__: initiates the object and inherits the parent methods and properties. The TensorFlow machine learning attributes are defined in here as well. After all the processors described above will be instantiated by composition, taking the object itself as an input argument (agent).update_network: extracts the samples from data dictionary and update the TensorFlow layers and network.buffering: store the sample in the ExperienceBuffer object if specified in the config.create_sample_list: create samples for experience buffering.process: the main procedure that controls the flow of the training or testing. It takes a tf.Session() and perform the looping based on the values in the StepCounter objects initiated by the Agent. __init__: initiates the object and inherits the parent methods and properties. The TensorFlow machine learning attributes are defined in here as well. After all the processors described above will be instantiated by composition, taking the object itself as an input argument (agent). update_network: extracts the samples from data dictionary and update the TensorFlow layers and network. buffering: store the sample in the ExperienceBuffer object if specified in the config. create_sample_list: create samples for experience buffering. process: the main procedure that controls the flow of the training or testing. It takes a tf.Session() and perform the looping based on the values in the StepCounter objects initiated by the Agent. This article and the relevant codes and content are purely informative and none of the information provided constitutes any recommendation regarding any security, transaction or investment strategy for any specific person. The implementation described in this article could be risky and the market condition could be volatile and differ from the period covered above. All trading strategies and tools are implemented at the users’ own risk. [1] Dickey, D. A., Fuller, W. A., Distribution of the estimators for autoregressive time series with a unit root (1979), Journal of the American Statistical Association. 74(366): 427–431. [2] Engle, R.F., Granger, C.W.J., Co-integration and error correction: representation, estimation, and testing (1987), Econometrica 55(2): 251–276 [3] Gatev, E., Goetzmann, W.N., and Rouwenhorst, K.G., Pairs trading: performance of a relative-value arbitrage rule (2006), The Review of Financial Studies 19(3): 797–827 [4] Granger, C.W., Some properties of time series data and their use in econometric model specification (1981), Journal of Economics 16(1): 121–130 [5] Johansen, S., Statistical analysis of cointegration vectors (1988), Journal of Economic Dynamics and Control 12(2–3): 231–254 [6] Krauss, C., Statistical arbitrage pairs trading strategies: review and outlook (2017), Journal of Economics Surveys 31(2): 513–545 [7] Stock, J.H., Asymptotic properties of least squares estimators of cointegrating vectors (1987), Econometrica 55: 277–302. [8] Sutton, R.S., Barto, A.G., Reinforcement Learning: An Introduction (1998), The MIT Press, Second Edition
[ { "code": null, "e": 501, "s": 171, "text": "This covers topics from concepts to implementation of RL in cointegration pair trading based on 1-minute stock market data. For the Reinforcement Learning here we use the N-armed bandit approach. The code is expandable so you can plug any strategies, data...
Tryit Editor v3.7
Tryit: HTML table headers
[]
C/C++ Program for Maximum height when coins are arranged in a triangle?
In this section, we will see one interesting problem. There are N coins. we have to find what is the max height we can make if we arrange the coins as pyramid. In this fashion, the first row will hold 1 coin, second will hold 2 coins and so on. In the given diagram, we can see to make a pyramid of height three we need minimum 6 coins. We cannot make height 4 until we have 10 coins. Now let us see how to check the maximum height. We can get the height by using this formula. Live Demo #include<iostream> #include<cmath> using namespace std; int getMaxHeight(int n) { int height = (-1 + sqrt(1 + 8 * n)) / 2; return height; } main() { int N; cout << "Enter number of coins: " ; cin >> N; cout << "Height of pyramid: " << getMaxHeight(N); } Enter number of coins: 13 Height of pyramid: 4
[ { "code": null, "e": 1307, "s": 1062, "text": "In this section, we will see one interesting problem. There are N coins. we have to find what is the max height we can make if we arrange the coins as pyramid. In this fashion, the first row will hold 1 coin, second will hold 2 coins and so on." }, ...
Java Regex - Example - Character \\ Match
The character \\ matches the backslash character present in a text. The following example shows the usage of character matching. package com.tutorialspoint; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CharactersDemo { private static final String REGEX = "\\"; private static final String INPUT = "dbca\\bcabc"; public static void main(String[] args) { // create a pattern Pattern pattern = Pattern.compile(Pattern.quote(REGEX)); // get a matcher object Matcher matcher = pattern.matcher(INPUT); if(matcher.find()) { //Prints the start index of the match. System.out.println("Match String start(): "+matcher.start()); } } } Let us compile and run the above program, this will produce the following result − Match String start(): 4 Print Add Notes Bookmark this page
[ { "code": null, "e": 2192, "s": 2124, "text": "The character \\\\ matches the backslash character present in a text." }, { "code": null, "e": 2253, "s": 2192, "text": "The following example shows the usage of character matching." }, { "code": null, "e": 2858, "s":...
Boolean Indexing in Pandas
Boolean indexing helps us to select the data from the DataFrames using a boolean vector. We need a DataFrame with a boolean index to use the boolean indexing. Let's see how to achieve the boolean indexing. Create a dictionary of data. Convert it into a DataFrame object with a boolean index as a vector. Now, access the data using boolean indexing. See the example below to get an idea. import pandas as pd # data data = { 'Name': ['Hafeez', 'Srikanth', 'Rakesh'], 'Age': [19, 20, 19] } # creating a DataFrame with boolean index vector data_frame = pd.DataFrame(data, index = [True, False, True]) print(data_frame) If you run the above program, you will get the following results. Name Age True Hafeez 19 False Srikanth 20 True Rakesh 19 Now, we can access the DataFrame by passing booleans to the methods loc[], iloc[], ix[]. Let's see them all. # accessing using .loc() print(data_frame.loc[True]) If run the above code, you will get the following results. Name Age True Hafeez 19 True Rakesh 19 # accessing using .iloc() print(data_frame.iloc[1]) # iloc methods takes only integers so, we are passing 1 i nsted of True. Both are same. If run the above code, you will get the following results. Name Srikanth Age 20 dtype: object # accessing using .ix[] # we can pass both boolean or integer values to .ix[] print(data_frame.ix[True]) print() print(data_frame.ix[1]) If run the above code, you will get the following results. Name Age True Hafeez 19 True Rakesh 19 Name Srikanth Age 20 dtype: object Another way to use the boolean index is to directly pass the boolean vector to the DataFrame. It will print all the rows with the value True. Let's see one example. import pandas as pd # data data = { 'Name': ['Hafeez', 'Srikanth', 'Rakesh'], 'Age': [19, 20, 19] } # creating a DataFrame with boolean index vector data_frame = pd.DataFrame(data) print(data_frame) If run the above code, you will get the following results. Name Age 0 Hafeez 19 1 Srikanth 20 2 Rakesh 19 Now, we can pass the boolean vector to the DataFrame to access the data. # passing boolean vector to data_frame index print(data_frame[[True, True, False]]) If run the above code, you will get the following results. We got the row only that is True. Name Age 0 Hafeez 19 1 Srikanth 20 If you have any doubts about the Boolean index, let me know in the comment section.
[ { "code": null, "e": 1268, "s": 1062, "text": "Boolean indexing helps us to select the data from the DataFrames using a boolean vector. We need a DataFrame with a boolean index to use the boolean indexing. Let's see how to achieve the boolean indexing." }, { "code": null, "e": 1297, ...
Maximum average subarray | Practice | GeeksforGeeks
Given an array Arr of size N and a positive integer K, find the sub-array of length K with the maximum average. Example 1: Input: K = 4, N = 6 Arr[] = {1, 12, -5, -6, 50, 3} Output: 12 -5 -6 50 Explanation: Maximum average is (12 - 5 - 6 + 50)/4 = 51/4. Example 2: Input: K = 3, N = 7 Arr[] = {3, -435, 335, 10, -50, 100, 20} Output: 335 10 -50 Explanation: Maximum average is (335 + 10 - 50)/3 = 295/3. Your Task: You don't need to read input or print anything. Your task is to complete the function findMaxAverage() which takes the array of integers arr, its size n and integer k as input parameters and returns an integer denoting the starting index of the subarray. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints 1 <= N <= 105 0 <= |Arr[i]| <= 103 0 avinashdhn19041 week ago // simple solution using sliding window int findMaxAverage(int arr[], int n, int k) { int sum=0; for(int i=0;i<k;i++)sum+=arr[i]; int mx=sum; pair<int,int>p={0,k-1}; for(int i=0;i<n-k;i++){ sum-=arr[i]; sum+=arr[k+i]; if(sum>mx){ mx=sum; p={i+1,k+i}; } } return p.first; } +1 dronzerdracel3 weeks ago Sliding window|C++ int i=0,j=0,sum=0,maxm=INT_MIN,pos=-1; while(j<n){ sum+=arr[j]; if(j-i+1==k){ if(sum>maxm){ maxm=sum; pos=i; } sum-=arr[i]; i++; } j++; } return pos; 0 srisai22601 month ago PYTHON SOLUTION: class Solution: def findMaxAverage(self, arr, n, k): sum=0 idx=0 maxsum=0 for i in range(k): sum+=arr[i] maxsum=sum for j in range(k,n): sum+=arr[j]-arr[j-k] if sum > maxsum: maxsum = sum idx = j-k+1 return idx 0 vainalavinayvvk0981 month ago class Solution: def findMaxAverage(self, arr, n, k): # code here maxsum = -99999999999999 index = 0 first = 0 summ = sum(arr[:k]) if summ>maxsum: summ = maxsum index = k-1 for i in range(k,n): summ+=arr[i] summ-=arr[first] first += 1 if summ >maxsum: maxsum = summ index = i #print(summ,index) return index-k+1 +1 bahubuli1 month ago int findMaxAverage(int arr[], int n, int k) { double ans =INT_MIN,sum=0; int idx,j=0; for(int i=0;i<n;i++) { if(i<k-1) sum+=arr[i]; else { sum+=arr[i]; if((sum/k)>ans) { idx = i+1-k; ans = sum/k; } sum-=arr[j]; j++; } } return idx; } +4 subha_nik1 month ago C++ Solution: Sliding window technique Code: class Solution{ public: int findMaxAverage(int arr[], int n, int k) { int idx = 0, sum = 0, maxsum = 0; for(int i=0; i<k; i++) sum += arr[i]; maxsum = sum; for(int i=k; i<n; i++) { sum += arr[i]-arr[i-k]; if(sum > maxsum) { maxsum = sum; idx = i-k+1; } } return idx; } }; 0 strsatyam1 month ago //using sliding window int findMaxAverage(int arr[], int n, int k) { if(n<k) return 0; int t =0; for(int i=0;i<k;i++){ t+=arr[i]; } int ans=t; int idx=0; for(int j=k;j<n;j++){ t+=arr[j]; t-=arr[j-k]; if(t>=ans){ ans=t; idx=j-k+1; } } return idx; } 0 akashmr10961 month ago int findMaxAverage(int[] arr, int n, int k) { int sum = 0; for (int i=0; i<k; i++) { sum += arr[i]; } int maxSum = sum; int index = 0; for (int i=k; i<n; i++) { sum -= arr[i-k]; sum += arr[i]; if (sum > maxSum) { index = i-k+1; maxSum = sum; } } return index; } +1 triple2double11 month ago NOOB SOLUTION int findMaxAverage(int arr[], int n, int k) { if(n<k) return 0; int sum =0; for(int i=0;i<k;i++){ sum+=arr[i]; } int ans=sum; int idx=0; for(int j=k;j<n;j++){ sum+=arr[j]-arr[j-k]; if(sum>=ans){ ans=sum; idx=j-k+1; } } return idx; } +3 tandava12341 month ago //SIMPLE C++ CODE int findMaxAverage(int arr[], int n, int k) { // code here vector<int> v; int sum=0; for(int i=0;i<k;i++) { sum+=arr[i]; } int inx=0,val=sum; for(int i=k;i<n;i++) { sum=sum+arr[i]-arr[i-k]; if(val<sum) { val=sum; inx=i-k+1; } } return inx; } 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": 351, "s": 238, "text": "Given an array Arr of size N and a positive integer K, find the sub-array of length K with the maximum average. " }, { "code": null, "e": 363, "s": 351, "text": "\nExample 1:" }, { "code": null, "e": 495, "s": 363, ...
Finding sum of digits of a number until sum becomes single digit in C++
In this tutorial, we are going to write a program that sums digits of the given number until it becomes a single digit. Let's see an example. Input −4543 Output −7 Let's see the steps to solve the problem. Initialize a number. Initialize a number. Initialize the sum to 0. Initialize the sum to 0. Iterate until the sum is less than 9.Add each digit of the number to the sum using modulo operator Iterate until the sum is less than 9. Add each digit of the number to the sum using modulo operator Add each digit of the number to the sum using modulo operator Print the sum Print the sum Let's see the code. Live Demo #include <bits/stdc++.h> using namespace std; void findTheSingleDigit(int n) { int sum = 0; while(n > 0 || sum > 9) { if(n == 0) { n = sum; sum = 0; } sum += n % 10; n /= 10; } cout << sum << endl; } int main() { int n = 4543; findTheSingleDigit(n); return 0; } you execute the above program, then you will get the following result. 7 We have another simple method to solve the problem. If the given number is divisible by 9, then the answer is 9. Else the number if n % 9. Let's see the code. Live Demo #include <bits/stdc++.h> using namespace std; void findTheSingleDigit(int n) { if (n == 0) { cout << 0; } else if (n % 9 == 0) { cout << 9 << endl; } else { cout << n % 9 << endl; } } int main() { int n = 4543; findTheSingleDigit(n); return 0; } If you run the above code, then you will get the following result. 7 If you have any queries in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1204, "s": 1062, "text": "In this tutorial, we are going to write a program that sums digits of the given number until it becomes a single digit. Let's see an example." }, { "code": null, "e": 1216, "s": 1204, "text": "Input −4543" }, { "code": null, ...
Java Program to create a new list with values from existing list with Lambda Expressions
To create a new list with values from existing list with Lambda Expressions, the following is an example. Here, we are displaying the name of Employees. Therefore, we have created an Employee class as well − List<Employee>emp = Arrays.asList(new Employee("Jack", 29, "South"), new Employee("Tom", 24, "North"), new Employee("Harry", 35, "West"),new Employee("Katie", 32, "East")); Use Lambda to crate anew list from existing list with Lambda Expressions − List<String>res = emp.stream().map(u ->u.displayEmpName()).collect(Collectors.toList()); Let us see the complete example − Live Demo import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; public class Demo { public static void main(String args[]) { List<Employee>emp = Arrays.asList(new Employee("Jack", 29, "South"), new Employee("Tom", 24, "North"), new Employee("Harry", 35, "West"),new Employee("Katie", 32, "East")); List<String>res = emp.stream().map(u ->u.displayEmpName()).collect(Collectors.toList()); System.out.println("Employee Names = "+res); } } class Employee { private String emp_name; private int emp_age; private String emp_zone; public Employee(String emp_name, int emp_age, String emp_zone) { this.emp_name = emp_name; this.emp_age = emp_age; this.emp_zone = emp_zone; } public String displayEmpName() { return this.emp_name; } } Employee Names = [Jack, Tom, Harry, Katie]
[ { "code": null, "e": 1168, "s": 1062, "text": "To create a new list with values from existing list with Lambda Expressions, the following is an example." }, { "code": null, "e": 1270, "s": 1168, "text": "Here, we are displaying the name of Employees. Therefore, we have created an...
D3.js selection.filter() Function - GeeksforGeeks
19 Aug, 2020 The d3.selection.filter() function in d3.js is used to filter the given selection and return a new selection for which the filter is true. The filter to be used may be a string or a function. Syntax: selection.filter(filter); Parameters: This function accepts one parameter as mentioned above and described below: filter: It is a string or a function that would be used to filter a selection. The filter is applied to each selected element when using a function. Return Values: This function returns the new selection. Example 1: This example selects all the odd children of the specified element. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width,initial-scale=1.0"> <script src= "https://d3js.org/d3.v4.min.js"> </script> <script src= "https://d3js.org/d3-selection.v1.min.js"> </script></head> <body> <div> <b>1. This text is in bold</b> <b>2. This text is also in bold</b> <b>3. Geeks for geeks</b> <b>4. Geeks for geeks</b> <b>5. Geeks for geeks</b> </div> <script> let selection = d3.selectAll("b") .filter(":nth-child(odd)") .nodes(); selection.forEach((e) => { console.log(e.textContent) }) </script></body> </html> Output: Example 2: This example selects all the even children of the specified element. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width,initial-scale=1.0"> <script src= "https://d3js.org/d3.v4.min.js"> </script> <script src= "https://d3js.org/d3-selection.v1.min.js"> </script></head> <body> <div> <b>1. This text is in bold</b> <b>2. This text is also in bold</b> <b>3. Geeks</b> <b>4. Geeks</b> <b>5. Geeks for geeks</b> </div> <script> let selection = d3.selectAll("b") .filter(":nth-child(even)") .nodes(); selection.forEach((e) => { console.log(e.textContent) }) </script></body> </html> Output: Example 3: This example uses selection.selectAll as a filter. HTML <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <script src= "https://d3js.org/d3.v4.min.js"> </script> <script src= "https://d3js.org/d3-selection.v1.min.js"> </script></head> <body> <div> <h3>1. This text is in bold</h3> <h3>2. This text is also in bold</h3> <h3>3. Geeks</h3> <h3>4. Geeks</h3> <h3>5. Geeks for geeks</h3> </div> <script> // Using selection.selectAll with filter let selection = d3.selectAll("div") .selectAll("h3") .filter(":nth-child(even)") .nodes(); selection.forEach((e) => { console.log(e.textContent) }) </script></body> </html> Output: D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request Remove elements from a JavaScript Array How to get character array from string in JavaScript? How to get selected value in dropdown list using JavaScript ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24909, "s": 24881, "text": "\n19 Aug, 2020" }, { "code": null, "e": 25101, "s": 24909, "text": "The d3.selection.filter() function in d3.js is used to filter the given selection and return a new selection for which the filter is true. The filter to be used ma...
Print all possible N-nodes Full Binary Trees - GeeksforGeeks
06 Oct, 2021 Given an integer N, the task is to print all possible Full Binary Trees with N nodes. The value at the nodes does not contribute to be a criteria for different Full Binary Tree, except for NULL. Examples: Input: N = 7Output: [[0, 0, 0, null, null, 0, 0, null, null, 0, 0, null, null, null, null], [0, 0, 0, null, null, 0, 0, 0, 0, null, null, null, null, null, null], [0, 0, 0, 0, 0, null, null, null, null, 0, 0, null, null, null, null], [0, 0, 0, 0, 0, null, null, 0, 0, null, null, null, null, null, null], [0, 0, 0, 0, 0, 0, 0, null, null, null, null, null, null, null, null]]Explanation: The possible full binary trees are – 0 | 0 | 0 | 0 | 0 / \ | / \ | / \ | / \ | / \ 0 0 | 0 0 | 0 0 | 0 0 | 0 0 / \ | / \ | / \ | / \ | / \ / \ 0 0 | 0 0 | 0 0 | 0 0 | 0 0 0 0 / \ | / \ | / \ | / \ | 0 0 | 0 0 | 0 0 | 0 0 | Input: N = 5Output: [[0, 0, 0, null, null, 0, 0, null, null, null, null],[0, 0, 0, 0, 0, null, null, null, null, null, null]] Approach: The simplest way to solve the problem is to use recursion and check for each subtree if there is a odd number of nodes or not because a full binary tree has odd nodes. Follow the steps below to solve the problem: Initialize a hashMap, say hm that stores all the Full Binary Tree. Create a function, say allPossibleBFT with the parameter as N by performing the following steps:Create a List, say list containing the class nodes.If N =1, then add nodes(0, NULL, NULL) in the list.Now check if N is odd, then Iterate in the range [0, N-1] using the variable x and perform the following steps:Initialize a variable, say y as N – 1 – x.Recursively call the function allPossibleBFT with x as the parameter and assign it to the node left.Recursively call the function allPossibleBFT with y as the parameter inside the above call and assign it to the node right.Now create a new Node with parameters as (0, NULL, NULL).Assign Node.left as left and Node.right as right.Add Node to the List.After performing the above steps, insert list in the hashMap hm. Create a List, say list containing the class nodes.If N =1, then add nodes(0, NULL, NULL) in the list.Now check if N is odd, then Iterate in the range [0, N-1] using the variable x and perform the following steps:Initialize a variable, say y as N – 1 – x.Recursively call the function allPossibleBFT with x as the parameter and assign it to the node left.Recursively call the function allPossibleBFT with y as the parameter inside the above call and assign it to the node right.Now create a new Node with parameters as (0, NULL, NULL).Assign Node.left as left and Node.right as right.Add Node to the List.After performing the above steps, insert list in the hashMap hm. Create a List, say list containing the class nodes. If N =1, then add nodes(0, NULL, NULL) in the list. Now check if N is odd, then Iterate in the range [0, N-1] using the variable x and perform the following steps:Initialize a variable, say y as N – 1 – x.Recursively call the function allPossibleBFT with x as the parameter and assign it to the node left.Recursively call the function allPossibleBFT with y as the parameter inside the above call and assign it to the node right.Now create a new Node with parameters as (0, NULL, NULL).Assign Node.left as left and Node.right as right.Add Node to the List. Initialize a variable, say y as N – 1 – x. Recursively call the function allPossibleBFT with x as the parameter and assign it to the node left.Recursively call the function allPossibleBFT with y as the parameter inside the above call and assign it to the node right.Now create a new Node with parameters as (0, NULL, NULL).Assign Node.left as left and Node.right as right.Add Node to the List. Recursively call the function allPossibleBFT with y as the parameter inside the above call and assign it to the node right.Now create a new Node with parameters as (0, NULL, NULL).Assign Node.left as left and Node.right as right.Add Node to the List. Recursively call the function allPossibleBFT with y as the parameter inside the above call and assign it to the node right. Now create a new Node with parameters as (0, NULL, NULL). Assign Node.left as left and Node.right as right. Add Node to the List. After performing the above steps, insert list in the hashMap hm. After performing all the steps, print the Full Binary Trees that are in the list. 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; // Class for creating node and// its left and right childstruct Node { Node* left; Node* right; int data; Node(int data, Node* left, Node* right) { this->data = data; this->left = left; this->right = right; }}; // Function to traverse the tree and add all// the left and right child in the list alvoid display(Node* node, vector<int> &al){ // If node = null then terminate the function if (node == nullptr) { return; } // If there is left child of Node node // then insert it into the list al if (node->left != nullptr) { al.push_back(node->left->data); } // Otherwise insert null in the list else { al.push_back(INT_MIN); } // Similarly, if there is right child // of Node node then insert it into // the list al if (node->right != nullptr) { al.push_back(node->right->data); } // Otherwise insert null else { al.push_back(INT_MIN); } // Recursively call the function // for left child and right child // of the Node node display(node->left, al); display(node->right, al);} // Save tree for all n before recursion.map<int, vector<Node*>> hm;vector<Node*> allPossibleFBT(int n){ // Check whether tree exists for given n value or not. if (hm.find(n) == hm.end()) { // Create a list containing nodes vector<Node*> list; // If N=1, Only one tree can exist // i.e. tree with root. if (n == 1) { list.push_back(new Node(0, nullptr, nullptr)); } // Check if N is odd because binary full // tree has N nodes else if (n % 2 == 1) { // Iterate through all the nodes that // can be in the left subtree for (int x = 0; x < n; x++) { // Remaining Nodes belongs to the // right subtree of the node int y = n - 1 - x; // Iterate through all left Full Binary Tree // by recursively calling the function vector<Node*> xallPossibleFBT = allPossibleFBT(x); vector<Node*> yallPossibleFBT = allPossibleFBT(y); for(int Left = 0; Left < xallPossibleFBT.size(); Left++) { // Iterate through all the right Full // Binary tree by recursively calling // the function for(int Right = 0; Right < yallPossibleFBT.size(); Right++) { // Create a new node Node* node = new Node(0, nullptr, nullptr); // Modify the left node node->left = xallPossibleFBT[Left]; // Modify the right node node->right = yallPossibleFBT[Right]; // Add the node in the list list.push_back(node); } } } } //Insert tree in Dictionary. hm.insert({n, list}); } return hm[n];} int main(){ // Given Input int n = 7; // Function Call vector<Node*> list = allPossibleFBT(n); // Print all possible binary full trees for(int root = 0; root < list.size(); root++) { vector<int> al; al.push_back((list[root])->data); display(list[root], al); cout << "["; for(int i = 0; i < al.size(); i++) { if(i != al.size() - 1) { if(al[i]==INT_MIN) cout << "null, "; else cout << al[i] << ", "; } else{ if(al[i]==INT_MIN) cout << "null]"; else cout << al[i] << "]"; } } cout << endl; } return 0;} // This code is contributed by decode2207. // JAVA program for the above approachimport java.util.*;import java.io.*; class GFG { // Class for creating node and // its left and right child public static class Node { int data; Node left; Node right; Node(int data, Node left, Node right) { this.data = data; this.left = left; this.right = right; } } // Function to traverse the tree and add all // the left and right child in the list al public static void display(Node node, List<Integer> al) { // If node = null then terminate the function if (node == null) { return; } // If there is left child of Node node // then insert it into the list al if (node.left != null) { al.add(node.left.data); } // Otherwise insert null in the list else { al.add(null); } // Similarly, if there is right child // of Node node then insert it into // the list al if (node.right != null) { al.add(node.right.data); } // Otherwise insert null else { al.add(null); } // Recursively call the function // for left child and right child // of the Node node display(node.left, al); display(node.right, al); } // Driver Code public static void main(String[] args) { // Given Input int n = 7; // Function Call List<Node> list = allPossibleFBT(n); // Print all possible binary full trees for (Node root: list) { List<Integer> al = new ArrayList<>(); al.add(root.data); display(root, al); System.out.println(al); } } // Save tree for all n before recursion. static HashMap<Integer, List<Node> > hm = new HashMap<>(); public static List<Node> allPossibleFBT(int n) { // Check whether tree exists for given n value or not. if (!hm.containsKey(n)) { // Create a list containing nodes List<Node> list = new LinkedList<>(); // If N=1, Only one tree can exist // i.e. tree with root. if (n == 1) { list.add(new Node(0, null, null)); } // Check if N is odd because binary full // tree has N nodes else if (n % 2 == 1) { // Iterate through all the nodes that // can be in the left subtree for (int x = 0; x < n; x++) { // Remaining Nodes belongs to the // right subtree of the node int y = n - 1 - x; // Iterate through all left Full Binary Tree // by recursively calling the function for (Node left: allPossibleFBT(x)) { // Iterate through all the right Full // Binary tree by recursively calling // the function for (Node right: allPossibleFBT(y)) { // Create a new node Node node = new Node(0, null, null); // Modify the left node node.left = left; // Modify the right node node.right = right; // Add the node in the list list.add(node); } } } } //Insert tree in HashMap. hm.put(n, list); } return hm.get(n); }} # Python3 program for the above approachimport sys # Class for creating node and# its left and right childclass Node: def __init__(self, data, left, right): self.data = data self.left = left self.right = right # Function to traverse the tree and add all# the left and right child in the list aldef display(node, al): # If node = null then terminate the function if (node == None): return # If there is left child of Node node # then insert it into the list al if (node.left != None): al.append(node.left.data) # Otherwise insert null in the list else: al.append(-sys.maxsize) # Similarly, if there is right child # of Node node then insert it into # the list al if (node.right != None): al.append(node.right.data) # Otherwise insert null else: al.append(-sys.maxsize) # Recursively call the function # for left child and right child # of the Node node display(node.left, al) display(node.right, al) # Save tree for all n before recursion.hm = {}def allPossibleFBT(n): # Check whether tree exists for given n value or not. if n not in hm: # Create a list containing nodes List = [] # If N=1, Only one tree can exist # i.e. tree with root. if (n == 1): List.append(Node(0, None, None)) # Check if N is odd because binary full # tree has N nodes elif (n % 2 == 1): # Iterate through all the nodes that # can be in the left subtree for x in range(n): # Remaining Nodes belongs to the # right subtree of the node y = n - 1 - x # Iterate through all left Full Binary Tree # by recursively calling the function xallPossibleFBT = allPossibleFBT(x) yallPossibleFBT = allPossibleFBT(y) for Left in range(len(xallPossibleFBT)): # Iterate through all the right Full # Binary tree by recursively calling # the function for Right in range(len(yallPossibleFBT)): # Create a new node node = Node(0, None, None) # Modify the left node node.left = xallPossibleFBT[Left] # Modify the right node node.right = yallPossibleFBT[Right] # Add the node in the list List.append(node) #Insert tree in Dictionary. hm[n] = List return hm[n] # Given Inputn = 7 # Function CallList = allPossibleFBT(n) # Print all possible binary full treesfor root in range(len(List)): al = [] al.append(List[root].data) display(List[root], al) print("[", end = "") for i in range(len(al)): if(i != len(al) - 1): if(al[i]==-sys.maxsize): print("null, ", end = "") else: print(al[i], end = ", ") else: if(al[i]==-sys.maxsize): print("null]", end = "") else: print(al[i], end = "]") print() # This code is contributed by mukesh07. // C# program for the above approachusing System;using System.Collections.Generic; public class GFG{ // Class for creating node and // its left and right child public class Node { public int data; public Node left; public Node right; public Node(int data, Node left, Node right) { this.data = data; this.left = left; this.right = right; } } // Function to traverse the tree and add all // the left and right child in the list al public static void display(Node node, List<int> al) { // If node = null then terminate the function if (node == null) { return; } // If there is left child of Node node // then insert it into the list al if (node.left != null) { al.Add(node.left.data); } // Otherwise insert null in the list else { al.Add(int.MinValue); } // Similarly, if there is right child // of Node node then insert it into // the list al if (node.right != null) { al.Add(node.right.data); } // Otherwise insert null else { al.Add(int.MinValue); } // Recursively call the function // for left child and right child // of the Node node display(node.left, al); display(node.right, al); } // Driver Code public static void Main(String[] args) { // Given Input int n = 7; // Function Call List<Node> list = allPossibleFBT(n); // Print all possible binary full trees foreach (Node root in list) { List<int> al = new List<int>(); al.Add(root.data); display(root, al); foreach (int i in al){ if(i==int.MinValue) Console.Write("null, "); else Console.Write(i+", "); } Console.WriteLine(); } } // Save tree for all n before recursion. static Dictionary<int, List<Node> > hm = new Dictionary<int, List<Node> >(); public static List<Node> allPossibleFBT(int n) { // Check whether tree exists for given n value or not. if (!hm.ContainsKey(n)) { // Create a list containing nodes List<Node> list = new List<Node>(); // If N=1, Only one tree can exist // i.e. tree with root. if (n == 1) { list.Add(new Node(0, null, null)); } // Check if N is odd because binary full // tree has N nodes else if (n % 2 == 1) { // Iterate through all the nodes that // can be in the left subtree for (int x = 0; x < n; x++) { // Remaining Nodes belongs to the // right subtree of the node int y = n - 1 - x; // Iterate through all left Full Binary Tree // by recursively calling the function foreach (Node left in allPossibleFBT(x)) { // Iterate through all the right Full // Binary tree by recursively calling // the function foreach (Node right in allPossibleFBT(y)) { // Create a new node Node node = new Node(0, null, null); // Modify the left node node.left = left; // Modify the right node node.right = right; // Add the node in the list list.Add(node); } } } } //Insert tree in Dictionary. hm.Add(n, list); } return hm[n]; }} // This code is contributed by 29AjayKumar <script> // Javascript program for the above approach // Class for creating node and // its left and right child class Node { constructor(data, left, right) { this.left = left; this.right = right; this.data = data; } } // Function to traverse the tree and add all // the left and right child in the list al function display(node, al) { // If node = null then terminate the function if (node == null) { return; } // If there is left child of Node node // then insert it into the list al if (node.left != null) { al.push(node.left.data); } // Otherwise insert null in the list else { al.push(Number.MIN_VALUE); } // Similarly, if there is right child // of Node node then insert it into // the list al if (node.right != null) { al.push(node.right.data); } // Otherwise insert null else { al.push(Number.MIN_VALUE); } // Recursively call the function // for left child and right child // of the Node node display(node.left, al); display(node.right, al); } // Save tree for all n before recursion. let hm = new Map(); function allPossibleFBT(n) { // Check whether tree exists for given n value or not. if (!hm.has(n)) { // Create a list containing nodes let list = []; // If N=1, Only one tree can exist // i.e. tree with root. if (n == 1) { list.push(new Node(0, null, null)); } // Check if N is odd because binary full // tree has N nodes else if (n % 2 == 1) { // Iterate through all the nodes that // can be in the left subtree for (let x = 0; x < n; x++) { // Remaining Nodes belongs to the // right subtree of the node let y = n - 1 - x; // Iterate through all left Full Binary Tree // by recursively calling the function let xallPossibleFBT = allPossibleFBT(x); let yallPossibleFBT = allPossibleFBT(y); for(let Left = 0; Left < xallPossibleFBT.length; Left++) { // Iterate through all the right Full // Binary tree by recursively calling // the function for(let Right = 0; Right < yallPossibleFBT.length; Right++) { // Create a new node let node = new Node(0, null, null); // Modify the left node node.left = xallPossibleFBT[Left]; // Modify the right node node.right = yallPossibleFBT[Right]; // Add the node in the list list.push(node); } } } } //Insert tree in Dictionary. hm.set(n, list); } return hm.get(n); } // Given Input let n = 7; // Function Call let list = allPossibleFBT(n); // Print all possible binary full trees for(let root = 0; root < list.length; root++) { let al = []; al.push(list[root].data); display(list[root], al); document.write("["); for(let i = 0; i < al.length; i++){ if(i != al.length - 1) { if(al[i]==Number.MIN_VALUE) document.write("null, "); else document.write(al[i]+ ", "); } else{ if(al[i]==Number.MIN_VALUE) document.write("null]"); else document.write(al[i]+ "]"); } } document.write("</br>"); } // This code is contributed by divyeshrabadiya07.</script> [0, 0, 0, null, null, 0, 0, null, null, 0, 0, null, null, null, null] [0, 0, 0, null, null, 0, 0, 0, 0, null, null, null, null, null, null] [0, 0, 0, 0, 0, null, null, null, null, 0, 0, null, null, null, null] [0, 0, 0, 0, 0, null, null, 0, 0, null, null, null, null, null, null] [0, 0, 0, 0, 0, 0, 0, null, null, null, null, null, null, null, null] Time Complexity: O(2N)Space Complexity: O(2N) 29AjayKumar divyeshrabadiya07 decode2207 mukesh07 Binary Tree Maths Dynamic Programming Recursion Tree Dynamic Programming Recursion Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Optimal Substructure Property in Dynamic Programming | DP-2 Maximum Subarray Sum using Divide and Conquer algorithm Min Cost Path | DP-6 3 Different ways to print Fibonacci series in Java Gold Mine Problem Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Program for Sum of the digits of a given number
[ { "code": null, "e": 24305, "s": 24277, "text": "\n06 Oct, 2021" }, { "code": null, "e": 24500, "s": 24305, "text": "Given an integer N, the task is to print all possible Full Binary Trees with N nodes. The value at the nodes does not contribute to be a criteria for different Ful...
How to build a Movie Recommender System in Python using LightFm | by Arun Mathew Kurian | Towards Data Science
In this blog post, we will be creating a movie recommender system in python, that suggest new movies to the user based on their viewing history. Before we start let's have a quick look at what a recommender system is. You may not know the definition of a Recommender system yet, but you have definitely encountered one before. This is because recommender systems are present everywhere on the internet. The purpose of a recommender system is to suggest users something based on their interest or usage history. So next time Amazon suggests you a product, or Netflix recommends you a tv show or medium display a great post on your feed, understand that there is a recommendation system working under the hood. There are two types of recommendation systems. They are Content-Based Recommender SystemCollaborative Recommender System Content-Based Recommender System Collaborative Recommender System A content-based recommender system works on the data generated from a user. The data can be generated either explicitly (like clicking likes) or implicitly (like clicking on links). This data will be used to create a user profile for the user which contain the metadata of the items user interacted. More the data it receives more accurate the system or engine becomes. A collaborative recommender system makes a recommendation based on how similar users liked the item. The system will group users with similar tastes. In addition to user similarity, recommender systems can also perform collaborative filtering using item similarity (like ‘Users who liked this item X also liked Y’). Most systems will be a combination of these two methods. Lest start coding First, we need to install some packages. LightFM is a Python implementation of a number of popular recommendation algorithms. LightFM includes implementations of BPR and WARP ranking losses(A loss function is a measure of how good a prediction model does in terms of being able to predict the expected outcome.). BPR: Bayesian Personalised Ranking pairwise loss: It maximizes the prediction difference between a positive example and a randomly chosen negative example. It is useful when only positive interactions are present. WARP: Weighted Approximate-Rank Pairwise loss: Maximises the rank of positive examples by repeatedly sampling negative examples until rank violating one is found LightFm also contains a large set of datasets related to the movie rating. We will be working on this dataset. So we will install this library also. pip install lightfm Next, we will be installing two packages for mathematical operations namely numpy and scipy pip install numpy pip install scipy We will create a python file called recommender.py. We can start by importing the libraries into this file import numpy as npfrom lightfm.datasets import fetch_movielensfrom lightfm import LightFM fetch_movielens method is the method from lightfm that can be used to fetch movie data. We can fetch the movie data with a minimum rating of 4. data = fetch_movielens(min_rating = 4.0) The ‘data’ variable will contain the movie data that is divided into many categories test and train. In a supervised learning, you use a training dataset, that contains outcomes, to train the machine. You then use testing dataset that has no outcomes to predict outcomes.Training Data is data for build model and Testing Data is data for test model. We can check this by printing these data print(repr(data[‘train’]))print(repr(data[‘test’])) We can see that the amount of train data is much greater than the test data. This because typically when you separate a dataset into a training set and testing set, most of the data is used for training. Next, we will be creating a lightfm model with ‘warp’ loss function model = LightFM(loss = ‘warp’) We can now train this model using our train data, with an epoch or iteration value of 30. model.fit(data[‘train’], epochs=30, num_threads=2) Now that's done let's build the function that process this data to recommend movies for any number of users. Our function will take the model, data and an array of user_ids. def sample_recommendation(model, data, user_ids): In the function definition, first, we need to get the number of all users and movies. n_users, n_items = data[‘train’].shape Next, we need to iterate the user_ids. for user_id in user_ids: For each user, we need to find the known positives or the movies they liked. This can be obtained from the data we have. known_positives = data[‘item_labels’][data[‘train’].tocsr()[user_id].indices] Next, we need to find the movies the user like. This can be done by the predict method of LightFm. The parameters of this function are user_id and the n_items variable arrange by numpy arrange scores = model.predict(user_id, np.arange(n_items)) We can now sort the scores based on the order of most liked to least liked. top_items = data[‘item_labels’][np.argsort(-scores)] Now that the prediction is done we can print the first 3 known positives and 3 predictions. print(“User %s” % user_id)print(“ Known positives:”)for x in known_positives[:3]: print(“ %s” % x)print(“ Recommended:”)for x in top_items[:3]: print(“ %s” % x) Thus our sample_recommendation method becomes def sample_recommendation(model, data, user_ids): n_users, n_items = data['train'].shape for user_id in user_ids: known_positives = data['item_labels'][data['train'].tocsr() [user_id].indices] scores = model.predict(user_id, np.arange(n_items)) top_items = data['item_labels'][np.argsort(-scores)] print("User %s" % user_id) print(" Known positives:") for x in known_positives[:3]: print(" %s" % x) print(" Recommended:") for x in top_items[:3]: print(" %s" % x) We can finish by invoking the function in our program, by providing three random user_ids. sample_recommendation(model, data, [3, 25, 451]) Let's run the code in the terminal by the command python recommender.py and we get the output Cool...We can see that our system recommends movies to our users. This is an example of how easily a recommender system can be implemented. I hope you find it useful. The code can be found at https://github.com/amkurian/movie-recommendation-system
[ { "code": null, "e": 390, "s": 172, "text": "In this blog post, we will be creating a movie recommender system in python, that suggest new movies to the user based on their viewing history. Before we start let's have a quick look at what a recommender system is." }, { "code": null, "e": ...
Tryit Editor v3.7
Tryit: Using the animation-direction property
[]
VBA - Time Serial Function
The TimeSerial function returns the time for the specified hour, minute, and second values. TimeSerial(hour,minute,second) Hour − A required parameter, which is an integer between 0 and 23 or any numeric expression. Hour − A required parameter, which is an integer between 0 and 23 or any numeric expression. Minute − A required parameter, which is an integer between 0 and 59 or any numeric expression. Minute − A required parameter, which is an integer between 0 and 59 or any numeric expression. Second − A required parameter, which is an integer between 0 and 59 or any numeric expression. Second − A required parameter, which is an integer between 0 and 59 or any numeric expression. Add a button and add the following function. Private Sub Constant_demo_Click() msgbox(TimeSerial(20,1,2)) msgbox(TimeSerial(0,59,59)) msgbox(TimeSerial(7*2,60/3,15+3)) End Sub When you execute the above function, it produces the following output. 8:01:02 PM 12:59:59 AM 2:20:18 PM 101 Lectures 6 hours Pavan Lalwani 41 Lectures 3 hours Arnold Higuit 80 Lectures 5.5 hours Prashant Panchal 25 Lectures 2 hours Prashant Panchal 26 Lectures 2 hours Arnold Higuit 92 Lectures 10.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2027, "s": 1935, "text": "The TimeSerial function returns the time for the specified hour, minute, and second values." }, { "code": null, "e": 2060, "s": 2027, "text": "TimeSerial(hour,minute,second) \n" }, { "code": null, "e": 2153, "s": 2060...
Serializers - Django REST Framework - GeeksforGeeks
10 Sep, 2021 Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data. The serializers in REST framework work very similarly to Django’s Form and ModelForm classes. The two major serializers that are most popularly used are ModelSerializer and HyperLinkedModelSerialzer.This article revolves around how to use serializers from scratch in Django REST Framework to advanced serializer fields and arguments. It assumes one is familiar with How to start a project with Django REST Framework ? Creating and Using Serializers ModelSerializer HyperLinkedModelSerializer Serializer Fields Core arguments in serializer fields To create a basic serializer one needs to import serializers class from rest_framework and define fields for a serializer just like creating a form or model in Django. Example Python3 # import serializer from rest_frameworkfrom rest_framework import serializers # create a serializerclass CommentSerializer(serializers.Serializer): # initialize fields email = serializers.EmailField() content = serializers.CharField(max_length = 200) created = serializers.DateTimeField() This way one can declare serializer for any particular entity or object based on fields required. Serializers can be used to serialize as well as deserialize the data. One can now use CommentSerializer to serialize a comment, or list of comments. Again, using the Serializer class looks a lot like using a Form class. Let’s create a Comment class first to create a object of type comment that can be understood by our serializer. Python3 # import datetime objectfrom datetime import datetime # create a classclass Comment(object): def __init__(self, email, content, created = None): self.email = email self.content = content self.created = created or datetime.now()# create a objectcomment = Comment(email ='leila@example.com', content ='foo bar') Now that our object is ready, let’s try serializing this comment object. Run following command, Python manage.py shell Now run the following code # import comment serializer >>> from apis.serializers import CommentSerializer # import datetime for date and time >>> from datetime import datetime # create a object >>> class Comment(object): ... def __init__(self, email, content, created=None): ... self.email = email ... self.content = content ... self.created = created or datetime.now() ... # create a comment object >>> comment = Comment(email='leila@example.com', content='foo bar') # serialize the data >>> serializer = CommentSerializer(comment) # print serialized data >>> serializer.data Now let’s check output for this, To check more on how to create and use a serializer visit – Creating and Using Serializers The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields. The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model. It will automatically generate validators for the serializer, such as unique_together validators. It includes simple default implementations of .create() and .update(). Syntax – Python3 class SerializerName(serializers.ModelSerializer): class Meta: model = ModelName fields = List of Fields Example – Python3 class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['id', 'account_name', 'users', 'created'] By default, all the model fields on the class will be mapped to a corresponding serializer fields. To checkout how to use ModelSerializer in your project, visit – ModelSerializer in serializers – Django REST Framework. The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field. The url field will be represented using a HyperlinkedIdentityField serializer field, and any relationships on the model will be represented using a HyperlinkedRelatedField serializer field. Syntax – Python3 class SerializerName(serializers.HyperlinkedModelSerializer): class Meta: model = ModelName fields = List of Fields Example – Python3 class AccountSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Account fields = ['id', 'account_name', 'users', 'created'] To checkout how to use HyperLinkedModelSerializer in your project, visit – HyperlinkedModelSerializer in serializers – Django REST Framework. Serializer fields in Django are same as Django Form fields and Django model fields and thus require certain arguments to manipulate the behaviour of those Fields. saurabh1990aror simmytarika5 Django-REST Python Django rest-framework Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Selecting rows in pandas DataFrame based on conditions
[ { "code": null, "e": 24332, "s": 24304, "text": "\n10 Sep, 2021" }, { "code": null, "e": 25043, "s": 24332, "text": "Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also...
Ext.js - Custom Events and listeners
Events are something which get fired when something happens to the class. For example, when a button is getting clicked or before/after the element is rendered. Built-in events using listeners Attaching events later Custom events Ext JS provides listener property for writing events and custom events in Ext JS files. Writing listener in Ext JS We will add the listener in the previous program itself by adding a listen property to the panel. <!DOCTYPE html> <html> <head> <link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-neptune/resources/theme-neptune-all.css" rel = "stylesheet" /> <script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script> <script type = "text/javascript"> Ext.onReady(function() { Ext.create('Ext.Button', { renderTo: Ext.getElementById('helloWorldPanel'), text: 'My Button', listeners: { click: function() { Ext.MessageBox.alert('Alert box', 'Button is clicked'); } } }); }); </script> </head> <body> <p> Please click the button to see event listener </p> <div id = 'helloWorldPanel' /> <!-- panel will be rendered here-- > </body> </html> The above program will produce the following result − Please click the button to see event listener: This way we can also write multiple events in listeners property. Multiple Events in the Same Listener <!DOCTYPE html> <html> <head> <link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-neptune/resources/theme-neptune-all.css" rel = "stylesheet" /> <script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script> <script type = "text/javascript"> Ext.onReady(function() { Ext.get('tag2').hide() Ext.create('Ext.Button', { renderTo: Ext.getElementById('helloWorldPanel'), text: 'My Button', listeners: { click: function() { this.hide(); }, hide: function() { Ext.get('tag1').hide(); Ext.get('tag2').show(); } } }); }); </script> </head> <body> <div id = "tag1">Please click the button to see event listener.</div> <div id = "tag2">The button was clicked and now it is hidden.</div> <div id = 'helloWorldPanel' /> <!-- panel will be rendered here-- > </body> </html> In the previous method of writing events, we have written events in listeners at the time of creating elements. The other way is to attach events. <!DOCTYPE html> <html> <head> <link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-neptune/resources/theme-neptune-all.css" rel = "stylesheet" /> <script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script> <script type = "text/javascript"> Ext.onReady(function() { var button = Ext.create('Ext.Button', { renderTo: Ext.getElementById('helloWorldPanel'), text: 'My Button' }); // This way we can attach event to the button after the button is created. button.on('click', function() { Ext.MessageBox.alert('Alert box', 'Button is clicked'); }); }); </script> </head> <body> <p> Please click the button to see event listener </p> <div id = 'helloWorldPanel' /> <!-- panel will be rendered here-- > </body> </html> The above program will produce the following result − Please click the button to see event listener: We can write custom events in Ext JS and fire the events with fireEvent method. Following example explains how to write custom events. <!DOCTYPE html> <html> <head> <link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-neptune/resources/theme-neptune-all.css" rel = "stylesheet" /> <script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script> <script type = "text/javascript"> Ext.onReady(function() { var button = Ext.create('Ext.Button', { renderTo: Ext.getElementById('helloWorldPanel'), text: 'My Button', listeners: { myEvent: function(button) { Ext.MessageBox.alert('Alert box', 'My custom event is called'); } } }); Ext.defer(function() { button.fireEvent('myEvent'); }, 5000); }); </script> </head> <body> <p> The event will be called after 5 seconds when the page is loaded. </p> <div id = 'helloWorldPanel' /> <!-- panel will be rendered here-- > </body> </html> Once the page is loaded and the document is ready, the UI page with a button will appear and as we are firing an event after 5 secs, the document is ready. The alert box will appear after 5 seconds. The event will be called after 5 seconds when the page is loaded. Here, we have written the custom event 'myEvent' and we are firing events as button.fireEvent(eventName); Print Add Notes Bookmark this page
[ { "code": null, "e": 2184, "s": 2023, "text": "Events are something which get fired when something happens to the class. For example, when a button is getting clicked or before/after the element is rendered." }, { "code": null, "e": 2216, "s": 2184, "text": "Built-in events using...
HTML | <frameset> rows Attribute - GeeksforGeeks
28 May, 2019 The HTML <frameset> rows Attribute is used to specify the size and the number of rows in a frameset. The height of each frame is separated by a comma. Syntax: <frameset rows="pixels|%|*"> Attribute Values: pixels: The height of row is set in terms of pixels. Example: “50px” or “50”. %: The height of row is set in terms of percentage. Example “70%”. *: The height of row is set to all available space. Note: The <frameset> rows Attribute is not supported by HTML 5. Example: <!DOCTYPE html><html> <head> <title>HTML frameset rows Attribute</title></head> <!-- frameset attribute starts here --><frameset rows="20%, 60%, 20%"> <frame name="top" src="attr1.png" /> <frame name="main" src="gradient3.png" /> <frame name="bottom" src="col_last.png" /></frameset><!-- frameset attribute ends here --> </html> Output: Supported Browsers: The browser supported by HTML <frameset> rows Attribute are listed below: Google Chrome Internet Explorer Firefox Safari Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Attributes 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 Angular File Upload Form validation using jQuery How to Dynamically Add/Remove Table Rows using jQuery ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Angular Libraries For Web Developers Convert a string to an integer in JavaScript
[ { "code": null, "e": 24814, "s": 24786, "text": "\n28 May, 2019" }, { "code": null, "e": 24965, "s": 24814, "text": "The HTML <frameset> rows Attribute is used to specify the size and the number of rows in a frameset. The height of each frame is separated by a comma." }, { ...
Perl foreach Loop
The foreach loop iterates over a list value and sets the control variable (var) to be each element of the list in turn − The syntax of a foreach loop in Perl programming language is − foreach var (list) { ... } #!/usr/local/bin/perl @list = (2, 20, 30, 40, 50); # foreach loop execution foreach $a (@list) { print "value of a: $a\n"; } When the above code is executed, it produces the following result − value of a: 2 value of a: 20 value of a: 30 value of a: 40 value of a: 50 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2341, "s": 2220, "text": "The foreach loop iterates over a list value and sets the control variable (var) to be each element of the list in turn −" }, { "code": null, "e": 2404, "s": 2341, "text": "The syntax of a foreach loop in Perl programming language is ...
Introducing Anomaly/Outlier Detection in Python with PyOD 🔥 | by Eirik Berge | Towards Data Science
Setting the StageWhat is Anomaly/Outlier Detection?Introducing PyODGetting Familiar with the DataAnomaly Detection for Data CleaningAnomaly Detection for PredictionWrapping Up Setting the Stage What is Anomaly/Outlier Detection? Introducing PyOD Getting Familiar with the Data Anomaly Detection for Data Cleaning Anomaly Detection for Prediction Wrapping Up In recent years, anomaly detection has become more popular in the machine learning community. Despite this, there are definitely fewer resources on anomaly detection than classical machine learning algorithms. As such, learning about anomaly detection can feel more tricky than it should be. Anomaly detection is from a conceptual standpoint actually very simple! The goal of this blog post is to give you a quick introduction to anomaly/outlier detection. Specifically, I will show you how to implement anomaly detection in Python with the package PyOD — Python Outlier Detection. In this way, you will not only get an understanding of what anomaly/outlier detection is but also how to implement anomaly detection in Python. The good news is that PyOD is easy to apply — especially if you already have experience with Scikit-Learn. In fact, the PyOD package tries to be very similar to the Scikit-Learn API interface. Prerequisites: You should have some basic familiarity with Python and Pandas. However, no knowledge of anomaly detection is necessary 😃 Anomaly detection goes under many names; outlier detection, outlier analysis, anomaly analysis, and novelty detection. A concise description from Wikipedia describes anomaly detection as follows: Anomaly detection is the identification of rare items, events or observations which raise suspicions by differing significantly from the majority of the data. Let‘s try to unpack the above statements. Say you have a dataset consisting of many observations. The goal of anomaly detection is to identify the observations that differ significantly from the rest. Why would you want to do this? There are two major reasons: When cleaning the data, it is sometimes better to remove anomalies as they misrepresent the data. Let’s illustrate this with a concrete example: Say that you have made a survey that asks questions regarding the respondents favourite cat breeds 😺 You first give the survey to 100 people that each complete the survey. Now you want to estimate the average time it took to take the survey. Why? You want 10.000 more people to take the survey. It would be professional to indicate roughly how long the survey takes for the new respondents. Even though cats are awesome, people are busy! Let’s say that you got the following results from the first 100 people: 3 Minutes — 57 respondents 4 Minutes — 33 respondents 5 Minutes — 6 respondents 6 Minutes — 3 respondents 480 Minutes — 1 respondent What is going on with the last one? 480 minutes is 8 hours! Upon further inspection, you find that the respondent started the survey at 23:58 in the evening, and then stood still from 00:00 until 07:56. Then from the time 07:56 to 07:58 it was finished. Can you see what happened? Clearly, a person started the survey, then went to bed, and then finished the survey when he/she got up in the morning. If you keep this result, then the average time to complete the survey will be average = (3 * 57 + 4 * 33 + 5 * 6 + 6 * 3 + 1 * 480)/100 = 8.31 However, saying that the survey takes roughly 8 minutes is not accurate. The only reason it took that long was because of a sleepy respondent 😪 It would be more accurate to remove that person from the tally and get average = (3 * 57 + 4 * 33 + 5 * 6 + 6 * 3)/99 = 3.54 For simplicity, the survey could write the sentence: The average completion time for the survey is between 3 and 4 minutes. Here you have manually removed an outlier to clean the data to better represent reality. Anomaly detection is implementing algorithms to detect outliers automatically. Caveat: In the above example you have removed an outlier to better match the survey length with reality. Anomaly detection should never be used to artificially make a product seem better than it really is. Careful consideration should be made whether it is ethically appropriate to use anomaly detection for data cleaning. In other applications, the anomalies themselves are the point of interest. Examples are network intrusion, bank fraud, and certain structural defects. In these applications, the anomalies represent something that is worthy of further study. Network intrusion — anomalies in network data can indicate that a network attack of some sort has taken place. Bank fraud — anomalies in transaction data can indicate fraud or suspicious behaviour. Structural defects — anomalies can indicate that something is wrong with your hardware. While more traditional monitoring software is typically available in this setting, anomaly detection can discover more weird defects. Caveat: In some settings like bank fraud, it is not always an individual transaction that raises suspicions. It is the frequency and magnitude of multiple transactions seen in context that should be considered. To deal with this, the data should be aggregated appropriately. This is outside the scope of this blog, but something that you should be aware of. Let’s describe the Python package PyOD that helps you to do anomaly detection. In the words of the PyOD documentation: PyOD is a comprehensive and scalable Python toolkit for detecting outlying objects in multivariate data. Brifly put, PyOD supplies you with a bunch of models that perform anomaly detection. Some cool highlights that are worth mentioning are: PyOD includes more than 30 different algorithms. Some of them are classics (like LOF), while others are the new kids on the block (like COPOD). See a full list of supported models. PyOD has optimized its code by using the jit-decorator from Numba. I’ve written a blog post on Numba if you are interested in this. PyOD has a uniform API. Hence if you become familiar with a few models in PyOD, then you can learn the rest with ease. I recommend taking a look at the PyOD API CheatSheet after you finish this blog. If you are using PIP, then you can install PyOD with the command: pip install pyod If you already have PyOD installed previously, then make sure it is updated with the pip command: pip install --upgrade pyod If you are instead using the Conda package manager, then you can run the command: conda install -c conda-forge pyod In this blog post, I will demonstrate two algorithms for doing anomaly detection: KNN and LOC. You’ve maybe heard of KNN (K – Nearest Neighbors) previously, while LOC (Local Outlier Factor) is probably unfamiliar to you. Let’s first take a look at the data you will be using ⚡️ We will be using the classical Titanic dataset. To get the dataset loaded into Pandas, simply run the code below: import pandas as pdtitanic = pd.read_csv("https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv") To check out the first rows of the dataset, use the head() method: titanic.head() As you can see, there are columns representing the sex, age, fare price, passenger class, ticket, etc. For simplicity you will only work with the following four columns: # Selecting only the columns Survived, Pclass, Fare, and Sexpartial_titanic = titanic[["Survived", "Pclass", "Fare", "Sex"]] There are no missing values in partial_titanic. However, the column Sex consists of the string values male or female. To be able to do anomaly detection, you need numeric values. You can convert this binary categorical variable to the values 0 and 1 with the code: # Change the categorical value Sex to numeric valuespartial_titanic["Sex"] = partial_titanic["Sex"].map({"male": 0,"female": 1}) Now you are ready to do anomaly detection 😃 Let’s now use anomaly detection to clean the dataset partial_titanic you made in the previous section. You will use the KNN model to do this. The KNN model examines the data and looks for data points (rows) that are far from the other data points. To get started, you import the KNN model as follows: # Import the KNNfrom pyod.models.knn import KNN We begin by initiating a KNN model: # Initiate a KNN modelKNN_model = KNN() For anomaly detection methods for data cleaning, you can fit on the whole dataset as follows # Fit the model to the whole datasetKNN_model.fit(partial_titanic)Output:KNN(algorithm='auto', contamination=0.1, leaf_size=30, method='largest', metric='minkowski', metric_params=None, n_jobs=1, n_neighbors=5, p=2, radius=1.0) When running the code above you get printed out a lot of default values (e.g. contamination=0.1). This can be tweaked if needed. After running a model you can access two types of output: Labels: By running KNN_model.labels_ you can find binary labels of whether an observation is an outlier or not. The number 0 indicates a normal observation, while the number 1 indicates an outlier. Decision Scores: By running KNN_model.decision_scores_ you get the raw scores of how much of an outlier something is. The values will range from 0 and upwards. A higher anomaly score indicates that a data point is more of an outlier. Let’s check out the labels of the trained model: # Find the labelsoutlier_labels = KNN_model.labels_# Find the number of outliersnumber_of_outliers = len(outlier_labels[outlier_labels == 1])print(number_of_outliers)Output:88 For a dataset with 891 passengers, having 88 outliers is quite high. To reduce this, you can specify the parameter contamination in the KNN model to be lower. The contamination indicates the percentage of data points that are outliers. Let’s say that the contamination is only 1%: # Initiate a KNN modelKNN_model = KNN(contamination=0.01)# Fit the model to the whole datasetKNN_model.fit(partial_titanic)# Find the labelsoutlier_labels = KNN_model.labels_# Find the number of outliersnumber_of_outliers = len(outlier_labels[outlier_labels == 1])print(number_of_outliers)Output: 9 Now there are only 9 outliers! You can check them out: # Finding the outlier passengersoutliers = partial_titanic.iloc[outlier_labels == 1] If you check out the outliers variable, you get the following table: If you check out the passengers above, then the KNN model picks up that their fare price is incredibly high. The average fare price for all the passengers can be easily found in Pandas: # Average fare priceround(partial_titanic["Fare"].mean(), 3)Output:32.204 The KNN algorithm has successfully found 9 passengers that are outliers in the sense of the fare price. There are many optional parameters you can play around with for the KNN model to make it suit your specific need 🔥 The outliers can now be removed from the data if you feel like they don’t represent the general feel of the data. As mentioned previously, you should consider carefully whether anomaly detection for data cleaning is appropriate for your problem. In the previous section, you looked at anomaly detection for data cleaning. In this section, you will take a peak at anomaly detection for prediction. You will train a model on existing data, and then use the model to predict whether new data are outliers. Say a rumor spread that a Mrs. Watson had also taken the Titanic, but her death was never recorded. According to the rumors, Mrs. Watson was a wealthy lady that paid 1000$ to travel with the Titanic in a very exclusive suite. Anomaly detection can not say with certainty whether the rumor is true or false. However, it can say whether Mrs. Watson is an anomaly or not based on the information of the other passengers. If she is an anomaly, the rumor should be taken with a grain of salt. Let’s test Mrs. Watson existence with another model in the PyOD library; Local Outlier Factor (LOF). A LOF model tests whether a data point is an outlier by comparing the local density of the datapoint with the local densities of its neighbors. For more information on this method, you can check out its Wikipedia page. Let’s get coding! You start by establishing a Local Outlier Factor model: # Import the LOFfrom pyod.models.lof import LOF# Initiate a LOF modelLOF_model = LOF()# Train the model on the Titanic dataLOF_model.fit(partial_titanic) Pay attention to how similar working with a LOF model is to working with a KNN model. Now you can represent Mrs. Watson as a data point: # Represent Mrs. Watson as a data pointmrs_watson = [[0, 1, 1000, 1]] The values in mrs_watson represent her survival (0 for not survived), passenger class (1 for first-class), fare price (1000$ for the fare price), and sex (1 for female). The LOF model requires 2D arrays, so this is the reason for the extra bracket pair [] in mrs_watson. We now use the predict() method to predict whether Mrs. Watson is an outlier or not: outlier = LOF_model.predict(mrs_watson)print(outlier)Output:1 A value of 1 indicates that Mrs. Watson is an outlier. This should make you suspicious that the rumor regarding Mrs. Watson is false 😮 I have shown you how to implement anomaly detection with the two algorithms KNN and LOF. As you probably suspect, there are many more algorithms that you can play around with in PyOD. Anomaly detection is important for both cleaning the data and also for predicting outliers. The application at hand should determine whether or not it is of interest to apply anomaly detection. If you are planning on applying anomaly detection in Python, then PyOD is a solid choice. Like my writing? Check out some of my other posts for more Python content: Modernize Your Sinful Python Code with Beautiful Type Hints Visualizing Missing Values in Python is Shockingly Easy Painlessly Speed Up Your Data Analysis in Python with Mito 5 Awesome NumPy Functions That Can Save You in a Pinch 5 Expert Tips to Skyrocket Your Dictionary Skills in Python 🚀 If you are interested in data science, programming, or anything in between, then feel free to add me on LinkedIn and say hi ✋
[ { "code": null, "e": 348, "s": 172, "text": "Setting the StageWhat is Anomaly/Outlier Detection?Introducing PyODGetting Familiar with the DataAnomaly Detection for Data CleaningAnomaly Detection for PredictionWrapping Up" }, { "code": null, "e": 366, "s": 348, "text": "Setting th...
SQLSERVER Tryit Editor v1.0
SELECT CAST('2017-08-25' AS datetime); ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, and Opera. If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 39, "s": 0, "text": "SELECT CAST('2017-08-25' AS datetime);" }, { "code": null, "e": 41, "s": 39, "text": "​" }, { "code": null, "e": 113, "s": 50, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "co...
7 Handy Use Cases Of Dictionary Comprehensions In Python | by Anupam Chugh | Towards Data Science
Comprehensions in Python are syntactic constructs that are used to build sequences from other sequences. Essentially, comprehensions are a fancy form of writing for loops that are more concise and readable. All comprehensions can be rewritten using for loops but the vice-versa doesn’t hold true. At large, there are four types of comprehension techniques in Python. List Comprehensions Dictionary Comprehensions Set Comprehensions Generator Comprehensions The goal of this piece is to show you the power of dictionary comprehensions and how to leverage it in different ways. Before we explore a few interesting cases, let’s understand the syntax as it can confuse a lot of developers when starting out. Consider the following code that creates a dictionary from a range of numbers with the value being the square of the key: square_dict = {num: num*num for num in range(1, 6)}print(square_dict)#Output{1: 1, 2: 4, 3: 9, 4: 16, 5: 25} Now let’s analyze the syntax of the dictionary expression using the above code as a reference: The above syntax represents the minimal form of writing a dictionary comprehension. The output of the dictionary comprehension is highlighted in green. All the key-value pairs are assigned to the constructed dictionary. The iterable doesn’t have to be a dictionary. It can be any python object on which you can loop over — list, tuple, strings, etc. Unlike list comprehensions, a dictionary comprehension can iterate over a group of keys and values simultaneously as well. By invoking the items() method on a dictionary, you can convert it into a list of tuples of key-value to loop over. You can also set a conditional statement after the for loop in dictionary comprehension as shown below: fruits = ['Apple', 'Orange', 'Papaya', 'Banana', '']fruits_dict = {f:len(f) for f in fruits if len(f) > 0}print(fruits_dict)#Output{'Apple': 5, 'Orange': 6, 'Papaya': 6, 'Banana': 6} Now that we’ve got a good look at the syntax of dictionary comprehensions, let's move onto its applications. Often a case comes up where you need to build a dictionary that holds the count of each word in a string. The classic way of doing this using for loops would be: s = 'I felt happy because I saw the others were happy and because I knew I should feel happy'dict = {}for token in s.split(" "): dict[token] = dict.get(token, 0) + 1 But we can make it significantly shorter using dictionary comprehensions as shown below: frequency_dict = {token: s.split().count(token) for token in set(s.split())}#Output{'felt': 1, 'and': 1, 'should': 1, 'others': 1, 'saw': 1, 'were': 1, 'knew': 1, 'happy': 3, 'feel': 1, 'the': 1, 'because': 2, 'I': 4} With a large dictionary, there might come a point where you need to append a single character to all of them. It could be a simple $ symbol for instance. In another scenario, you might need to remove a character from a key or value string. Here’s an example of how to create a new dictionary by modifying keys and values using dictionary comprehension: d = {'My_Article1': '1', 'My_Article2' : '2'}my_dict = { k[3:] : '$' + v for k, v in d.items()}#Output{'Article1': '$1', 'Article2': '$2'} You probably might be interested in only a part of a dictionary that has a certain set of keys. Here’s an example that filters and creates a new dictionary based on a list of keys: d = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}keys = [1, 2]my_dict = {key: d[key] for key in keys}#Output{1: 'a', 2: 'b'} But the above code would throw an error when the list of keys contains an extraneous value not present in the dictionary. So, instead of iterating over keys , we’ll look to find the common keys in d and keys using sets as shown below: my_dict = {key: d[key] for key in set(keys).intersection(d.keys())} Here’s a third case, where we’re filtering the dictionary by keys containing a specified string: d = {'num_1': 'a', '2': 'b', 'num_3': 'c', '4': 'd'}filter_string = 'num'filtered_dict = {k:v for (k,v) in d.items() if filter_string in k}#Output{'num_1': 'a', 'num_3': 'c'} In cases, where your dictionary has unique keys and values and would like to invert the mapping from k:v to v:k you could do it with a for loop in the following way: d = {'1': 'a', '2': 'b', '3': 'c', '4': 'd'}my_dict = {}for k,v in d.items(): my_dict[v] = k By using dictionary comprehension, we can do the same thing in a single line as: my_dict = {v: k for k, v in d.items()}#Output{'a': '1', 'b': '2', 'c': '3', 'd': '4'} Next up, we have a tuple list where each element holds the country code and name. We’ll create a dictionary out of it using comprehension technique with the country name being the key, and country-code being the value: tuples = [("US", '+1'), ("Australia", '+61'), ("India", '+91')]my_dict = {k[0]: k[1] for k in tuples} Sparse vectors generally contain a lot of zero values. We can consider keeping only non-zero values in a dictionary we can save some space. By using the following dictionary comprehension technique, we can convert a sparse vector to key-value pairs with the key being the index from the sparse vector: values = [0,0,21,0,0,0,100]my_dict = { values.index(v) : v for v in values if v}#Output{2: 21, 6: 100} There’s another way of writing the above dictionary comprehension that’s slightly more readable: my_dict = {n: v for n,v in enumerate(values) if v} if v indicates to add the key and value to the dictionary only if the sparse vector’s element isn’t False, 0, None, etc. There are different ways to sort a dictionary. We can do it with keys or values, in ascending or descending orders. Let’s take a look. Here’s an example to sort by keys in ascending and descending order: d = {"a": 3, "b": 4, "d": 1, "c": 2}dk_ascending = {k: d[k] for k in sorted(d)}#Output{'a': 3, 'b': 4, 'c': 2, 'd': 1}dk_descending = {k: d[k] for k in sorted(d, reverse=True)}#Output{'d': 1, 'c': 2, 'b': 4, 'a': 3} The below example shows how to sort by value in ascending and descending order: d = {"a": 3, "b": 4, "d": 1, "c": 2}dv_ascending = {k: d[k] for k in sorted(d, key=d.get)}#Output{'d': 1, 'c': 2, 'a': 3, 'b': 4}dv_descending = {k: d[k] for k in sorted(d, key=d.get, reverse=True)}#Output{'b': 4, 'a': 3, 'c': 2, 'd': 1} Let’s say we have an unknown number of dictionaries present in a Python List as shown below: l = [{'a':1}, {'b':2}, {'c':3, 'd' : 4}] Now, we’d like to flatten the list into a dictionary such that all the sub-dictionaries are merged into a single dictionary. We can use the following doubly nested dictionary comprehension technique: my_dict = {k: v for d in l for k, v in d.items()}#Output{'a': 1, 'b': 2, 'c': 3, 'd': 4} We saw a bunch of different use cases for applying dictionary comprehensions in Python. The idea is to use it efficiently and not overdo it. It’s very easy to misuse it for fairly straightforward manipulations. That’s it for this one — thanks for reading.
[ { "code": null, "e": 379, "s": 172, "text": "Comprehensions in Python are syntactic constructs that are used to build sequences from other sequences. Essentially, comprehensions are a fancy form of writing for loops that are more concise and readable." }, { "code": null, "e": 539, "s...
How to make a text italic using JavaScript?
To make text italic using JavaScript, use the italics() method. This method causes a string to be italic as if it were in an <i> tag. You can try to run the following code to make a text italic with JavaScript − Live Demo <html> <head> <title>JavaScript String italics() Method</title> </head> <body> <script> var str = new String("Demo Text"); document.write(str.italics()); alert(str.italics()); </script> </body> </html>
[ { "code": null, "e": 1196, "s": 1062, "text": "To make text italic using JavaScript, use the italics() method. This method causes a string to be italic as if it were in an <i> tag." }, { "code": null, "e": 1274, "s": 1196, "text": "You can try to run the following code to make a ...
C++ Memory Library - auto_ptr
It an automatic Pointer and it provides a limited garbage collection facility for pointers, by allowing pointers to have the elements they point to automatically destroyed when the auto_ptr object is itself destroyed. Following is the declaration for std::auto_ptr function. template <class X> class auto_ptr; template <class X> class auto_ptr; X − It is a managed object. Print Add Notes Bookmark this page
[ { "code": null, "e": 2821, "s": 2603, "text": "It an automatic Pointer and it provides a limited garbage collection facility for pointers, by allowing pointers to have the elements they point to automatically destroyed when the auto_ptr object is itself destroyed." }, { "code": null, "e"...
How to add padding to a tkinter widget only on one side?
Let us suppose that we want to add padding on one side (either top/bottom or left/right) of a particular widget. We can achieve this in Tkinter by using its pack() and grid() methods. In pack() method, we have to define the value for “padx” and “pady”. On the other hand, the grid method requires only two tuples, i.e., x and y for adding padding around either of X-axis or Y-axis. #import the required library from tkinter import * #Create an instance of window or frame win= Tk() win.geometry("700x400") #Create two buttons #Add padding in x and y axis b1= Button(win, text= "Button1", font=('Poppins bold', 15)) b1.pack(padx=10) b2= Button(win, text= "Button2", font=('Poppins bold', 15)) b2.pack(pady=50) b3= Button(win, text= "Button3", font= ('Poppins bold', 15)) b3.pack(padx=50, pady=50) #Keep running the window win.mainloop() Running the above code will create a window containing three buttons that will have some padding around either of X, Y, or both axes.
[ { "code": null, "e": 1246, "s": 1062, "text": "Let us suppose that we want to add padding on one side (either top/bottom or left/right) of a particular widget. We can achieve this in Tkinter by using its pack() and grid() methods." }, { "code": null, "e": 1444, "s": 1246, "text":...
Python program to remove all duplicates word from a given sentence.
Given a sentence. Remove all duplicates words from a given sentence. Input: I am a peaceful soul and blissful soul. Output: I am a peaceful soul and blissful. Step 1: Split input sentence separated by space into words. Step 2: So to get all those strings together first we will join each string in a given list of strings. Step 3: now create a dictionary using the counter method which will have strings as key and their Frequencies as value. Step 4: Join each words are unique to form single string. from collections import Counter def remov_duplicates(st): st = st.split(" ") for i in range(0, len(st)): st[i] = "".join(st[i]) dupli = Counter(st) s = " ".join(dupli.keys()) print ("After removing the sentence is ::>",s) # Driver program if __name__ == "__main__": st = input("Enter the sentence") remov_duplicates(st) Enter the sentence ::> i am a peaceful soul and blissful soul After removing the sentence is ::> i am a peaceful soul and blissful
[ { "code": null, "e": 1131, "s": 1062, "text": "Given a sentence. Remove all duplicates words from a given sentence." }, { "code": null, "e": 1221, "s": 1131, "text": "Input: I am a peaceful soul and blissful soul.\nOutput: I am a peaceful soul and blissful." }, { "code": ...
C++ Program to Generate Random Numbers Using Probability Distribution Function
Probability Density Function (pdf), is a function that describes the relative likelihood for this random variable to take on a given value. It is also called as density of a continuous random variable. The probability of the random variable fall within a particular range of values is given by the integral of this variable’s density over that range, So, it is given by the area under the density function but above the horizontal axis and between the lowest and greatest values of the range. Probability Distribution is based upon this probability density function. Begin Declare n Assign pdf=0 For i =0 to n , do pdf = rand() mod 200 If pdf greater than 360 Print 1 Else if pdf less than 0 Print 0 Else Print pdf * 0.1 / 360 Done Done end #include <iostream> using namespace std; int n = 6; int main(int argc, char **argv) { int pdf = 0; for (int i = 0; i < n; i++) { pdf = rand() % 200; if (pdf > 360) cout << 1 << " "; else if (pdf < 0) cout << 0 << " "; else cout << pdf * 0.1 / 360 << " "; } cout << "..."; } 0.0508333 0.0238889 0.0491667 0.0319444 0.0536111 0.0375 ...
[ { "code": null, "e": 1264, "s": 1062, "text": "Probability Density Function (pdf), is a function that describes the relative likelihood for this random variable to take on a given value. It is also called as density of a continuous random variable." }, { "code": null, "e": 1629, "s":...
Groovy - Closures
A closure is a short anonymous block of code. It just normally spans a few lines of code. A method can even take the block of code as a parameter. They are anonymous in nature. Following is an example of a simple closure and what it looks like. class Example { static void main(String[] args) { def clos = {println "Hello World"}; clos.call(); } } In the above example, the code line - {println "Hello World"} is known as a closure. The code block referenced by this identifier can be executed with the call statement. When we run the above program, we will get the following result − Hello World Closures can also contain formal parameters to make them more useful just like methods in Groovy. class Example { static void main(String[] args) { def clos = {param->println "Hello ${param}"}; clos.call("World"); } } In the above code example, notice the use of the ${param } which causes the closure to take a parameter. When calling the closure via the clos.call statement we now have the option to pass a parameter to the closure. When we run the above program, we will get the following result − Hello World The next illustration repeats the previous example and produces the same result, but shows that an implicit single parameter referred to as it can be used. Here ‘it’ is a keyword in Groovy. class Example { static void main(String[] args) { def clos = {println "Hello ${it}"}; clos.call("World"); } } When we run the above program, we will get the following result − Hello World More formally, closures can refer to variables at the time the closure is defined. Following is an example of how this can be achieved. class Example { static void main(String[] args) { def str1 = "Hello"; def clos = {param -> println "${str1} ${param}"} clos.call("World"); // We are now changing the value of the String str1 which is referenced in the closure str1 = "Welcome"; clos.call("World"); } } In the above example, in addition to passing a parameter to the closure, we are also defining a variable called str1. The closure also takes on the variable along with the parameter. When we run the above program, we will get the following result − Hello World Welcome World Closures can also be used as parameters to methods. In Groovy, a lot of the inbuilt methods for data types such as Lists and collections have closures as a parameter type. The following example shows how a closure can be sent to a method as a parameter. class Example { def static Display(clo) { // This time the $param parameter gets replaced by the string "Inner" clo.call("Inner"); } static void main(String[] args) { def str1 = "Hello"; def clos = { param -> println "${str1} ${param}" } clos.call("World"); // We are now changing the value of the String str1 which is referenced in the closure str1 = "Welcome"; clos.call("World"); // Passing our closure to a method Example.Display(clos); } } In the above example, We are defining a static method called Display which takes a closure as an argument. We are defining a static method called Display which takes a closure as an argument. We are then defining a closure in our main method and passing it to our Display method as a parameter. We are then defining a closure in our main method and passing it to our Display method as a parameter. When we run the above program, we will get the following result − Hello World Welcome World Welcome Inner Several List, Map, and String methods accept a closure as an argument. Let’s look at example of how closures can be used in these data types. The following example shows how closures can be used with Lists. In the following example we are first defining a simple list of values. The list collection type then defines a function called .each. This function takes on a closure as a parameter and applies the closure to each element of the list. class Example { static void main(String[] args) { def lst = [11, 12, 13, 14]; lst.each {println it} } } When we run the above program, we will get the following result − 11 12 13 14 The following example shows how closures can be used with Maps. In the following example we are first defining a simple Map of key value items. The map collection type then defines a function called .each. This function takes on a closure as a parameter and applies the closure to each key-value pair of the map. class Example { static void main(String[] args) { def mp = ["TopicName" : "Maps", "TopicDescription" : "Methods in Maps"] mp.each {println it} mp.each {println "${it.key} maps to: ${it.value}"} } } When we run the above program, we will get the following result − TopicName = Maps TopicDescription = Methods in Maps TopicName maps to: Maps TopicDescription maps to: Methods in Maps Often, we may wish to iterate across the members of a collection and apply some logic only when the element meets some criterion. This is readily handled with a conditional statement in the closure. class Example { static void main(String[] args) { def lst = [1,2,3,4]; lst.each {println it} println("The list will only display those numbers which are divisible by 2") lst.each{num -> if(num % 2 == 0) println num} } } The above example shows the conditional if(num % 2 == 0) expression being used in the closure which is used to check if each item in the list is divisible by 2. When we run the above program, we will get the following result − 1 2 3 4 The list will only display those numbers which are divisible by 2. 2 4 The closures themselves provide some methods. The find method finds the first value in a collection that matches some criterion. It finds all values in the receiving object matching the closure condition. Method any iterates through each element of a collection checking whether a Boolean predicate is valid for at least one element. The method collect iterates through a collection, converting each element into a new value using the closure as the transformer. 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2415, "s": 2238, "text": "A closure is a short anonymous block of code. It just normally spans a few lines of code. A method can even take the block of code as a parameter. They are anonymous in nature." }, { "code": null, "e": 2483, "s": 2415, "text": "Follo...
Be Careful When Interpreting Predictive Models in Search of Causal Insights | by Scott Lundberg | Towards Data Science
A joint article about causality and interpretable machine learning with Eleanor Dillon, Jacob LaRiviere, Jonathan Roth, and Vasilis Syrgkanis from Microsoft. Predictive machine learning models like XGBoost become even more powerful when paired with interpretability tools like SHAP. These tools identify the most informative relationships between the input features and the predicted outcome, which is useful for explaining what the model is doing, getting stakeholder buy-in, and diagnosing potential problems. It is tempting to take this analysis one step further and assume that interpretation tools can also identify what features decision makers should manipulate if they want to change outcomes in the future. However, in this article, we discuss how using predictive models to guide this kind of policy choice can often be misleading. The reason relates to the fundamental difference between correlation and causation. SHAP makes transparent the correlations picked up by predictive ML models. But making correlations transparent does not make them causal! All predictive models implicitly assume that everyone will keep behaving the same way in the future, and therefore correlation patterns will stay constant. To understand what happens if someone starts behaving differently, we need to build causal models, which requires making assumptions and using the tools of causal analysis. Imagine we are tasked with building a model that predicts whether a customer will renew their product subscription. Let’s assume that after a bit of digging we manage to get eight features which are important for predicting churn: customer discount, ad spending, customer’s monthly usage, last upgrade, bugs reported by a customer, interactions with a customer, sales calls with a customer, and macroeconomic activity. We then use those features to train a basic XGBoost model to predict if a customer will renew their subscription when it expires: X, y = user_retention_dataset()model = fit_xgboost(X, y) Once we have our XGBoost customer retention model in hand, we can begin exploring what it has learned with an interpretability tool like SHAP. We start by plotting the global importance of each feature in the model: explainer = shap.Explainer(model)shap_values = explainer(X)clust = shap.utils.hclust(X, y, linkage="single")shap.plots.bar(shap_values, clustering=clust, clustering_cutoff=1) This bar plot shows that the discount offered, ad spend, and number of bugs reported are the top three factors driving the model’s prediction of customer retention (it also includes a feature redundancy clustering which we will use later). This is interesting and at first glance looks reasonable. However, when we dig deeper and look at how changing the value of each feature impacts the model’s prediction, we find some unintuitive patterns. SHAP scatter plots show how changing the value of a feature impacts the model’s prediction of renewal probabilities. If the blue dots follow an increasing pattern, this means that the larger the feature, the higher is the model’s predicted renewal probability. shap.plots.scatter(shap_values) The scatter plots show some surprising findings: Users who report more bugs are more likely to renew! Users with larger discounts are less likely to renew! We triple-check our code and data pipelines to rule out a bug, then talk to some business partners who offer an intuitive explanation: Users with high usage who value the product are more likely to report bugs and to renew their subscriptions. The sales force tends to give high discounts to customers they think are less likely to be interested in the product, and these customers have higher churn. Are these at-first counter-intuitive relationships in the model a problem? That depends on what our goal is! Our original goal for this model was to predict customer retention, which is useful for projects like estimating future revenue for financial planning. Since users reporting more bugs are in fact more likely to renew, capturing this relationship in the model is helpful for prediction. As long as our model has good fit out-of-sample, we should be able to provide finance with a good prediction, and therefore shouldn’t worry about the direction of this relationship in the model. This is an example of a class of tasks called prediction tasks. In a prediction task, the goal is to predict an outcome Y (e.g. renewals) given a set of features X. A key component of a prediction exercise is that we only care that the prediction model(X) is close to Y in data distributions similar to our training set. A simple correlation between X and Y can be helpful for these types of predictions. However, suppose a second team picks up our prediction model with the new goal of determining what actions our company can take to retain more customers. This team cares a lot about how each X feature relates to Y, not just in our training distribution, but the counterfactual scenario produced when the world changes. In that use case, it is no longer sufficient to identify a stable correlation between variables; this team wants to know whether manipulating feature X will cause a change in Y. Picture the face of the chief of engineering when you tell him that you want him to introduce new bugs to increase customer renewals! This is an example of a class of tasks called causal tasks. In a causal task, we want to know how changing an aspect of the world X (e.g bugs reported) affects an outcome Y (renewals). In this case, it’s critical to know whether changing X causes an increase in Y, or whether the relationship in the data is merely correlational. A useful tool to understanding causal relationships is writing down a causal graph of the data generating process we’re interested in. A causal graph of our example illustrates why the robust predictive relationships picked up by our XGBoost customer retention model differ from the causal relationships of interest to the team that wants to plan interventions to increase retention. This graph is just a summary of the true data generating mechanism (which can be found in the notebook version of this article). Solid ovals represent features that we observe, while dashed ovals represent hidden features that we don’t measure. Each feature is a function of all the features with an arrow to it, plus some random effects. In our example we know the causal graph because we simulate the data. In practice the true causal graph will not be known, but we may be able to use context-specific domain knowledge about how the world works to infer which relationships can or cannot exist. There are lots of relationships in this graph, but the first important concern is that some of the features we can measure are influenced by unmeasured confounding features like product need and bugs faced. For example, users who report more bugs are encountering more bugs because they use the product more, and they are also more likely to report those bugs because they need the product more. Product need has its own direct causal effect on renewal. Because we can’t directly measure product need, the correlation we end up capturing in predictive models between bugs reported and renewal combines a small negative direct effect of bugs faced and a large positive confounding effect from product need. The figure below plots the SHAP values in our example against the true causal effect of each feature (known in this example since we generated the data). The predictive model captures an overall positive effect of bugs reported on retention (as shown with SHAP), even though the causal effect of reporting a bug is zero, and the effect of encoutering a bug is negative. We see a similar problem with Discounts, which are also driven by unobserved customer need for the product. Our predictive model finds a negative relationship between discounts and retention, driven by this correlation with the unobserved feature, Product Need, even though there is actually a small positive causal effect of discounts on renewal! Put another way, if two customers with have the same Product Need and are otherwise similar, then the customer with the larger discount is more likely to renew. This plot also reveals a second, sneakier problem when we start to interpret predictive models as if they were causal. Notice that Ad Spend has a similar problem — it has no causal effect on retention (the black line is flat), but the predictive model is picking up a positive effect! In this case, Ad Spend is only driven by Last Upgrade and Monthly Usage, so we don’t have an unobserved confounding problem, instead we have an observed confounding problem. There is statistical redundancy between Ad Spend and features that influence Ad Spend. When we have the same information captured by several features, predictive models can use any of those features for prediction, even though they are not all causal. While Ad Spend has no causal effect on renewal itself, it is strongly correlated with several features that do drive renewal. Our regularized model identifies Ad Spend as a useful predictor because it summarizes multiple causal drivers (so leading to a sparser model), but that becomes seriously misleading if we start to interpret it as a causal effect. We will now tackle each piece of our example in turn to illustrate when predictive models can accurately measure causal effects, and when they cannot. We will also introduce some causal tools that can sometimes estimate causal effects in cases where predictive models fail. Let’s start with the successes in our example. Notice that our predictive model does a good job of capturing the real causal effect of the Economy feature (a better economy has a positive effect on retention). So when can we expect predictive models to capture true causal effects? The important ingredient that allowed XGBoost to get a good causal effect estimate for Economy is the feature’s strong independent component (in this simulation); its predictive power for retention is not strongly redundant with any other measured features, or with any unmeasured confounders. In consequence, it is not subject to bias from either unmeasured confounders or feature redundancy. Since we have added clustering to the right side of the SHAP bar plot we can see the redundancy structure of our data as a dendrogram. When features merge together at the bottom (left) of the dendrogram it means that that the information those features contain about the outcome (renewal) is very redundant and the model could have used either feature. When features merge together at the top (right) of the dendrogram it means the information they contain about the outcome is independent from each other. We can see that Economy is independent from all the other measured features by noting that Economy does not merge with any other features until the very top of the clustering dendrogram. This tells us that Economy does not suffer from observed confounding. But to trust that the Economy effect is causal we also need to check for unobserved confounding. Checking for unmeasured confounders is harder and requires using domain knowledge (provided by the business partners in our example above). For classic predictive ML models to deliver causal results the features need to be independent not only of other features in the model, but also of unobserved confounders. It’s not common to find examples of drivers of interest that exhibit this level of independence naturally, but we can often find examples of independent features when our data contains some experiments. In most real-world datasets features are not independent and unconfounded, so standard predictive models will not learn the true causal effects. As a result, explaining them with SHAP will not reveal causal effects. But all is not lost, sometimes we can fix or at least minimize this problem using the tools of observational causal inference. The first scenario where causal inference can help is observed confounding. A feature is “confounded” when there is another feature that causally affects both the original feature and the outcome we are predicting. If we can measure that other feature it is called an observed confounder. An example of this in our scenario is the Ad Spend feature. Even though Ad Spend has no direct causal effect on retention, it is correlated with the Last Upgrade and Monthly Usage features, which do drive retention. Our predictive model identifies Ad Spend as the one of the best single predictors of retention because it captures so many of the true causal drivers through correlations. XGBoost imposes regularization, which is a fancy way of saying that it tries to choose the simplest possible model that still predicts well. If it could predict equally well using one feature rather than three, it will tend to do that to avoid overfitting. But this means that if Ad Spend is highly correlated with both Last Upgrade and Monthly Usage, XGBoost may use Ad Spend instead of the causal features! This property of XGBoost (or any other machine learning model with regularization) is very useful for generating robust predictions of future retention, but not good for understanding which features we should manipulate if we want to increase retention. This highlights the importance of matching the right modeling tools to each question. Unlike the bug reporting example, there is nothing intuitively wrong with the conclusion that increasing ad spend increases retention. Without proper attention to what our predictive model is, and is not, measuring, we could easily have proceeded with this finding and only learned our mistake after increasing spending on advertising and not getting the renewal results we expected. The good news for Ad Spend is that we can measure all the features that could confound it (those features with arrows into Ad Spend in our causal graph above). Therefore, this is an example of observed confounding, and we should be able to disentangle the correlation patterns using only the data we’ve already collected; we just need to use the right tools from observational causal inference. These tools allow us to specify what features could confound Ad Spend and then adjust for those features, to get an unconfounded estimate of the causal effect of Ad Spend on product renewal. One particularly flexible tool for observational causal inference is double/debiased machine learning. It uses any machine learning model you want to first deconfound the feature of interest (i.e. Ad Spend) and then estimate the average causal effect of changing that feature (i.e. the average slope of the causal effect). Double ML works as follows: Train a model to predict a feature of interest (i.e. Ad Spend) using a set of possible confounders (i.e. any features not caused by Ad Spend).Train a model to predict the outcome (i.e. Did Renew) using the same set of possible confounders.Train a model to predict the residual variation of the outcome (the variation left after subtracting our prediction) using the residual variation of the causal feature of interest. Train a model to predict a feature of interest (i.e. Ad Spend) using a set of possible confounders (i.e. any features not caused by Ad Spend). Train a model to predict the outcome (i.e. Did Renew) using the same set of possible confounders. Train a model to predict the residual variation of the outcome (the variation left after subtracting our prediction) using the residual variation of the causal feature of interest. The intuition is that if Ad Spend causes renewal, then the part of Ad Spend that can’t be predicted by other confounding features should be correlated with the part of renewal that can’t be predicted by other confounding features. Stated another way, double ML assumes that there is an independent (unobserved) noise feature that impacts Ad Spend (since Ad Spend is not perfectly determined by the other features), so we can impute the value of this independent noise feature and then train a model on this independent feature to predict the output. While we could do all the double ML steps manually, it is easier to use a causal inference package like econML or CausalML. Here we use econML’s LinearDML model (see notebook for details). This returns a P-value of whether that treatment has a non-zero a causal effect, and works beautifully in our scenario, correctly identifying that there is no evidence for a causal effect of ad spending on renewal (P-value = 0.85): Remember, double ML (or any other observational causal inference method) only works when you can measure and identify all the possible confounders of the feature for which you want to estimate causal effects. Here we know the causal graph and can see that Monthly Usage and Last Upgrade are the two direct confounders we need to control for. But if we didn’t know the causal graph we could still look at the redundancy in the SHAP bar plot and see that Monthly Usage and Last Upgrade are the most redundant features and so are good candidates to control for (as are Discounts and Bugs Reported). The second scenario where causal inference can help is non-confounding redundancy. This occurs when the feature we want causal effects for causally drives, or is driven by, another feature included in the model, but that other feature is not a confounder of our feature of interest. An example of this is the Sales Calls feature. Sales Calls directly impact retention, but also have an indirect effect on retention through Interactions. When we include both the Interactions and Sales Calls features in the model the causal effect shared by both features is forced to spread out between them. We can see this in the SHAP scatter plots above, which show how XGBoost underestimates the true causal effect of Sales Calls because most of that effect got put onto the Interactions feature. Non-confounding redundancy can be fixed in principle by removing the redundant variables from the model (see notebook). For example, if we removed Interactions from the model then we will capture the full effect of making a sales call on renewal probability. This removal is also important for double ML, since double ML will fail to capture indirect causal effects if you control for downstream features caused by the feature of interest. In this case double ML will only measure the “direct” effect that does not pass through the other feature. Double ML is however robust to controlling for upstream non-confounding redundancy (where the redundant feature causes the feature of interest), though this will reduce your statistical power to detect true effects. Unfortunately, we often don’t know the true causal graph so it can be hard to know when another feature is redundant with our feature of interest because of observed confounding vs. non-confounding redundancy. If it is because of confounding then we should control for that feature using a method like double ML, whereas if it is a downstream consequence then we should drop the feature from our model if we want full causal effects rather than only direct effects. Controlling for a feature we shouldn’t tends to hide or split up causal effects, while failing to control for a feature we should have controlled for tends to infer causal effects that do not exist. This generally makes controlling for a feature the safer option when you are uncertain. Double ML (or any other causal inference method that assumes unconfoundedness) only works when you can measure and identify all the possible confounders of the feature for which you want to estimate causal effects. If you can’t measure all the confounders then you are in the hardest possible scenario: unobserved confounding. The Discount and Bugs Reported features both suffer from unobserved confounding because not all important variables (e.g., Product Need and Bugs Faced) are measured in the data. Even though both features are relatively independent of all the other features in the model, there are important drivers that are unmeasured. In this case, both predictive models and causal models that require confounders to be observed, like double ML, will fail. This is why double ML estimates a large negative causal effect for the Discount feature even when controlling for all other observed features: Barring the ability to measure the previously unmeasured features (or features correlated with them), finding causal effects in the presence of unobserved confounding is difficult. In these situations, the only way to identify causal effects that can inform policy is to create or exploit some randomization that breaks the correlation between the features of interest and the unmeasured confounders. Randomized experiments remain the gold standard for finding causal effects in this context. Specialized causal tools based on the principals of instrumental variables, differences-in-differences, or regression discontinuities can sometimes exploit partial randomization even in cases where a full experiment is impossible. For example, instrumental variable techniques can be used to identify causal effects in cases where we cannot randomly assign a treatment, but we can randomly nudge some customers towards treatment, like sending an email encouraging them to explore a new product feature. Difference-in-difference approaches can be helpful when the introduction of new treatments is staggered across groups. Finally, regression discontinuity approaches are a good option when patterns of treatment exhibit sharp cut-offs (for example qualification for treatment based on a specific, measurable trait like revenue over $5,000 per month). Flexible predictive models like XGBoost or LightGBM are powerful tools for solving prediction problems. However, they are not inherently causal models, so interpreting them with SHAP will fail to accurately answer causal questions in many common situations. Unless features in a model are the result of experimental variation, applying SHAP to predictive models without considering confounding is generally not an appropriate tool to measure causal impacts used to inform policy. SHAP and other interpretability tools can be useful for causal inference, and SHAP is integrated into many causal inference packages, but those use cases are explicitly causal in nature. To that end, using the same data we would collect for prediction problems and using causal inference methods like double ML that are particularly designed to return causal effects is often a good approach for informing policy. In other situations, only an experiment or other source of randomization can really answer what if questions. Causal inference always requires us to make important assumptions. The main point of this article is that the assumptions we make by interpreting a normal predictive model as causal are often unrealistic.
[ { "code": null, "e": 330, "s": 172, "text": "A joint article about causality and interpretable machine learning with Eleanor Dillon, Jacob LaRiviere, Jonathan Roth, and Vasilis Syrgkanis from Microsoft." }, { "code": null, "e": 1014, "s": 330, "text": "Predictive machine learning...
Kotlin Flow in Android with Example - GeeksforGeeks
16 Aug, 2021 Kotlin Flow is one of the latest addition to the Kotlin Coroutines. With Kotlin Flow we can handle streams of data asynchronously which is being executed sequentially. We will build a simple app that fetches some data from API and shows it on the screen. It’s a simple app demonstrating the Kotlin flow working. It will use MVVM architecture. Prerequisites: Good knowledge of AndroidKnowledge of KotlinBasics of MVVM ArchitectureBasics of Retrofit LibraryBasics of Kotlin coroutinesBasics of View Binding Good knowledge of Android Knowledge of Kotlin Basics of MVVM Architecture Basics of Retrofit Library Basics of Kotlin coroutines Basics of View Binding 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: Project Structure We will be following some patterns to keep our files. Create folders and files according to this project structure. Uses will be explained later in this article. Project structure Step 3: Add required dependencies Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. // Retrofit dependency implementation ‘com.squareup.retrofit2:retrofit:2.9.0’ // json convertor factory implementation ‘com.squareup.retrofit2:converter-gson:2.1.0’ // Coroutines(includes kotlin flow) implementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0’ // lifecycle components implementation ‘androidx.lifecycle:lifecycle-extensions:2.2.0’ implementation “androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1” implementation “androidx.lifecycle:lifecycle-runtime-ktx:2.3.1” Step 4: Working with the activity_main.xml Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".presentation.MainActivity"> <androidx.constraintlayout.widget.Guideline android:id="@+id/guideline2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" app:layout_constraintGuide_percent="0.3" /> <EditText android:id="@+id/search_edit_text" android:layout_width="0dp" android:layout_height="wrap_content" android:autofillHints="Search Comments By Id" android:inputType="numberSigned" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toLeftOf="@id/button" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Search" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <ProgressBar android:layout_width="match_parent" android:id="@+id/progress_bar" android:layout_height="wrap_content" app:layout_constraintBottom_toTopOf="@+id/textView" app:layout_constraintEnd_toEndOf="parent" android:visibility="gone" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/search_edit_text" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:layout_marginEnd="20dp" android:layout_marginRight="20dp" android:text="Comment Id" android:textStyle="bold" app:layout_constraintEnd_toStartOf="@+id/guideline2" app:layout_constraintHorizontal_bias="1.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/search_edit_text" /> <TextView android:id="@+id/comment_id_textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginLeft="20dp" android:layout_marginTop="20dp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="@+id/textView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toEndOf="@+id/guideline2" app:layout_constraintTop_toBottomOf="@id/search_edit_text" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:layout_marginEnd="20dp" android:layout_marginRight="20dp" android:text="Name" android:textStyle="bold" app:layout_constraintEnd_toStartOf="@+id/guideline2" app:layout_constraintHorizontal_bias="1.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/comment_id_textview" /> <TextView android:id="@+id/name_textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginLeft="20dp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="@+id/textView2" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toEndOf="@+id/guideline2" app:layout_constraintTop_toTopOf="@+id/textView2" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:layout_marginEnd="20dp" android:layout_marginRight="20dp" android:text="Email" android:textStyle="bold" app:layout_constraintEnd_toStartOf="@+id/guideline2" app:layout_constraintHorizontal_bias="1.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/name_textview" /> <TextView android:id="@+id/email_textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginLeft="20dp" android:layout_marginTop="20dp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="@+id/textView3" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toEndOf="@+id/guideline2" app:layout_constraintTop_toBottomOf="@id/name_textview" /> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:layout_marginEnd="20dp" android:layout_marginRight="20dp" android:text="Comment" android:textStyle="bold" app:layout_constraintEnd_toStartOf="@+id/guideline2" app:layout_constraintHorizontal_bias="1.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/email_textview" /> <TextView android:id="@+id/comment_textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginLeft="20dp" android:layout_marginTop="20dp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="@+id/textView4" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toEndOf="@+id/guideline2" app:layout_constraintTop_toBottomOf="@id/email_textview" /> </androidx.constraintlayout.widget.ConstraintLayout> It UI looks like this: Step 5: Working with the API We will be using https://jsonplaceholder.typicode.com/comments API, It gives some JSON data when id is passed as a path. For example, https://jsonplaceholder.typicode.com/comments/2 gives JSON which contains some random data. We will be using this data and show it on the screen using kotlin flow. Open model > CommentModel and create a model class to parse data that is received from the API. Example Response We need to create a dataclass for this response. Add the following code in CommentModel Kotlin data class CommentModel( val postId: Int?=null, val id: Int?=null, val email: String?=null, val name:String?=null, @SerializedName("body") val comment: String?=null) Creating API Interface We need to create an API interface to call the API using a retrofit. Open network > ApiService and add the following code Kotlin import retrofit2.http.GETimport retrofit2.http.Path interface ApiService { // Get method to call the api ,passing id as a path @GET("/comments/{id}") suspend fun getComments(@Path("id") id: Int): CommentModel} Let’s add some helper classes to handle the loading or error state of API. Open network > CommentApiState. Refer to the comment in the code for an explanation. Kotlin // A helper class to handle statesdata class CommentApiState<out T>(val status: Status, val data: T?, val message: String?) { companion object { // In case of Success,set status as // Success and data as the response fun <T> success(data: T?): CommentApiState<T> { return CommentApiState(Status.SUCCESS, data, null) } // In case of failure ,set state to Error , // add the error message,set data to null fun <T> error(msg: String): CommentApiState<T> { return CommentApiState(Status.ERROR, null, msg) } // When the call is loading set the state // as Loading and rest as null fun <T> loading(): CommentApiState<T> { return CommentApiState(Status.LOADING, null, null) } }} // An enum to store the// current state of api callenum class Status { SUCCESS, ERROR, LOADING} Open utils > AppConfig and add code to create API service, which will be used to make API calls. Kotlin import com.google.gson.GsonBuilderimport retrofit2.Retrofitimport retrofit2.converter.gson.GsonConverterFactory object AppConfig { // Base url of the api private const val BASE_URL = "https://jsonplaceholder.typicode.com/" // create retrofit service fun ApiService(): ApiService = Retrofit.Builder().baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create(GsonBuilder().create())) .build() .create(ApiService::class.java)} The API part of the App is complete. Now we need to work on ViewModel and repository. Step 6: Working with the Repository Open repository > CommentsRepository. Add the following code. Refer to the comments for an explanation. Kotlin class CommentsRepository(private val apiService: ApiService) { suspend fun getComment(id: Int): Flow<CommentApiState<CommentModel>> { return flow { // get the comment Data from the api val comment=apiService.getComments(id) // Emit this data wrapped in // the helper class [CommentApiState] emit(CommentApiState.success(comment)) }.flowOn(Dispatchers.IO) }} Step 7: Working with the ViewModel Open ViewModel > CommentViewModel.Add the following code. Refer to the comments for an explanation. Kotlin import androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScopeimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.catchimport kotlinx.coroutines.flow.collectimport kotlinx.coroutines.launch class CommentsViewModel : ViewModel() { // Create a Repository and pass the api // service we created in AppConfig file private val repository = CommentsRepository( AppConfig.ApiService() ) val commentState = MutableStateFlow( CommentApiState( Status.LOADING, CommentModel(), "" ) ) init { // Initiate a starting // search with comment Id 1 getNewComment(1) } // Function to get new Comments fun getNewComment(id: Int) { // Since Network Calls takes time,Set the // initial value to loading state commentState.value = CommentApiState.loading() // ApiCalls takes some time, So it has to be // run and background thread. Using viewModelScope // to call the api viewModelScope.launch { // Collecting the data emitted // by the function in repository repository.getComment(id) // If any errors occurs like 404 not found // or invalid query, set the state to error // State to show some info // on screen .catch { commentState.value = CommentApiState.error(it.message.toString()) } // If Api call is succeeded, set the State to Success // and set the response data to data received from api .collect { commentState.value = CommentApiState.success(it.data) } } }} we are almost done, we now need to call the API from view(MainActivity) and show the data on the screen. Step 8: Working with the view (MainActivity.kt) Open presentation > MainActivity.kt. Add the following code, refer to the comments for explanation. Kotlin import android.os.Bundleimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.core.view.isVisibleimport androidx.lifecycle.ViewModelProviderimport androidx.lifecycle.lifecycleScopeimport kotlinx.coroutines.flow.collectimport kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { // create a CommentsViewModel // variable to initialize it later private lateinit var viewModel: CommentsViewModel // create a view binding variable private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // instantiate view binding binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // initialize viewModel viewModel = ViewModelProvider(this).get(CommentsViewModel::class.java) // Listen for the button click event to search binding.button.setOnClickListener { // check to prevent api call with no parameters if (binding.searchEditText.text.isNullOrEmpty()) { Toast.makeText(this, "Query Can't be empty", Toast.LENGTH_SHORT).show() } else { // if Query isn't empty, make the api call viewModel.getNewComment(binding.searchEditText.text.toString().toInt()) } } // Since flow run asynchronously, // start listening on background thread lifecycleScope.launch { viewModel.commentState.collect { // When state to check the // state of received data when (it.status) { // If its loading state then // show the progress bar Status.LOADING -> { binding.progressBar.isVisible = true } // If api call was a success , Update the Ui with // data and make progress bar invisible Status.SUCCESS -> { binding.progressBar.isVisible = false // Received data can be null, put a check to prevent // null pointer exception it.data?.let { comment -> binding.commentIdTextview.text = comment.id.toString() binding.nameTextview.text = comment.name binding.emailTextview.text = comment.email binding.commentTextview.text = comment.comment } } // In case of error, show some data to user else -> { binding.progressBar.isVisible = false Toast.makeText(this@MainActivity, "${it.message}", Toast.LENGTH_SHORT).show() } } } } }} Now run the app, put some numbers and click search. Enter any number from 1-500, It will return a successful state. Output: Get the complete project from GitHub. sagartomar9927 Kotlin Android Picked Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Android Listview in Java with Example Retrofit with Kotlin Coroutine in Android Android UI Layouts Kotlin Array Retrofit with Kotlin Coroutine in Android Kotlin Setters and Getters
[ { "code": null, "e": 24725, "s": 24697, "text": "\n16 Aug, 2021" }, { "code": null, "e": 24894, "s": 24725, "text": "Kotlin Flow is one of the latest addition to the Kotlin Coroutines. With Kotlin Flow we can handle streams of data asynchronously which is being executed sequentia...
SQL Tryit Editor v1.6
WHERE ProductID = ALL (SELECT ProductID FROM OrderDetails WHERE Quantity = 10); ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, Opera, and Edge(79). If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 114, "s": 34, "text": "WHERE ProductID = ALL (SELECT ProductID FROM OrderDetails WHERE Quantity = 10);" }, { "code": null, "e": 116, "s": 114, "text": "​" }, { "code": null, "e": 179, "s": 116, "text": "Edit the SQL Statement, and click \"...