title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
IEEE-CIS Fraud Detection. Machine learning algorithms help to... | by Sohail Hosseini | Towards Data Science
In this work, we are going to classify whether an online transaction is fraudulent or not. It is a binary target, named: isFraud. A lot of us have been in a situation where a transaction has been canceled without our consideration. To have a better algorithm that only cancels the fraudulent transaction and doesn't just result in being embarrassed in a store. While it is often embarrassing at the moment, but this system is truly sparing consumers millions of dollars every year. The dataset is provided by Vesta’s real-world e-commerce transactions that includes a wide range of features from the country to the recipient email domain. With this dataset, we apply the Lightgbm algorithm on a challenging large e-scale dataset. Improving the effectiveness of fraudulent transaction warnings will save lots of people the trouble of false positive. If you would like to see an implementation in PySpark, read the next article. But how can we analyze these sorts of problems? The first step would be to download the dataset. The training set is used here, which has two sections. One is train_transcation and the other is train_identity. train_identity = pd.read_csv(‘../input/ieee-fraud-detection/train_identity.csv’)train_transaction = pd.read_csv(‘../input/ieee-fraud-detection/train_transaction.csv’) I am going to merge these two DataFrames on a column named “TransactionID”. But not all transactions have corresponding identity information. train_transaction_identity = train_transaction.merge(train_identity, on=’TransactionID’,how=’left’ ) The dataset contains several features that I only mention a few of them below. TransactionDT: timedelta from a given reference datetime (It is not actual time stamp) TransactionAMT: transaction payment amount in US Dollar (some of them exchanged from other currencies). card1 — card6: payment card information, such as card type. addr: address Please look at the data source link if you want to have a better understanding of features. As it is displayed below, memory usage is over 1.9+ GB. We can reduce memory usage without losing any data. train_transaction_identity.info() First, I have found out different types of features include Object, float, and Integer. By using .info in the Pandas library, you can find out the size of memory usage. The majority is occupied by float64. I have changed those columns from float64 to float32. As you can see memory usage is reduced by almost 50%. Most of the transactions are not fraud so in this case, we have unbalanced data. Machine learning algorithms do not work properly with an unbalanced dataset. A snippet of code is written below shows that only 3.5% are fraudulent. They are several methods to deal with an unbalanced dataset as oversampling and undersampling. Fortunately, Lightgbm can solve this matter for you. By default, the model thinks that the dataset is balanced. So in your case, we would need to change to the parameter as: is_unbalance = True By doing this, the “unbalance” mode uses the values of the target to automatically adjust weights inversely proportional to class frequencies in the input data. If we look at each column, we can see that if we have a lot of missing values. (np.sum(pd.isnull(train_transaction_identity)).sort_values(ascending=False)/len(train_transaction_identity))*100 The following figure shows that we have features with about 99% missing values. These columns do not add any values to our model. So we can remove them without losing much data. From all features, I have removed columns with more than 30% missing values. The code is written below for removing these unimportant features. Categorical data are the data that need only a limited number of possible values. Machine learning algorithms cannot work directly with categorical data and to use them, categories must be transformed into numbers first, before you can apply the learning algorithm on them. There several techniques to apply including OneHotEncoder, Replacing values. Here I am using Pandas get_dummy function to convert categorical variables into dummy/indicator variables. train_dummy = pd.get_dummies(train_transaction_identity, drop_first=True) There are several methods to deal with missing values like imputation, erase them. By default, Lightgbm has an option to deal with this problem. It ignores missing values during split finding, then allocates them to whichever side the decreases the loss the most. If you do not want to use option and apply other techniques, you would need to its parameter as: use_missing=false Feature scaling is one of the most important steps in machine learning algorithms during the pre-processing of data before creating a machine learning model. Most of the time, your dataset will include features highly varying in magnitudes, units, and range. But for most of the machine learning, using unscaled features create a problem. For instance, machine learning methods like linear regression, and neural networks that use gradient descent as an optimization algorithm need the dataset to be scaled. A similar problem happens when we use distance algorithms like K-means and SVM that are most affected by the range of features. The reason is that they are using distances between data points to determine their similarity. Fortunately, we do not need to be worried about its feature scaling. Tree-based algorithms are quite insensitive to the scale of the features. I have used 25% of the data for validation and the rest for training. There are a lot of hyperparameters involved here. So your job is like an architect to find the best values in order to maximize accuracy. There are several techniques that are really helpful including GridSearchCV and RandomizedSearchCV. As you can see there are a lot of parameters involved, but you want to understand what each parameter is please look at this link. As we can see below, we have got AUC for training data almost 98% and 94% for the validation dataset. It took around 5 minutes. You can increase “Number of boosting iterations” to have better AUC for the training/validation dataset. You can consider that or change other parameters to trade off accuracy and speed. You would be able to run Lightgbm on CPU. In order to do that, you just need to set the following parameter “device_type”:”gpu”. All the code used in this article can be accessed from my GitHub. I look forward to hearing feedback or questions.
[ { "code": null, "e": 529, "s": 47, "text": "In this work, we are going to classify whether an online transaction is fraudulent or not. It is a binary target, named: isFraud. A lot of us have been in a situation where a transaction has been canceled without our consideration. To have a better algorithm that only cancels the fraudulent transaction and doesn't just result in being embarrassed in a store. While it is often embarrassing at the moment, but this system is truly sparing consumers millions of dollars every year." }, { "code": null, "e": 974, "s": 529, "text": "The dataset is provided by Vesta’s real-world e-commerce transactions that includes a wide range of features from the country to the recipient email domain. With this dataset, we apply the Lightgbm algorithm on a challenging large e-scale dataset. Improving the effectiveness of fraudulent transaction warnings will save lots of people the trouble of false positive. If you would like to see an implementation in PySpark, read the next article." }, { "code": null, "e": 1022, "s": 974, "text": "But how can we analyze these sorts of problems?" }, { "code": null, "e": 1184, "s": 1022, "text": "The first step would be to download the dataset. The training set is used here, which has two sections. One is train_transcation and the other is train_identity." }, { "code": null, "e": 1351, "s": 1184, "text": "train_identity = pd.read_csv(‘../input/ieee-fraud-detection/train_identity.csv’)train_transaction = pd.read_csv(‘../input/ieee-fraud-detection/train_transaction.csv’)" }, { "code": null, "e": 1493, "s": 1351, "text": "I am going to merge these two DataFrames on a column named “TransactionID”. But not all transactions have corresponding identity information." }, { "code": null, "e": 1594, "s": 1493, "text": "train_transaction_identity = train_transaction.merge(train_identity, on=’TransactionID’,how=’left’ )" }, { "code": null, "e": 1673, "s": 1594, "text": "The dataset contains several features that I only mention a few of them below." }, { "code": null, "e": 1760, "s": 1673, "text": "TransactionDT: timedelta from a given reference datetime (It is not actual time stamp)" }, { "code": null, "e": 1864, "s": 1760, "text": "TransactionAMT: transaction payment amount in US Dollar (some of them exchanged from other currencies)." }, { "code": null, "e": 1924, "s": 1864, "text": "card1 — card6: payment card information, such as card type." }, { "code": null, "e": 1938, "s": 1924, "text": "addr: address" }, { "code": null, "e": 2030, "s": 1938, "text": "Please look at the data source link if you want to have a better understanding of features." }, { "code": null, "e": 2138, "s": 2030, "text": "As it is displayed below, memory usage is over 1.9+ GB. We can reduce memory usage without losing any data." }, { "code": null, "e": 2172, "s": 2138, "text": "train_transaction_identity.info()" }, { "code": null, "e": 2486, "s": 2172, "text": "First, I have found out different types of features include Object, float, and Integer. By using .info in the Pandas library, you can find out the size of memory usage. The majority is occupied by float64. I have changed those columns from float64 to float32. As you can see memory usage is reduced by almost 50%." }, { "code": null, "e": 2716, "s": 2486, "text": "Most of the transactions are not fraud so in this case, we have unbalanced data. Machine learning algorithms do not work properly with an unbalanced dataset. A snippet of code is written below shows that only 3.5% are fraudulent." }, { "code": null, "e": 2985, "s": 2716, "text": "They are several methods to deal with an unbalanced dataset as oversampling and undersampling. Fortunately, Lightgbm can solve this matter for you. By default, the model thinks that the dataset is balanced. So in your case, we would need to change to the parameter as:" }, { "code": null, "e": 3005, "s": 2985, "text": "is_unbalance = True" }, { "code": null, "e": 3166, "s": 3005, "text": "By doing this, the “unbalance” mode uses the values of the target to automatically adjust weights inversely proportional to class frequencies in the input data." }, { "code": null, "e": 3245, "s": 3166, "text": "If we look at each column, we can see that if we have a lot of missing values." }, { "code": null, "e": 3358, "s": 3245, "text": "(np.sum(pd.isnull(train_transaction_identity)).sort_values(ascending=False)/len(train_transaction_identity))*100" }, { "code": null, "e": 3536, "s": 3358, "text": "The following figure shows that we have features with about 99% missing values. These columns do not add any values to our model. So we can remove them without losing much data." }, { "code": null, "e": 3680, "s": 3536, "text": "From all features, I have removed columns with more than 30% missing values. The code is written below for removing these unimportant features." }, { "code": null, "e": 3954, "s": 3680, "text": "Categorical data are the data that need only a limited number of possible values. Machine learning algorithms cannot work directly with categorical data and to use them, categories must be transformed into numbers first, before you can apply the learning algorithm on them." }, { "code": null, "e": 4138, "s": 3954, "text": "There several techniques to apply including OneHotEncoder, Replacing values. Here I am using Pandas get_dummy function to convert categorical variables into dummy/indicator variables." }, { "code": null, "e": 4212, "s": 4138, "text": "train_dummy = pd.get_dummies(train_transaction_identity, drop_first=True)" }, { "code": null, "e": 4573, "s": 4212, "text": "There are several methods to deal with missing values like imputation, erase them. By default, Lightgbm has an option to deal with this problem. It ignores missing values during split finding, then allocates them to whichever side the decreases the loss the most. If you do not want to use option and apply other techniques, you would need to its parameter as:" }, { "code": null, "e": 4591, "s": 4573, "text": "use_missing=false" }, { "code": null, "e": 4930, "s": 4591, "text": "Feature scaling is one of the most important steps in machine learning algorithms during the pre-processing of data before creating a machine learning model. Most of the time, your dataset will include features highly varying in magnitudes, units, and range. But for most of the machine learning, using unscaled features create a problem." }, { "code": null, "e": 5322, "s": 4930, "text": "For instance, machine learning methods like linear regression, and neural networks that use gradient descent as an optimization algorithm need the dataset to be scaled. A similar problem happens when we use distance algorithms like K-means and SVM that are most affected by the range of features. The reason is that they are using distances between data points to determine their similarity." }, { "code": null, "e": 5465, "s": 5322, "text": "Fortunately, we do not need to be worried about its feature scaling. Tree-based algorithms are quite insensitive to the scale of the features." }, { "code": null, "e": 5673, "s": 5465, "text": "I have used 25% of the data for validation and the rest for training. There are a lot of hyperparameters involved here. So your job is like an architect to find the best values in order to maximize accuracy." }, { "code": null, "e": 5773, "s": 5673, "text": "There are several techniques that are really helpful including GridSearchCV and RandomizedSearchCV." }, { "code": null, "e": 5904, "s": 5773, "text": "As you can see there are a lot of parameters involved, but you want to understand what each parameter is please look at this link." }, { "code": null, "e": 6219, "s": 5904, "text": "As we can see below, we have got AUC for training data almost 98% and 94% for the validation dataset. It took around 5 minutes. You can increase “Number of boosting iterations” to have better AUC for the training/validation dataset. You can consider that or change other parameters to trade off accuracy and speed." }, { "code": null, "e": 6348, "s": 6219, "text": "You would be able to run Lightgbm on CPU. In order to do that, you just need to set the following parameter “device_type”:”gpu”." } ]
Collect Data from Twitter: A Step-by-Step Implementation Using Tweepy | by Zoumana Keita | Towards Data Science
Getting data comes as the second step in any data science/machine learning project lifecycle, right after framing the problem you want to solve, which would make this step be the backbone of the rest of the phases. Also, social media are great places to collect data, especially for competitor analysis, topic research, sentiment analysis, etc. This article aims to perform a step-by-step implementation on how to get credentials and the implementation on a simple use case. Twitter has 313,000,000 active users (Statista, 2017), which means that this method of data collection could reduce barriers to research participation based on the geographical location of researchers and research resources. It can also maximize resources, including time, effort, and convenience: Sage Journal Before performing any kind of analysis, the first action to perform is to get your Twitter authentication credentials, as described below. Get access to authentication credentials Sign up for developer account Sign up for developer account Here is the link that gives access to the following page. 2. Get your authentication credentials Once on this page, create a project and answer all the questions. Then you will get the following page with all the credentials. Make sure you don’t share this information with anyone. Implementation requirements Install the tweepy module pip install tweepy # install the tweepy module Import the required modules import tweepy # tweepy module to interact with Twitterimport pandas as pd # Pandas library to create dataframesfrom tweepy import OAuthHandler # Used for authenticationfrom tweepy import Cursor # Used to perform pagination Python implementation Implement utility functions to get tweets:There are three main functions in this example. (1) An authentication function. (2) A client function in order to interact with the Twitter API. (3) A final function that collects tweets and creates a data frame containing some specific information about a given Twitter account. The information collected are the following: > the date the tweet was created > the author of the tweet> the screen name corresponding to the name on the Twitter account> number of likes obtained by that tweet> number of retweets from the tweet """Twitter Authentification CredentialsPlease update with your own credentials"""cons_key = ''cons_secret = ''acc_token = ''acc_secret = ''# (1). Athentication Functiondef get_twitter_auth(): """ @return: - the authentification to Twitter """ try: consumer_key = cons_key consumer_secret = cons_secret access_token = acc_token access_secret = acc_secret except KeyError: sys.stderr.write("Twitter Environment Variable not Set\n") sys.exit(1) auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) return auth# (2). Client function to access the authentication APIdef get_twitter_client(): """ @return: - the client to access the authentification API """ auth = get_twitter_auth() client = tweepy.API(auth, wait_on_rate_limit=True) return client# (3). Function creating final dataframedef get_tweets_from_user(twitter_user_name, page_limit=16, count_tweet=200): """ @params: - twitter_user_name: the twitter username of a user (company, etc.) - page_limit: the total number of pages (max=16) - count_tweet: maximum number to be retrieved from a page @return - all the tweets from the user twitter_user_name """ client = get_twitter_client() all_tweets = [] for page in Cursor(client.user_timeline, screen_name=twitter_user_name, count=count_tweet).pages(page_limit): for tweet in page: parsed_tweet = {} parsed_tweet['date'] = tweet.created_at parsed_tweet['author'] = tweet.user.name parsed_tweet['twitter_name'] = tweet.user.screen_name parsed_tweet['text'] = tweet.text parsed_tweet['number_of_likes'] = tweet.favorite_count parsed_tweet['number_of_retweets'] = tweet.retweet_count all_tweets.append(parsed_tweet) # Create dataframe df = pd.DataFrame(all_tweets) # Revome duplicates if there are any df = df.drop_duplicates( "text" , keep='first') return df All the functions are finally implemented, now we can continue with data collection. Let’s say we want to collect tweets from Google AI. The function creating the data frame takes the Twitter username/screen name as a mandatory parameter, in this case, it is GoogleAI, without the @ sign. googleAI = get_tweets_from_user("GoogleAI")print("Data Shape: {}".format(googleAI.shape)) The print instruction shows Data Shape: (1743, 6) meaning we have 1743 tweets from Google AI, and the following.head(10) gives the first 10 tweets in the data frame googleAI.head(10) Advantages Well written documentation, with a very active community Provides many features about a given tweet (e.g. information about a tweet’s geographical location, etc.) Disadvantages Limits the user to the last 3200 tweets in a timeline. In this article, you have learned how to get your Twitter developer credentials, and how to use tweepy to get data from Twitter. Also, you have learned about the limitations and benefits of this tool. For further readings do not hesitate to consult the following links: Source code on Github Twitter Developer Documentation Tweepy documentation Twint documentation How to get access to the Twitter API Using Twitter for data collection with health-care consumers: a scoping review Bye for now 🏃🏾
[ { "code": null, "e": 647, "s": 172, "text": "Getting data comes as the second step in any data science/machine learning project lifecycle, right after framing the problem you want to solve, which would make this step be the backbone of the rest of the phases. Also, social media are great places to collect data, especially for competitor analysis, topic research, sentiment analysis, etc. This article aims to perform a step-by-step implementation on how to get credentials and the implementation on a simple use case." }, { "code": null, "e": 958, "s": 647, "text": "Twitter has 313,000,000 active users (Statista, 2017), which means that this method of data collection could reduce barriers to research participation based on the geographical location of researchers and research resources. It can also maximize resources, including time, effort, and convenience: Sage Journal" }, { "code": null, "e": 1097, "s": 958, "text": "Before performing any kind of analysis, the first action to perform is to get your Twitter authentication credentials, as described below." }, { "code": null, "e": 1138, "s": 1097, "text": "Get access to authentication credentials" }, { "code": null, "e": 1168, "s": 1138, "text": "Sign up for developer account" }, { "code": null, "e": 1198, "s": 1168, "text": "Sign up for developer account" }, { "code": null, "e": 1256, "s": 1198, "text": "Here is the link that gives access to the following page." }, { "code": null, "e": 1295, "s": 1256, "text": "2. Get your authentication credentials" }, { "code": null, "e": 1480, "s": 1295, "text": "Once on this page, create a project and answer all the questions. Then you will get the following page with all the credentials. Make sure you don’t share this information with anyone." }, { "code": null, "e": 1508, "s": 1480, "text": "Implementation requirements" }, { "code": null, "e": 1534, "s": 1508, "text": "Install the tweepy module" }, { "code": null, "e": 1581, "s": 1534, "text": "pip install tweepy # install the tweepy module" }, { "code": null, "e": 1609, "s": 1581, "text": "Import the required modules" }, { "code": null, "e": 1832, "s": 1609, "text": "import tweepy # tweepy module to interact with Twitterimport pandas as pd # Pandas library to create dataframesfrom tweepy import OAuthHandler # Used for authenticationfrom tweepy import Cursor # Used to perform pagination" }, { "code": null, "e": 1854, "s": 1832, "text": "Python implementation" }, { "code": null, "e": 2421, "s": 1854, "text": "Implement utility functions to get tweets:There are three main functions in this example. (1) An authentication function. (2) A client function in order to interact with the Twitter API. (3) A final function that collects tweets and creates a data frame containing some specific information about a given Twitter account. The information collected are the following: > the date the tweet was created > the author of the tweet> the screen name corresponding to the name on the Twitter account> number of likes obtained by that tweet> number of retweets from the tweet" }, { "code": null, "e": 4605, "s": 2421, "text": "\"\"\"Twitter Authentification CredentialsPlease update with your own credentials\"\"\"cons_key = ''cons_secret = ''acc_token = ''acc_secret = ''# (1). Athentication Functiondef get_twitter_auth(): \"\"\" @return: - the authentification to Twitter \"\"\" try: consumer_key = cons_key consumer_secret = cons_secret access_token = acc_token access_secret = acc_secret except KeyError: sys.stderr.write(\"Twitter Environment Variable not Set\\n\") sys.exit(1) auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) return auth# (2). Client function to access the authentication APIdef get_twitter_client(): \"\"\" @return: - the client to access the authentification API \"\"\" auth = get_twitter_auth() client = tweepy.API(auth, wait_on_rate_limit=True) return client# (3). Function creating final dataframedef get_tweets_from_user(twitter_user_name, page_limit=16, count_tweet=200): \"\"\" @params: - twitter_user_name: the twitter username of a user (company, etc.) - page_limit: the total number of pages (max=16) - count_tweet: maximum number to be retrieved from a page @return - all the tweets from the user twitter_user_name \"\"\" client = get_twitter_client() all_tweets = [] for page in Cursor(client.user_timeline, screen_name=twitter_user_name, count=count_tweet).pages(page_limit): for tweet in page: parsed_tweet = {} parsed_tweet['date'] = tweet.created_at parsed_tweet['author'] = tweet.user.name parsed_tweet['twitter_name'] = tweet.user.screen_name parsed_tweet['text'] = tweet.text parsed_tweet['number_of_likes'] = tweet.favorite_count parsed_tweet['number_of_retweets'] = tweet.retweet_count all_tweets.append(parsed_tweet) # Create dataframe df = pd.DataFrame(all_tweets) # Revome duplicates if there are any df = df.drop_duplicates( \"text\" , keep='first') return df" }, { "code": null, "e": 4894, "s": 4605, "text": "All the functions are finally implemented, now we can continue with data collection. Let’s say we want to collect tweets from Google AI. The function creating the data frame takes the Twitter username/screen name as a mandatory parameter, in this case, it is GoogleAI, without the @ sign." }, { "code": null, "e": 4984, "s": 4894, "text": "googleAI = get_tweets_from_user(\"GoogleAI\")print(\"Data Shape: {}\".format(googleAI.shape))" }, { "code": null, "e": 5149, "s": 4984, "text": "The print instruction shows Data Shape: (1743, 6) meaning we have 1743 tweets from Google AI, and the following.head(10) gives the first 10 tweets in the data frame" }, { "code": null, "e": 5167, "s": 5149, "text": "googleAI.head(10)" }, { "code": null, "e": 5178, "s": 5167, "text": "Advantages" }, { "code": null, "e": 5235, "s": 5178, "text": "Well written documentation, with a very active community" }, { "code": null, "e": 5341, "s": 5235, "text": "Provides many features about a given tweet (e.g. information about a tweet’s geographical location, etc.)" }, { "code": null, "e": 5355, "s": 5341, "text": "Disadvantages" }, { "code": null, "e": 5410, "s": 5355, "text": "Limits the user to the last 3200 tweets in a timeline." }, { "code": null, "e": 5611, "s": 5410, "text": "In this article, you have learned how to get your Twitter developer credentials, and how to use tweepy to get data from Twitter. Also, you have learned about the limitations and benefits of this tool." }, { "code": null, "e": 5680, "s": 5611, "text": "For further readings do not hesitate to consult the following links:" }, { "code": null, "e": 5702, "s": 5680, "text": "Source code on Github" }, { "code": null, "e": 5734, "s": 5702, "text": "Twitter Developer Documentation" }, { "code": null, "e": 5755, "s": 5734, "text": "Tweepy documentation" }, { "code": null, "e": 5775, "s": 5755, "text": "Twint documentation" }, { "code": null, "e": 5812, "s": 5775, "text": "How to get access to the Twitter API" }, { "code": null, "e": 5891, "s": 5812, "text": "Using Twitter for data collection with health-care consumers: a scoping review" } ]
Lifecycle in Android Architecture Components
23 Mar, 2021 Lifecycle is one of the Android Architecture Components which was released by Google to make it easier for all the Android developers. The Lifecycle is a class/interface which holds the information about the state of an activity/fragment and also it allows other objects to observe this state by keeping track of it. The LifeCycle component is concerned with the Android LifeCycle events of a component such as an Activity or a Fragment, it has three main classes that we’ll deal with: LifecycleLifecycle OwnerLifecycle Observer Lifecycle Lifecycle Owner Lifecycle Observer Lifecycle is a process that tells us about the Events performed on an Activity/Fragment. We have a lifecycle as a class that has two types of enumerations to track the components, State and Event. Event and State are used to determine the lifecycle. Each event has its own state. Event State Within the Lifecycle Events, you can declare how your activity behaves when the user leaves and re-enters the activity. Example: If you’re watching a Youtube video, you might pause the video and terminates the network connection when the user switches to another app. When the user returns, you can reconnect to the network and allow the user to resume the video from the same spot. Every Activity has a Lifecycle. This Activity will be a Lifecycle Owner(any activity or fragment can be called a lifecycle owner). When an activity is initialized LifecycleOwner is the one that will be constructed initially. Any class that implements the LifeCycleOwner interface indicates that it has Android LifeCycle. For example, starting from Support Library 26.1.0 Fragments and Activities implement the LifeCycleOwner interface. One can create custom LifeCycleOwner components by implementing the interface and using a LifeCycleRegistry as described here. Lifecycle Observer, which observes the activity and keeps track of the lifecycle, and performs an action. The action performed by this lifecycle Observer depends on the lifecycle of the lifecycle Owner. Every lifecycle owner has a lifecycle and based on the event or state of the lifecycle of the owner, the lifecycle observer performs the action. Java import android.os.Bundle;import android.util.Log;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.e("lifecycle", "onCreate invoked"); } @Override protected void onStart() { super.onStart(); Log.e("lifecycle", "onStart invoked"); } @Override protected void onResume() { super.onResume(); Log.e("lifecycle", "onResume invoked"); } @Override protected void onPause() { super.onPause(); Log.e("lifecycle", "onPause invoked"); } @Override protected void onStop() { super.onStop(); Log.e("lifecycle", "onStop invoked"); } @Override protected void onRestart() { super.onRestart(); Log.e("lifecycle", "onRestart invoked"); } @Override protected void onDestroy() { super.onDestroy(); Log.e("lifecycle", "onDestroy invoked"); }} You will not see any output on the emulator or device. You need to open logcat window. Now see on the logcat: OnCreate, OnStart, and OnResume methods are invoked. Now click on the HOME button. You will see on the Pause method is invoked. After a while, you will see onStop method is invoked. Now see on the emulator. It is on the home. Now click on the center button to launch the app again. Now click on the app icon. Now see on the logcat: onRestart, onStart and onResume methods are invoked. If you see on the emulator, the application is started again. Now click on the back button. Now you will see onPause methods are invoked. After a while, you will see onStop and Destroy methods are invoked. Android-Jetpack Picked Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Mar, 2021" }, { "code": null, "e": 514, "s": 28, "text": "Lifecycle is one of the Android Architecture Components which was released by Google to make it easier for all the Android developers. The Lifecycle is a class/interface which holds the information about the state of an activity/fragment and also it allows other objects to observe this state by keeping track of it. The LifeCycle component is concerned with the Android LifeCycle events of a component such as an Activity or a Fragment, it has three main classes that we’ll deal with:" }, { "code": null, "e": 557, "s": 514, "text": "LifecycleLifecycle OwnerLifecycle Observer" }, { "code": null, "e": 567, "s": 557, "text": "Lifecycle" }, { "code": null, "e": 583, "s": 567, "text": "Lifecycle Owner" }, { "code": null, "e": 602, "s": 583, "text": "Lifecycle Observer" }, { "code": null, "e": 882, "s": 602, "text": "Lifecycle is a process that tells us about the Events performed on an Activity/Fragment. We have a lifecycle as a class that has two types of enumerations to track the components, State and Event. Event and State are used to determine the lifecycle. Each event has its own state." }, { "code": null, "e": 891, "s": 882, "text": " Event" }, { "code": null, "e": 919, "s": 891, "text": " State" }, { "code": null, "e": 1044, "s": 924, "text": "Within the Lifecycle Events, you can declare how your activity behaves when the user leaves and re-enters the activity." }, { "code": null, "e": 1054, "s": 1044, "text": "Example: " }, { "code": null, "e": 1308, "s": 1054, "text": "If you’re watching a Youtube video, you might pause the video and terminates the network connection when the user switches to another app. When the user returns, you can reconnect to the network and allow the user to resume the video from the same spot." }, { "code": null, "e": 1871, "s": 1308, "text": "Every Activity has a Lifecycle. This Activity will be a Lifecycle Owner(any activity or fragment can be called a lifecycle owner). When an activity is initialized LifecycleOwner is the one that will be constructed initially. Any class that implements the LifeCycleOwner interface indicates that it has Android LifeCycle. For example, starting from Support Library 26.1.0 Fragments and Activities implement the LifeCycleOwner interface. One can create custom LifeCycleOwner components by implementing the interface and using a LifeCycleRegistry as described here." }, { "code": null, "e": 2219, "s": 1871, "text": "Lifecycle Observer, which observes the activity and keeps track of the lifecycle, and performs an action. The action performed by this lifecycle Observer depends on the lifecycle of the lifecycle Owner. Every lifecycle owner has a lifecycle and based on the event or state of the lifecycle of the owner, the lifecycle observer performs the action." }, { "code": null, "e": 2224, "s": 2219, "text": "Java" }, { "code": "import android.os.Bundle;import android.util.Log;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.e(\"lifecycle\", \"onCreate invoked\"); } @Override protected void onStart() { super.onStart(); Log.e(\"lifecycle\", \"onStart invoked\"); } @Override protected void onResume() { super.onResume(); Log.e(\"lifecycle\", \"onResume invoked\"); } @Override protected void onPause() { super.onPause(); Log.e(\"lifecycle\", \"onPause invoked\"); } @Override protected void onStop() { super.onStop(); Log.e(\"lifecycle\", \"onStop invoked\"); } @Override protected void onRestart() { super.onRestart(); Log.e(\"lifecycle\", \"onRestart invoked\"); } @Override protected void onDestroy() { super.onDestroy(); Log.e(\"lifecycle\", \"onDestroy invoked\"); }}", "e": 3314, "s": 2224, "text": null }, { "code": null, "e": 3401, "s": 3314, "text": "You will not see any output on the emulator or device. You need to open logcat window." }, { "code": null, "e": 3606, "s": 3401, "text": "Now see on the logcat: OnCreate, OnStart, and OnResume methods are invoked. Now click on the HOME button. You will see on the Pause method is invoked. After a while, you will see onStop method is invoked." }, { "code": null, "e": 3733, "s": 3606, "text": "Now see on the emulator. It is on the home. Now click on the center button to launch the app again. Now click on the app icon." }, { "code": null, "e": 4016, "s": 3733, "text": "Now see on the logcat: onRestart, onStart and onResume methods are invoked. If you see on the emulator, the application is started again. Now click on the back button. Now you will see onPause methods are invoked. After a while, you will see onStop and Destroy methods are invoked." }, { "code": null, "e": 4032, "s": 4016, "text": "Android-Jetpack" }, { "code": null, "e": 4039, "s": 4032, "text": "Picked" }, { "code": null, "e": 4047, "s": 4039, "text": "Android" }, { "code": null, "e": 4055, "s": 4047, "text": "Android" } ]
md5sum Command in Linux with Examples
23 May, 2019 The md5sum is designed to verify data integrity using MD5 (Message Digest Algorithm 5). MD5 is 128-bit cryptographic hash and if used properly it can be used to verify file authenticity and integrity. Example : Input : md5sum /home/mandeep/test/test.cpp Output : c6779ec2960296ed9a04f08d67f64422 /home/mandeep/test/test.cpp Importance :Suppose, anyone wants to install an operating system , so to verify if it’s correct CD, it’s always a good idea to verify .iso file using MD5 checksum, so that you don’t end up installing wrong software (some sort of virus which can corrupt your filesystem). Syntax : md5sum [OPTION]... [FILE]... It will print or check MD5(128-bit) checksum. It computes MD5 checksum for file “test.cpp”Output : c6779ec2960296ed9a04f08d67f64422 /home/mandeep/test/test.cpp Options :-b : read in binary mode-c : read MD5 from files and check them–tag : create a BSD-style checksum-t : read in text mode(it’s by default) The options which are useful when verifying checksum :–ignore-missing : don’t report status for missing files–quiet : don’t print OK for each successfully verified file–status : don’t output anything, status code shows success–strict : exit non-zero for improperly formatted checksum files-w : warn about improperly formatted checksum files Command usage examples with options : Example 1: Store the MD5 checksum in file and then verify it. # md5sum /home/mandeep/test/test.cpp > checkmd5.md5 It will store the MD5 checksum for test.cpp in file checkmd5.md5 # md5sum -c checkmd5.md5 It will verify the contents of file Output : /home/mandeep/test/test.cpp: OK After changing the contents of file checkmd5.md5, the output will be : /home/mandeep/test/test.cpp: FAILED md5sum: WARNING: 1 computed checksum did NOT match Example 2: create a BSD-style checksum with –tag option # md5sum --tag /home/mandeep/test/test.cpp Output : MD5 (/home/mandeep/test/test.cpp) = c6779ec2960296ed9a04f08d67f64422 Example 3: –quiet option, can be used when verifying checksum, don’t print OK when verification is successful. # md5sum -c --quiet checkmd5.md5 Don’t produce any output, means it’s successful. But if checksum don’t match, it produces warning. # md5sum -c --quiet checkmd5.md5 /home/mandeep/test/test.cpp: FAILED md5sum: WARNING: 1 computed checksum did NOT match Example 4: –warn option, it can be used for generating a warning for improperly formatted checksum files. content of file checkmd5.md5: c6779ec2960296ed9a04f08d67f64422 /home/mandeep/test/test.cpp Now, execute command with –warn option # md5sum -c --warn checkmd5.md5 /home/mandeep/test/test.cpp: OK It don’t produce any warning. Now, do some formatting in file checkmd5.md5 c6779ec2960296ed9a04f08d67f64422 /home/mandeep/test/test.cpp Now, execute the command # md5sum -c --warn checkmd5.md5 Output : md5sum: checkmd5.md5: 1: improperly formatted MD5 checksum line md5sum: checkmd5.md5: 2: improperly formatted MD5 checksum line md5sum: checkmd5.md5: no properly formatted MD5 checksum lines found and if –warn is replaced with –strict option, it will exit non-zero for improperly formatted checksum lines # md5sum -c --strict checkmd5.md5 md5sum: checkmd5.md5: no properly formatted MD5 checksum lines found – Mandeep Singh References :1) md5sum wikipedia2) linux man page linux-command Linux-misc-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script Tail command in Linux with examples Docker - COPY Instruction UDP Server-Client implementation in C scp command in Linux with Examples echo command in Linux with Examples Cat command in Linux with examples touch command in Linux with Examples
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2019" }, { "code": null, "e": 116, "s": 28, "text": "The md5sum is designed to verify data integrity using MD5 (Message Digest Algorithm 5)." }, { "code": null, "e": 229, "s": 116, "text": "MD5 is 128-bit cryptographic hash and if used properly it can be used to verify file authenticity and integrity." }, { "code": null, "e": 239, "s": 229, "text": "Example :" }, { "code": null, "e": 355, "s": 239, "text": "Input : md5sum /home/mandeep/test/test.cpp\nOutput : c6779ec2960296ed9a04f08d67f64422 /home/mandeep/test/test.cpp\n\n" }, { "code": null, "e": 626, "s": 355, "text": "Importance :Suppose, anyone wants to install an operating system , so to verify if it’s correct CD, it’s always a good idea to verify .iso file using MD5 checksum, so that you don’t end up installing wrong software (some sort of virus which can corrupt your filesystem)." }, { "code": null, "e": 635, "s": 626, "text": "Syntax :" }, { "code": null, "e": 665, "s": 635, "text": "md5sum [OPTION]... [FILE]...\n" }, { "code": null, "e": 711, "s": 665, "text": "It will print or check MD5(128-bit) checksum." }, { "code": null, "e": 764, "s": 711, "text": "It computes MD5 checksum for file “test.cpp”Output :" }, { "code": null, "e": 827, "s": 764, "text": "c6779ec2960296ed9a04f08d67f64422 /home/mandeep/test/test.cpp\n" }, { "code": null, "e": 973, "s": 827, "text": "Options :-b : read in binary mode-c : read MD5 from files and check them–tag : create a BSD-style checksum-t : read in text mode(it’s by default)" }, { "code": null, "e": 1314, "s": 973, "text": "The options which are useful when verifying checksum :–ignore-missing : don’t report status for missing files–quiet : don’t print OK for each successfully verified file–status : don’t output anything, status code shows success–strict : exit non-zero for improperly formatted checksum files-w : warn about improperly formatted checksum files" }, { "code": null, "e": 1352, "s": 1314, "text": "Command usage examples with options :" }, { "code": null, "e": 1414, "s": 1352, "text": "Example 1: Store the MD5 checksum in file and then verify it." }, { "code": null, "e": 1467, "s": 1414, "text": "# md5sum /home/mandeep/test/test.cpp > checkmd5.md5\n" }, { "code": null, "e": 1532, "s": 1467, "text": "It will store the MD5 checksum for test.cpp in file checkmd5.md5" }, { "code": null, "e": 1558, "s": 1532, "text": "# md5sum -c checkmd5.md5\n" }, { "code": null, "e": 1594, "s": 1558, "text": "It will verify the contents of file" }, { "code": null, "e": 1603, "s": 1594, "text": "Output :" }, { "code": null, "e": 1636, "s": 1603, "text": "/home/mandeep/test/test.cpp: OK\n" }, { "code": null, "e": 1707, "s": 1636, "text": "After changing the contents of file checkmd5.md5, the output will be :" }, { "code": null, "e": 1795, "s": 1707, "text": "/home/mandeep/test/test.cpp: FAILED\nmd5sum: WARNING: 1 computed checksum did NOT match\n" }, { "code": null, "e": 1851, "s": 1795, "text": "Example 2: create a BSD-style checksum with –tag option" }, { "code": null, "e": 1895, "s": 1851, "text": "# md5sum --tag /home/mandeep/test/test.cpp\n" }, { "code": null, "e": 1904, "s": 1895, "text": "Output :" }, { "code": null, "e": 1974, "s": 1904, "text": "MD5 (/home/mandeep/test/test.cpp) = c6779ec2960296ed9a04f08d67f64422\n" }, { "code": null, "e": 2085, "s": 1974, "text": "Example 3: –quiet option, can be used when verifying checksum, don’t print OK when verification is successful." }, { "code": null, "e": 2122, "s": 2085, "text": "# md5sum -c --quiet checkmd5.md5 \n" }, { "code": null, "e": 2171, "s": 2122, "text": "Don’t produce any output, means it’s successful." }, { "code": null, "e": 2221, "s": 2171, "text": "But if checksum don’t match, it produces warning." }, { "code": null, "e": 2343, "s": 2221, "text": "# md5sum -c --quiet checkmd5.md5\n/home/mandeep/test/test.cpp: FAILED\nmd5sum: WARNING: 1 computed checksum did NOT match\n" }, { "code": null, "e": 2449, "s": 2343, "text": "Example 4: –warn option, it can be used for generating a warning for improperly formatted checksum files." }, { "code": null, "e": 2479, "s": 2449, "text": "content of file checkmd5.md5:" }, { "code": null, "e": 2541, "s": 2479, "text": "c6779ec2960296ed9a04f08d67f64422 /home/mandeep/test/test.cpp\n" }, { "code": null, "e": 2580, "s": 2541, "text": "Now, execute command with –warn option" }, { "code": null, "e": 2646, "s": 2580, "text": "# md5sum -c --warn checkmd5.md5\n/home/mandeep/test/test.cpp: OK\n" }, { "code": null, "e": 2676, "s": 2646, "text": "It don’t produce any warning." }, { "code": null, "e": 2721, "s": 2676, "text": "Now, do some formatting in file checkmd5.md5" }, { "code": null, "e": 2784, "s": 2721, "text": "c6779ec2960296ed9a04f08d67f64422 \n/home/mandeep/test/test.cpp\n" }, { "code": null, "e": 2809, "s": 2784, "text": "Now, execute the command" }, { "code": null, "e": 2843, "s": 2809, "text": "# md5sum -c --warn checkmd5.md5\n" }, { "code": null, "e": 2852, "s": 2843, "text": "Output :" }, { "code": null, "e": 3050, "s": 2852, "text": "md5sum: checkmd5.md5: 1: improperly formatted MD5 checksum line\nmd5sum: checkmd5.md5: 2: improperly formatted MD5 checksum line\nmd5sum: checkmd5.md5: no properly formatted MD5 checksum lines found\n" }, { "code": null, "e": 3158, "s": 3050, "text": "and if –warn is replaced with –strict option, it will exit non-zero for improperly formatted checksum lines" }, { "code": null, "e": 3263, "s": 3158, "text": "# md5sum -c --strict checkmd5.md5\nmd5sum: checkmd5.md5: no properly formatted MD5 checksum lines found\n" }, { "code": null, "e": 3279, "s": 3263, "text": "– Mandeep Singh" }, { "code": null, "e": 3328, "s": 3279, "text": "References :1) md5sum wikipedia2) linux man page" }, { "code": null, "e": 3342, "s": 3328, "text": "linux-command" }, { "code": null, "e": 3362, "s": 3342, "text": "Linux-misc-commands" }, { "code": null, "e": 3373, "s": 3362, "text": "Linux-Unix" }, { "code": null, "e": 3471, "s": 3373, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3506, "s": 3471, "text": "tar command in Linux with examples" }, { "code": null, "e": 3542, "s": 3506, "text": "curl command in Linux with Examples" }, { "code": null, "e": 3580, "s": 3542, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 3616, "s": 3580, "text": "Tail command in Linux with examples" }, { "code": null, "e": 3642, "s": 3616, "text": "Docker - COPY Instruction" }, { "code": null, "e": 3680, "s": 3642, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 3715, "s": 3680, "text": "scp command in Linux with Examples" }, { "code": null, "e": 3751, "s": 3715, "text": "echo command in Linux with Examples" }, { "code": null, "e": 3786, "s": 3751, "text": "Cat command in Linux with examples" } ]
How to Install Julia Programming Language on Linux ?
19 Feb, 2020 Julia is a programming language used for mathematical computations and scientific data analysis. Julia is an open-source high-performance language that is used to perform statistical calculations and general-purpose programming. Julia programs can be written in any of the widely used text editors like Notepad, Notepad++, gedit, etc. or on any of the text-editors. One can also use an online IDE for writing Julia codes or can even install one on their system to make it more feasible to write these codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc.To begin with, writing Julia Codes and performing various intriguing and useful operations, one must have Julia installed on their System. This can be done by following the step by step instructions provided below: Before we begin with the installation of Julia, it is good to check if it might be already installed on your system. To check if your device is preinstalled with Julia or not, just go to the terminal and type: julia Julia can be downloaded and installed in Linux with the use of a package manager known as ‘Snaps’. Follow the steps given below to install Snaps and Julia in a Linux system using command-line: Step 1: Open Terminal, type the following command and press Enter. sudo apt install snapd Step 2: Wait for the Snap package to unpack the files and install them in the registry. Step 3: Once the installation of Snap is over, clear the terminal and begin with the Julia Installation process. Step 4: Use the following command to install Julia and then press Enter. Step 5: Now Terminal will download Julia online and will begin with the installation process Step 6: Mounting Julia on the Destination Drive after completing the download. Step 7: Installation of Julia is now over, you can proceed with the next step to Start Julia compiler and begin with writing Julia programming codes. Step 8: Enter the following command to begin with the Julia compiler and to confirm if the installation is completed successfully. Type the following command and press Enter: julia After completing the installation process, any IDE or text editor can be used to write Julia Codes and Run them on the IDE or the terminal with the use of command: julia file_name.jl Let’s consider a simple Hello World Program. # Julia program to print Hello World # print functionprintln("Hello World !") Output: Julia-Basics Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Vectors in Julia Getting rounded value of a number in Julia - round() Method Storing Output on a File in Julia Reshaping array dimensions in Julia | Array reshape() Method Manipulating matrices in Julia Exception handling in Julia Creating array with repeated elements in Julia - repeat() Method while loop in Julia Tuples in Julia Get array dimensions and size of a dimension in Julia - size() Method
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Feb, 2020" }, { "code": null, "e": 257, "s": 28, "text": "Julia is a programming language used for mathematical computations and scientific data analysis. Julia is an open-source high-performance language that is used to perform statistical calculations and general-purpose programming." }, { "code": null, "e": 841, "s": 257, "text": "Julia programs can be written in any of the widely used text editors like Notepad, Notepad++, gedit, etc. or on any of the text-editors. One can also use an online IDE for writing Julia codes or can even install one on their system to make it more feasible to write these codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc.To begin with, writing Julia Codes and performing various intriguing and useful operations, one must have Julia installed on their System. This can be done by following the step by step instructions provided below:" }, { "code": null, "e": 1051, "s": 841, "text": "Before we begin with the installation of Julia, it is good to check if it might be already installed on your system. To check if your device is preinstalled with Julia or not, just go to the terminal and type:" }, { "code": null, "e": 1057, "s": 1051, "text": "julia" }, { "code": null, "e": 1317, "s": 1057, "text": "Julia can be downloaded and installed in Linux with the use of a package manager known as ‘Snaps’. Follow the steps given below to install Snaps and Julia in a Linux system using command-line: Step 1: Open Terminal, type the following command and press Enter." }, { "code": null, "e": 1340, "s": 1317, "text": "sudo apt install snapd" }, { "code": null, "e": 2112, "s": 1340, "text": " Step 2: Wait for the Snap package to unpack the files and install them in the registry. Step 3: Once the installation of Snap is over, clear the terminal and begin with the Julia Installation process. Step 4: Use the following command to install Julia and then press Enter. Step 5: Now Terminal will download Julia online and will begin with the installation process Step 6: Mounting Julia on the Destination Drive after completing the download. Step 7: Installation of Julia is now over, you can proceed with the next step to Start Julia compiler and begin with writing Julia programming codes. Step 8: Enter the following command to begin with the Julia compiler and to confirm if the installation is completed successfully. Type the following command and press Enter:" }, { "code": null, "e": 2118, "s": 2112, "text": "julia" }, { "code": null, "e": 2283, "s": 2118, "text": " After completing the installation process, any IDE or text editor can be used to write Julia Codes and Run them on the IDE or the terminal with the use of command:" }, { "code": null, "e": 2302, "s": 2283, "text": "julia file_name.jl" }, { "code": null, "e": 2347, "s": 2302, "text": "Let’s consider a simple Hello World Program." }, { "code": "# Julia program to print Hello World # print functionprintln(\"Hello World !\") ", "e": 2429, "s": 2347, "text": null }, { "code": null, "e": 2437, "s": 2429, "text": "Output:" }, { "code": null, "e": 2450, "s": 2437, "text": "Julia-Basics" }, { "code": null, "e": 2456, "s": 2450, "text": "Julia" }, { "code": null, "e": 2554, "s": 2456, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2571, "s": 2554, "text": "Vectors in Julia" }, { "code": null, "e": 2631, "s": 2571, "text": "Getting rounded value of a number in Julia - round() Method" }, { "code": null, "e": 2665, "s": 2631, "text": "Storing Output on a File in Julia" }, { "code": null, "e": 2726, "s": 2665, "text": "Reshaping array dimensions in Julia | Array reshape() Method" }, { "code": null, "e": 2757, "s": 2726, "text": "Manipulating matrices in Julia" }, { "code": null, "e": 2785, "s": 2757, "text": "Exception handling in Julia" }, { "code": null, "e": 2850, "s": 2785, "text": "Creating array with repeated elements in Julia - repeat() Method" }, { "code": null, "e": 2870, "s": 2850, "text": "while loop in Julia" }, { "code": null, "e": 2886, "s": 2870, "text": "Tuples in Julia" } ]
Input Iterators in C++
23 Jan, 2021 After going through the template definition of various STL algorithms like std::find, std::equal, std::count, you must have found their template definition consisting of objects of type Input Iterator. So what are they and why are they used?Input iterators are one of the five main types of iterators present in the C++ Standard Library, others being Output iterators, Forward iterator, Bidirectional iterator, and Random – access iterators.Input iterators are considered to be the weakest as well as the simplest among all the iterators available, based upon their functionality and what can be achieved using them. They are the iterators that can be used in sequential input operations, where each value pointed by the iterator is read-only once and then the iterator is incremented. One important thing to be kept in mind is that forward, bidirectional and random-access iterators are also valid input iterators, as shown in the iterator hierarchy above. Salient Features Usability: Input iterators can be used only with single-pass algorithms, i.e., algorithms in which we can go to all the locations in the range at most once, like when we have to search or find any element in the range, we go through the locations at most once. Equality / Inequality Comparison: An input iterator can be compared for equality with another iterator. Since, iterators point to some location, so the two iterators will be equal only when they point to the same position, otherwise not.So, the following two expressions are valid if A and B are input iterators: Usability: Input iterators can be used only with single-pass algorithms, i.e., algorithms in which we can go to all the locations in the range at most once, like when we have to search or find any element in the range, we go through the locations at most once. Equality / Inequality Comparison: An input iterator can be compared for equality with another iterator. Since, iterators point to some location, so the two iterators will be equal only when they point to the same position, otherwise not.So, the following two expressions are valid if A and B are input iterators: A == B // Checking for equality A != B // Checking for inequality 3. Dereferencing: An input iterator can be dereferenced, using the operator * and -> as an rvalue to obtain the value stored at the position being pointed to by the iterator. So, the following two expressions are valid if A is an input iterator: *A // Dereferencing using * A -> m // Accessing a member element m 4. Incrementable: An input iterator can be incremented, so that it refers to the next element in the sequence, using operator ++(). Note: The fact that we can use input iterators with increment operator doesn’t mean that operator – -() can also be used with them. Remember, that input iterators are unidirectional and can only move in the forward direction.So, the following two expressions are valid if A is an input iterator: A++ // Using post increment operator ++A // Using pre increment operator Swappable: The value pointed to by these iterators can be exchanged or swapped. Practical implementationAfter understanding its features and deficiencies, it is very important to learn about its practical implementation as well. As told earlier, input iterators are used only when we want to access elements and not when we have to assign elements to them. The following two STL algorithms can show this fact: std::find: As we know this algorithm is used to find the presence of an element inside a container. So, let us look at its internal working (Don’t go into detail just look where input iterators can be used and where they cannot be): CPP // Definition of std::find() template InputIterator find (InputIterator first, InputIterator last, const T& val){ while (first!=last) { if (*first==val) return first; ++first; } return last;} So, this is the practical implementation of input iterators, single-pass algorithms where only we have to move sequentially and access the elements and check for equality with another element just like first is used above, so here they can be used. More such algorithms are std::equal, std::equal_range and std::count. std::copy: As the name suggests, this algorithm is used to copy a range into another range. Now, as far as accessing elements are concerned, input iterators are fine, but as soon as we have to assign elements in another container, then we cannot use these input iterators for this purpose. CPP // Definition of std::copy() template OutputIterator copy(InputIterator first, InputIterator last, OutputIterator result) { while (first != last) *result++ = *first++; return result;} Here, since the result is the iterator to the resultant container, to which elements are assigned, so for this, we cannot use input iterators and have made use of output iterators at their place, whereas for first, which only needs to be incremented and accessed, we have used input iterator. LimitationsAfter studying the salient features, one must also know its deficiencies as well which make it the weakest iterator among all, which are mentioned in the following points: Only accessing, no assigning: One of the biggest deficiency is that we cannot assign any value to the location pointed by this iterator, it can only be used to access elements and not assign elements. Only accessing, no assigning: One of the biggest deficiency is that we cannot assign any value to the location pointed by this iterator, it can only be used to access elements and not assign elements. CPP // C++ program to demonstrate input iterator#include <iostream>#include <vector>using namespace std;int main(){ vector<int> v1 = { 1, 2, 3, 4, 5 }; // Declaring an iterator vector<int>::iterator i1; for (i1 = v1.begin(); i1 != v1.end(); ++i1) { // Accessing elements using iterator cout << (*i1) << " "; } return 0;} Output: 1 2 3 4 5 The above is an example of accessing elements using input iterator, however, if we do something like: *i1 = 7; So, this is not allowed in the input iterator. However, if you try this for the above code, it will work, because vectors return iterators higher in the hierarchy than input iterators.That big deficiency is the reason why many algorithms like std::copy, which requires copying a range into another container cannot use input iterator for the resultant container, because we can’t assign values to it with such iterators and instead make use of output iterators. Cannot be decremented: Just like we can use operator ++() with input iterators for incrementing them, we cannot decrement them. If A is an input iterator, then A-- // Not allowed with input iterators Use in multi-pass algorithms: Since it is unidirectional and can only move forward, therefore, such iterators cannot be used in multi-pass algorithms, in which we need to process the container multiple times. Relational Operators: Although, input iterators can be used with equality operator (==), but it can not be used with other relational operators like <=. If A and B are input iterators, then A == B // Allowed A <= B // Not Allowed Arithmetic Operators: Similar to relational operators, they also can’t be used with arithmetic operators like +, – and so on. This means that input operators can only move in one direction that too forward and that too sequentially. If A and B are input iterators, then A + 1 // Not allowed B - 2 // Not allowed So, the two above examples very well show when, where, why, and how input iterators are used practically.This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Akanksha_Rai vyer cpp-iterator STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ std::string class in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Unordered Sets in C++ Standard Template Library List in C++ Standard Template Library (STL) std::find in C++ Inline Functions in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jan, 2021" }, { "code": null, "e": 841, "s": 54, "text": "After going through the template definition of various STL algorithms like std::find, std::equal, std::count, you must have found their template definition consisting of objects of type Input Iterator. So what are they and why are they used?Input iterators are one of the five main types of iterators present in the C++ Standard Library, others being Output iterators, Forward iterator, Bidirectional iterator, and Random – access iterators.Input iterators are considered to be the weakest as well as the simplest among all the iterators available, based upon their functionality and what can be achieved using them. They are the iterators that can be used in sequential input operations, where each value pointed by the iterator is read-only once and then the iterator is incremented. " }, { "code": null, "e": 1014, "s": 841, "text": "One important thing to be kept in mind is that forward, bidirectional and random-access iterators are also valid input iterators, as shown in the iterator hierarchy above. " }, { "code": null, "e": 1032, "s": 1014, "text": "Salient Features " }, { "code": null, "e": 1609, "s": 1032, "text": "Usability: Input iterators can be used only with single-pass algorithms, i.e., algorithms in which we can go to all the locations in the range at most once, like when we have to search or find any element in the range, we go through the locations at most once. Equality / Inequality Comparison: An input iterator can be compared for equality with another iterator. Since, iterators point to some location, so the two iterators will be equal only when they point to the same position, otherwise not.So, the following two expressions are valid if A and B are input iterators: " }, { "code": null, "e": 1872, "s": 1609, "text": "Usability: Input iterators can be used only with single-pass algorithms, i.e., algorithms in which we can go to all the locations in the range at most once, like when we have to search or find any element in the range, we go through the locations at most once. " }, { "code": null, "e": 2187, "s": 1872, "text": "Equality / Inequality Comparison: An input iterator can be compared for equality with another iterator. Since, iterators point to some location, so the two iterators will be equal only when they point to the same position, otherwise not.So, the following two expressions are valid if A and B are input iterators: " }, { "code": null, "e": 2256, "s": 2187, "text": "A == B // Checking for equality\nA != B // Checking for inequality\n" }, { "code": null, "e": 2535, "s": 2256, "text": " 3. Dereferencing: An input iterator can be dereferenced, using the operator * and -> as an rvalue to obtain the value stored at the position being pointed to by the iterator. So, the following two expressions are valid if A is an input iterator: " }, { "code": null, "e": 2611, "s": 2535, "text": "*A // Dereferencing using *\nA -> m // Accessing a member element m\n" }, { "code": null, "e": 2751, "s": 2611, "text": " 4. Incrementable: An input iterator can be incremented, so that it refers to the next element in the sequence, using operator ++()." }, { "code": null, "e": 3048, "s": 2751, "text": "Note: The fact that we can use input iterators with increment operator doesn’t mean that operator – -() can also be used with them. Remember, that input iterators are unidirectional and can only move in the forward direction.So, the following two expressions are valid if A is an input iterator: " }, { "code": null, "e": 3126, "s": 3048, "text": "A++ // Using post increment operator\n++A // Using pre increment operator\n" }, { "code": null, "e": 3206, "s": 3126, "text": "Swappable: The value pointed to by these iterators can be exchanged or swapped." }, { "code": null, "e": 3537, "s": 3206, "text": "Practical implementationAfter understanding its features and deficiencies, it is very important to learn about its practical implementation as well. As told earlier, input iterators are used only when we want to access elements and not when we have to assign elements to them. The following two STL algorithms can show this fact: " }, { "code": null, "e": 3771, "s": 3537, "text": "std::find: As we know this algorithm is used to find the presence of an element inside a container. So, let us look at its internal working (Don’t go into detail just look where input iterators can be used and where they cannot be): " }, { "code": null, "e": 3775, "s": 3771, "text": "CPP" }, { "code": "// Definition of std::find() template InputIterator find (InputIterator first, InputIterator last, const T& val){ while (first!=last) { if (*first==val) return first; ++first; } return last;}", "e": 4016, "s": 3775, "text": null }, { "code": null, "e": 4337, "s": 4016, "text": "So, this is the practical implementation of input iterators, single-pass algorithms where only we have to move sequentially and access the elements and check for equality with another element just like first is used above, so here they can be used. More such algorithms are std::equal, std::equal_range and std::count. " }, { "code": null, "e": 4628, "s": 4337, "text": "std::copy: As the name suggests, this algorithm is used to copy a range into another range. Now, as far as accessing elements are concerned, input iterators are fine, but as soon as we have to assign elements in another container, then we cannot use these input iterators for this purpose. " }, { "code": null, "e": 4632, "s": 4628, "text": "CPP" }, { "code": "// Definition of std::copy() template OutputIterator copy(InputIterator first, InputIterator last, OutputIterator result) { while (first != last) *result++ = *first++; return result;}", "e": 4845, "s": 4632, "text": null }, { "code": null, "e": 5139, "s": 4845, "text": "Here, since the result is the iterator to the resultant container, to which elements are assigned, so for this, we cannot use input iterators and have made use of output iterators at their place, whereas for first, which only needs to be incremented and accessed, we have used input iterator. " }, { "code": null, "e": 5324, "s": 5139, "text": "LimitationsAfter studying the salient features, one must also know its deficiencies as well which make it the weakest iterator among all, which are mentioned in the following points: " }, { "code": null, "e": 5526, "s": 5324, "text": "Only accessing, no assigning: One of the biggest deficiency is that we cannot assign any value to the location pointed by this iterator, it can only be used to access elements and not assign elements. " }, { "code": null, "e": 5728, "s": 5526, "text": "Only accessing, no assigning: One of the biggest deficiency is that we cannot assign any value to the location pointed by this iterator, it can only be used to access elements and not assign elements. " }, { "code": null, "e": 5732, "s": 5728, "text": "CPP" }, { "code": "// C++ program to demonstrate input iterator#include <iostream>#include <vector>using namespace std;int main(){ vector<int> v1 = { 1, 2, 3, 4, 5 }; // Declaring an iterator vector<int>::iterator i1; for (i1 = v1.begin(); i1 != v1.end(); ++i1) { // Accessing elements using iterator cout << (*i1) << \" \"; } return 0;}", "e": 6085, "s": 5732, "text": null }, { "code": null, "e": 6094, "s": 6085, "text": "Output: " }, { "code": null, "e": 6105, "s": 6094, "text": "1 2 3 4 5\n" }, { "code": null, "e": 6208, "s": 6105, "text": "The above is an example of accessing elements using input iterator, however, if we do something like: " }, { "code": null, "e": 6218, "s": 6208, "text": "*i1 = 7;\n" }, { "code": null, "e": 6682, "s": 6218, "text": "So, this is not allowed in the input iterator. However, if you try this for the above code, it will work, because vectors return iterators higher in the hierarchy than input iterators.That big deficiency is the reason why many algorithms like std::copy, which requires copying a range into another container cannot use input iterator for the resultant container, because we can’t assign values to it with such iterators and instead make use of output iterators. " }, { "code": null, "e": 6811, "s": 6682, "text": "Cannot be decremented: Just like we can use operator ++() with input iterators for incrementing them, we cannot decrement them. " }, { "code": null, "e": 6888, "s": 6811, "text": "If A is an input iterator, then\n\nA-- // Not allowed with input iterators\n" }, { "code": null, "e": 7099, "s": 6888, "text": "Use in multi-pass algorithms: Since it is unidirectional and can only move forward, therefore, such iterators cannot be used in multi-pass algorithms, in which we need to process the container multiple times. " }, { "code": null, "e": 7253, "s": 7099, "text": "Relational Operators: Although, input iterators can be used with equality operator (==), but it can not be used with other relational operators like <=. " }, { "code": null, "e": 7340, "s": 7253, "text": "If A and B are input iterators, then\n\nA == B // Allowed\nA <= B // Not Allowed\n" }, { "code": null, "e": 7574, "s": 7340, "text": "Arithmetic Operators: Similar to relational operators, they also can’t be used with arithmetic operators like +, – and so on. This means that input operators can only move in one direction that too forward and that too sequentially. " }, { "code": null, "e": 7663, "s": 7574, "text": "If A and B are input iterators, then\n\nA + 1 // Not allowed\nB - 2 // Not allowed\n" }, { "code": null, "e": 8196, "s": 7663, "text": "So, the two above examples very well show when, where, why, and how input iterators are used practically.This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 8209, "s": 8196, "text": "Akanksha_Rai" }, { "code": null, "e": 8214, "s": 8209, "text": "vyer" }, { "code": null, "e": 8227, "s": 8214, "text": "cpp-iterator" }, { "code": null, "e": 8231, "s": 8227, "text": "STL" }, { "code": null, "e": 8235, "s": 8231, "text": "C++" }, { "code": null, "e": 8239, "s": 8235, "text": "STL" }, { "code": null, "e": 8243, "s": 8239, "text": "CPP" }, { "code": null, "e": 8341, "s": 8243, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8365, "s": 8341, "text": "Sorting a vector in C++" }, { "code": null, "e": 8385, "s": 8365, "text": "Polymorphism in C++" }, { "code": null, "e": 8410, "s": 8385, "text": "std::string class in C++" }, { "code": null, "e": 8443, "s": 8410, "text": "Friend class and function in C++" }, { "code": null, "e": 8487, "s": 8443, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 8532, "s": 8487, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 8580, "s": 8532, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 8624, "s": 8580, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 8641, "s": 8624, "text": "std::find in C++" } ]
DataInputStream readInt() method in Java with Examples
05 Jun, 2020 The readInt() method of DataInputStream class in Java is used to read four input bytes and returns a integer value. This method reads the next four bytes from the input stream and interprets it into integer type and returns. Syntax: public final int readInt() throws IOException Specified By: This method is specified by readInt() method of DataInput interface. Parameters: This method does not accept any parameter. Return value: This method returns the int value interpreted by the next four bytes of the input stream. Exceptions: EOFException – It throws EOFException if the input stream is ended before four bytes can be read. IOException – This method throws IOException if the stream is closed or some other I/O error occurs. Below programs illustrate readInt() method in DataInputStream class in IO package: Program 1: Assume the existence of file “demo.txt”. // Java program to illustrate// DataInputStream readInt() methodimport java.io.*;public class GFG { public static void main(String[] args) throws IOException { // Create integer array int[] buf = { 10, 20, 30, 40, 50 }; // Create file output stream FileOutputStream outputStream = new FileOutputStream("c:\\demo.txt"); // Create data output stream DataOutputStream dataOutputStr = new DataOutputStream(outputStream); for (int b : buf) { // Write integer value to // the dataOutputStream dataOutputStr.writeInt(b); } dataOutputStr.flush(); // Create file input stream FileInputStream inputStream = new FileInputStream("c:\\demo.txt"); // Create data input stream DataInputStream dataInputStr = new DataInputStream(inputStream); while (dataInputStr.available() > 0) { // Print integer values System.out.println( dataInputStr.readInt()); } }} Program 2: Assume the existence of file “demo.txt”. // Java program to illustrate// DataInputStream readInt() methodimport java.io.*;public class GFG { public static void main(String[] args) throws IOException { // Create integer array int[] buf = { 191, 225, 480, 763, 500 }; // Create file output stream FileOutputStream outputStream = new FileOutputStream("c:\\demo.txt"); // Create data output stream DataOutputStream dataOutputStr = new DataOutputStream(outputStream); for (int b : buf) { // Write integer value to // the dataOutputStream dataOutputStr.writeInt(b); } dataOutputStr.flush(); // Create file input stream FileInputStream inputStream = new FileInputStream("c:\\demo.txt"); // Create data input stream DataInputStream dataInputStr = new DataInputStream(inputStream); while (dataInputStr.available() > 0) { // Print integer values System.out.println( dataInputStr.readInt()); } }} References:https://docs.oracle.com/javase/10/docs/api/java/io/DataInputStream.html#readInt() Java-Functions Java-IO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jun, 2020" }, { "code": null, "e": 253, "s": 28, "text": "The readInt() method of DataInputStream class in Java is used to read four input bytes and returns a integer value. This method reads the next four bytes from the input stream and interprets it into integer type and returns." }, { "code": null, "e": 261, "s": 253, "text": "Syntax:" }, { "code": null, "e": 321, "s": 261, "text": "public final int readInt()\n throws IOException\n" }, { "code": null, "e": 404, "s": 321, "text": "Specified By: This method is specified by readInt() method of DataInput interface." }, { "code": null, "e": 459, "s": 404, "text": "Parameters: This method does not accept any parameter." }, { "code": null, "e": 563, "s": 459, "text": "Return value: This method returns the int value interpreted by the next four bytes of the input stream." }, { "code": null, "e": 575, "s": 563, "text": "Exceptions:" }, { "code": null, "e": 673, "s": 575, "text": "EOFException – It throws EOFException if the input stream is ended before four bytes can be read." }, { "code": null, "e": 774, "s": 673, "text": "IOException – This method throws IOException if the stream is closed or some other I/O error occurs." }, { "code": null, "e": 857, "s": 774, "text": "Below programs illustrate readInt() method in DataInputStream class in IO package:" }, { "code": null, "e": 909, "s": 857, "text": "Program 1: Assume the existence of file “demo.txt”." }, { "code": "// Java program to illustrate// DataInputStream readInt() methodimport java.io.*;public class GFG { public static void main(String[] args) throws IOException { // Create integer array int[] buf = { 10, 20, 30, 40, 50 }; // Create file output stream FileOutputStream outputStream = new FileOutputStream(\"c:\\\\demo.txt\"); // Create data output stream DataOutputStream dataOutputStr = new DataOutputStream(outputStream); for (int b : buf) { // Write integer value to // the dataOutputStream dataOutputStr.writeInt(b); } dataOutputStr.flush(); // Create file input stream FileInputStream inputStream = new FileInputStream(\"c:\\\\demo.txt\"); // Create data input stream DataInputStream dataInputStr = new DataInputStream(inputStream); while (dataInputStr.available() > 0) { // Print integer values System.out.println( dataInputStr.readInt()); } }}", "e": 2000, "s": 909, "text": null }, { "code": null, "e": 2052, "s": 2000, "text": "Program 2: Assume the existence of file “demo.txt”." }, { "code": "// Java program to illustrate// DataInputStream readInt() methodimport java.io.*;public class GFG { public static void main(String[] args) throws IOException { // Create integer array int[] buf = { 191, 225, 480, 763, 500 }; // Create file output stream FileOutputStream outputStream = new FileOutputStream(\"c:\\\\demo.txt\"); // Create data output stream DataOutputStream dataOutputStr = new DataOutputStream(outputStream); for (int b : buf) { // Write integer value to // the dataOutputStream dataOutputStr.writeInt(b); } dataOutputStr.flush(); // Create file input stream FileInputStream inputStream = new FileInputStream(\"c:\\\\demo.txt\"); // Create data input stream DataInputStream dataInputStr = new DataInputStream(inputStream); while (dataInputStr.available() > 0) { // Print integer values System.out.println( dataInputStr.readInt()); } }}", "e": 3148, "s": 2052, "text": null }, { "code": null, "e": 3241, "s": 3148, "text": "References:https://docs.oracle.com/javase/10/docs/api/java/io/DataInputStream.html#readInt()" }, { "code": null, "e": 3256, "s": 3241, "text": "Java-Functions" }, { "code": null, "e": 3272, "s": 3256, "text": "Java-IO package" }, { "code": null, "e": 3277, "s": 3272, "text": "Java" }, { "code": null, "e": 3282, "s": 3277, "text": "Java" }, { "code": null, "e": 3380, "s": 3282, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3431, "s": 3380, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3462, "s": 3431, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3481, "s": 3462, "text": "Interfaces in Java" }, { "code": null, "e": 3511, "s": 3481, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3529, "s": 3511, "text": "ArrayList in Java" }, { "code": null, "e": 3544, "s": 3529, "text": "Stream In Java" }, { "code": null, "e": 3564, "s": 3544, "text": "Collections in Java" }, { "code": null, "e": 3596, "s": 3564, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 3620, "s": 3596, "text": "Singleton Class in Java" } ]
Create a Sticky Social Media Bar using HTML and CSS
27 Sep, 2021 To create a sticky social media bar on any website HTML and CSS are used. If you want to attach the icons with the sticky social media then you need a font-awesome CDN link. These days social media is the best platform to advertise your stuff. Social media, where you can inform the client or the user about your product easily, the user can share the details of the product on their social media account if they like your product. So creating a sticky Social Media bar sometimes makes your site slower (if you are using jQuery plugins for the Sticky Social Media Bar). In this article, you will get to know how to attach a sticky Social Media bar on your website. This article is divided into two sections Creating Structure and Designing Structure. Glimpse of complete Sticky Social Media Bar: Creating Structure: In this section we will create a basic site structure and also attach the CDN link of the Font-Awesome for the icons which will be used as a sticky social media bar. CDN links for the Icons from the Font Awesome: <link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css”> HTML code to make the structure: HTML <!DOCTYPE html><html> <head> <title>Sticky Social Media Bar</title></head> <body> <center> <h3>Sticky Social Media Bar</h3> <!-- Icons for the sticky Social Bar --> <div class="body-part"> <div class="icon-list"> <a href="#instagram" class="instagram"> <i class="fa fa-instagram"></i> </a> <a href="#facebook" class="facebook"> <i class="fa fa-facebook"></i> </a> <a href="#twitter" class="twitter"> <i class="fa fa-twitter"></i> </a> <a href="#linkedin" class="linkedin"> <i class="fa fa-linkedin"></i> </a> <a href="#google" class="google"> <i class="fa fa-google"></i> </a> <a href="#youtube" class="youtube"> <i class="fa fa-youtube"></i> </a> </div> <!-- Content of the Page --> <h2>GeeksforGeeks</h2> <p> An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </p> <p> Only the zeal to learn and improve yourself is all we need. Anyone who has a passion for learning and writing is welcome to write for us. Contribution on GeeksforGeeks is not limited to writing articles only, below are the details about the ways in which you can help us and other fellow programmers: </p> <p> If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. </p> </div> </center></body> </html> Designing Structure: In the previous section we have created the structure of the basic website where we are going to use sticky social media bars. In this section, we will design the structure and attach the sticky icons of the social media bar. CSS code to look good the structure: HTML <style> /* Styling Body-part */ .body-part { width: 600px; height: 200px; border: 3px solid black; overflow: auto; } h2 { color: green; } /* Justifying Content text */ p { text-align: justify; margin: 40px; } /* Styling icons */ .icon-list { position: fixed; top: 242px; right:40%; transform: translateY(-50%); } .icon-list a { display: block; text-align: center; padding: 8px; transition: all 0.5s ease; color: white; font-size: 20px; float:right; } /* HOver affect on icons */ .icon-list a:hover { color: #000; width:50px; } /* Designing each icons */ .instagram { background: #3f729b; color: white; } .facebook { background: #3b5998; color: white; } .twitter { background: #00acee; color: white; } .linkedin { background: #0e76a8; color: white; } .google { background: #db4a39; color: white; } .youtube { background: #c4302b; color: white; }</style> Combine the HTML and CSS code: This is the final code after combining the above two sections. It will create a sticky social media bar of a website. HTML <!DOCTYPE html><html> <head> <title>Sticky Social Media Bar</title> <!-- Linking Font-Awesome For the Icons --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> /* Styling Body-part */ .body-part { width: 600px; height: 200px; border: 3px solid black; overflow: auto; } h2 { color: green; } /* Justifying Content text */ p { text-align: justify; margin: 40px; } /* Styling icons */ .icon-list { position: fixed; top: 242px; right:40%; transform: translateY(-50%); } .icon-list a { display: block; text-align: center; padding: 8px; transition: all 0.5s ease; color: white; font-size: 20px; float:right; } /* HOver affect on icons */ .icon-list a:hover { color: #000; width:50px; } /* Designing each icons */ .instagram { background: #3f729b; color: white; } .facebook { background: #3b5998; color: white; } .twitter { background: #00acee; color: white; } .linkedin { background: #0e76a8; color: white; } .google { background: #db4a39; color: white; } .youtube { background: #c4302b; color: white; } </style></head> <body> <center> <h3>Sticky Social Media Bar</h3> <!-- Icons for the sticky Social Bar --> <div class="body-part"> <div class="icon-list"> <a href="#instagram" class="instagram"> <i class="fa fa-instagram"></i> </a> <a href="#facebook" class="facebook"> <i class="fa fa-facebook"></i> </a> <a href="#twitter" class="twitter"> <i class="fa fa-twitter"></i> </a> <a href="#linkedin" class="linkedin"> <i class="fa fa-linkedin"></i> </a> <a href="#google" class="google"> <i class="fa fa-google"></i> </a> <a href="#youtube" class="youtube"> <i class="fa fa-youtube"></i> </a> </div> <!-- Content of the Page --> <h2>GeeksforGeeks</h2> <p> An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </p> <p> Only the zeal to learn and improve yourself is all we need. Anyone who has a passion for learning and writing is welcome to write for us. Contribution on GeeksforGeeks is not limited to writing articles only, below are the details about the ways in which you can help us and other fellow programmers: </p> <p> If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. </p> </div> </center></body> </html> Output: arorakashish0911 CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Sep, 2021" }, { "code": null, "e": 806, "s": 54, "text": "To create a sticky social media bar on any website HTML and CSS are used. If you want to attach the icons with the sticky social media then you need a font-awesome CDN link. These days social media is the best platform to advertise your stuff. Social media, where you can inform the client or the user about your product easily, the user can share the details of the product on their social media account if they like your product. So creating a sticky Social Media bar sometimes makes your site slower (if you are using jQuery plugins for the Sticky Social Media Bar). In this article, you will get to know how to attach a sticky Social Media bar on your website. This article is divided into two sections Creating Structure and Designing Structure. " }, { "code": null, "e": 852, "s": 806, "text": "Glimpse of complete Sticky Social Media Bar: " }, { "code": null, "e": 1039, "s": 852, "text": "Creating Structure: In this section we will create a basic site structure and also attach the CDN link of the Font-Awesome for the icons which will be used as a sticky social media bar. " }, { "code": null, "e": 1087, "s": 1039, "text": "CDN links for the Icons from the Font Awesome: " }, { "code": null, "e": 1201, "s": 1087, "text": "<link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css”>" }, { "code": null, "e": 1234, "s": 1201, "text": "HTML code to make the structure:" }, { "code": null, "e": 1239, "s": 1234, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Sticky Social Media Bar</title></head> <body> <center> <h3>Sticky Social Media Bar</h3> <!-- Icons for the sticky Social Bar --> <div class=\"body-part\"> <div class=\"icon-list\"> <a href=\"#instagram\" class=\"instagram\"> <i class=\"fa fa-instagram\"></i> </a> <a href=\"#facebook\" class=\"facebook\"> <i class=\"fa fa-facebook\"></i> </a> <a href=\"#twitter\" class=\"twitter\"> <i class=\"fa fa-twitter\"></i> </a> <a href=\"#linkedin\" class=\"linkedin\"> <i class=\"fa fa-linkedin\"></i> </a> <a href=\"#google\" class=\"google\"> <i class=\"fa fa-google\"></i> </a> <a href=\"#youtube\" class=\"youtube\"> <i class=\"fa fa-youtube\"></i> </a> </div> <!-- Content of the Page --> <h2>GeeksforGeeks</h2> <p> An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </p> <p> Only the zeal to learn and improve yourself is all we need. Anyone who has a passion for learning and writing is welcome to write for us. Contribution on GeeksforGeeks is not limited to writing articles only, below are the details about the ways in which you can help us and other fellow programmers: </p> <p> If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. </p> </div> </center></body> </html>", "e": 3633, "s": 1239, "text": null }, { "code": null, "e": 3881, "s": 3633, "text": "Designing Structure: In the previous section we have created the structure of the basic website where we are going to use sticky social media bars. In this section, we will design the structure and attach the sticky icons of the social media bar. " }, { "code": null, "e": 3919, "s": 3881, "text": "CSS code to look good the structure: " }, { "code": null, "e": 3924, "s": 3919, "text": "HTML" }, { "code": "<style> /* Styling Body-part */ .body-part { width: 600px; height: 200px; border: 3px solid black; overflow: auto; } h2 { color: green; } /* Justifying Content text */ p { text-align: justify; margin: 40px; } /* Styling icons */ .icon-list { position: fixed; top: 242px; right:40%; transform: translateY(-50%); } .icon-list a { display: block; text-align: center; padding: 8px; transition: all 0.5s ease; color: white; font-size: 20px; float:right; } /* HOver affect on icons */ .icon-list a:hover { color: #000; width:50px; } /* Designing each icons */ .instagram { background: #3f729b; color: white; } .facebook { background: #3b5998; color: white; } .twitter { background: #00acee; color: white; } .linkedin { background: #0e76a8; color: white; } .google { background: #db4a39; color: white; } .youtube { background: #c4302b; color: white; }</style>", "e": 5145, "s": 3924, "text": null }, { "code": null, "e": 5294, "s": 5145, "text": "Combine the HTML and CSS code: This is the final code after combining the above two sections. It will create a sticky social media bar of a website." }, { "code": null, "e": 5299, "s": 5294, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Sticky Social Media Bar</title> <!-- Linking Font-Awesome For the Icons --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"> <style> /* Styling Body-part */ .body-part { width: 600px; height: 200px; border: 3px solid black; overflow: auto; } h2 { color: green; } /* Justifying Content text */ p { text-align: justify; margin: 40px; } /* Styling icons */ .icon-list { position: fixed; top: 242px; right:40%; transform: translateY(-50%); } .icon-list a { display: block; text-align: center; padding: 8px; transition: all 0.5s ease; color: white; font-size: 20px; float:right; } /* HOver affect on icons */ .icon-list a:hover { color: #000; width:50px; } /* Designing each icons */ .instagram { background: #3f729b; color: white; } .facebook { background: #3b5998; color: white; } .twitter { background: #00acee; color: white; } .linkedin { background: #0e76a8; color: white; } .google { background: #db4a39; color: white; } .youtube { background: #c4302b; color: white; } </style></head> <body> <center> <h3>Sticky Social Media Bar</h3> <!-- Icons for the sticky Social Bar --> <div class=\"body-part\"> <div class=\"icon-list\"> <a href=\"#instagram\" class=\"instagram\"> <i class=\"fa fa-instagram\"></i> </a> <a href=\"#facebook\" class=\"facebook\"> <i class=\"fa fa-facebook\"></i> </a> <a href=\"#twitter\" class=\"twitter\"> <i class=\"fa fa-twitter\"></i> </a> <a href=\"#linkedin\" class=\"linkedin\"> <i class=\"fa fa-linkedin\"></i> </a> <a href=\"#google\" class=\"google\"> <i class=\"fa fa-google\"></i> </a> <a href=\"#youtube\" class=\"youtube\"> <i class=\"fa fa-youtube\"></i> </a> </div> <!-- Content of the Page --> <h2>GeeksforGeeks</h2> <p> An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. </p> <p> Only the zeal to learn and improve yourself is all we need. Anyone who has a passion for learning and writing is welcome to write for us. Contribution on GeeksforGeeks is not limited to writing articles only, below are the details about the ways in which you can help us and other fellow programmers: </p> <p> If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. </p> </div> </center></body> </html>", "e": 9400, "s": 5299, "text": null }, { "code": null, "e": 9409, "s": 9400, "text": "Output: " }, { "code": null, "e": 9428, "s": 9411, "text": "arorakashish0911" }, { "code": null, "e": 9437, "s": 9428, "text": "CSS-Misc" }, { "code": null, "e": 9447, "s": 9437, "text": "HTML-Misc" }, { "code": null, "e": 9451, "s": 9447, "text": "CSS" }, { "code": null, "e": 9456, "s": 9451, "text": "HTML" }, { "code": null, "e": 9473, "s": 9456, "text": "Web Technologies" }, { "code": null, "e": 9500, "s": 9473, "text": "Web technologies Questions" }, { "code": null, "e": 9505, "s": 9500, "text": "HTML" }, { "code": null, "e": 9603, "s": 9505, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9651, "s": 9603, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 9713, "s": 9651, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 9763, "s": 9713, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 9821, "s": 9763, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 9871, "s": 9821, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 9919, "s": 9871, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 9981, "s": 9919, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 10031, "s": 9981, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 10055, "s": 10031, "text": "REST API (Introduction)" } ]
Print Nodes in Top View of Binary Tree
23 Jun, 2022 Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes can be printed in any order. A node x is there in output if x is the topmost node at its horizontal distance. Horizontal distance of left child of a node x is equal to horizontal distance of x minus 1, and that of right child is horizontal distance of x plus 1. 1 / \ 2 3 / \ / \ 4 5 6 7 Top view of the above binary tree is 4 2 1 3 7 1 / \ 2 3 \ 4 \ 5 \ 6 Top view of the above binary tree is 2 1 3 6 The idea is to do something similar to vertical Order Traversal. Like vertical Order Traversal, we need to put nodes of same horizontal distance together. We do a level order traversal so that the topmost node at a horizontal node is visited before any other node of same horizontal distance below it. Hashing is used to check if a node at given horizontal distance is seen or not. Implementation: C++14 Java Python3 C# Javascript // C++ program to print top// view of binary tree #include <bits/stdc++.h>using namespace std; // Structure of binary treestruct Node{ Node* left; Node* right; int hd; int data;}; // function to create a new nodeNode* newNode(int key){ Node* node = new Node(); node -> left = node -> right = NULL; node -> data = key; return node;} // function should print the topView of// the binary treevoid topview(Node* root){ if (root == NULL) return; queue<Node*> q; map<int, int> m; int hd = 0; root -> hd = hd; // push node and horizontal distance to queue q.push(root); cout << "The top view of the tree is : \n"; while (q.size()) { hd = root -> hd; // count function returns 1 if the container // contains an element whose key is equivalent // to hd, or returns zero otherwise. if (m.count(hd) == 0) m[hd] = root -> data; if (root -> left) { root -> left -> hd = hd - 1; q.push(root -> left); } if (root -> right) { root -> right -> hd = hd + 1; q.push(root -> right); } q.pop(); root = q.front(); } for (auto i = m.begin(); i != m.end(); i++) { cout << i -> second << " "; }} // Driver Program to test above functionsint main(){ /* Create following Binary Tree 1 / \ 2 3 \ 4 \ 5 \ 6*/ Node* root = newNode(1); root -> left = newNode(2); root -> right = newNode(3); root -> left -> right = newNode(4); root -> left -> right -> right = newNode(5); root -> left -> right -> right -> right = newNode(6); cout << "Following are nodes in top view of Binary " "Tree\n"; topview(root); return 0;}/* This code is contributed by Niteesh Kumar */ // Java program to print top// view of binary treeimport java.util.LinkedList;import java.util.Map;import java.util.Map.Entry;import java.util.Queue;import java.util.TreeMap; // class to create a nodeclass Node { int data; Node left, right; public Node(int data) { this.data = data; left = right = null; }} // class of binary treeclass BinaryTree { Node root; public BinaryTree() { root = null; } // function should print the topView of // the binary tree private void TopView(Node root) { class QueueObj { Node node; int hd; QueueObj(Node node, int hd) { this.node = node; this.hd = hd; } } Queue<QueueObj> q = new LinkedList<QueueObj>(); Map<Integer, Node> topViewMap = new TreeMap<Integer, Node>(); if (root == null) { return; } else { q.add(new QueueObj(root, 0)); } System.out.println( "The top view of the tree is : "); // count function returns 1 if the container // contains an element whose key is equivalent // to hd, or returns zero otherwise. while (!q.isEmpty()) { QueueObj tmpNode = q.poll(); if (!topViewMap.containsKey(tmpNode.hd)) { topViewMap.put(tmpNode.hd, tmpNode.node); } if (tmpNode.node.left != null) { q.add(new QueueObj(tmpNode.node.left, tmpNode.hd - 1)); } if (tmpNode.node.right != null) { q.add(new QueueObj(tmpNode.node.right, tmpNode.hd + 1)); } } for (Map.Entry<Integer, Node> entry : topViewMap.entrySet()) { System.out.print(entry.getValue().data); } } // Driver Program to test above functions public static void main(String[] args) { /* Create following Binary Tree 1 / \ 2 3 \ 4 \ 5 \ 6*/ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.right = new Node(4); tree.root.left.right.right = new Node(5); tree.root.left.right.right.right = new Node(6); System.out.println( "Following are nodes in top view of Binary Tree"); tree.TopView(tree.root); }} # Python3 program to print top# view of binary tree # Binary Tree Node""" utility that allocates a newNodewith the given key """ class newNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None self.hd = 0 # function should print the topView# of the binary tree def topview(root): if(root == None): return q = [] m = dict() hd = 0 root.hd = hd # push node and horizontal # distance to queue q.append(root) while(len(q)): root = q[0] hd = root.hd # count function returns 1 if the # container contains an element # whose key is equivalent to hd, # or returns zero otherwise. if hd not in m: m[hd] = root.data if(root.left): root.left.hd = hd - 1 q.append(root.left) if(root.right): root.right.hd = hd + 1 q.append(root.right) q.pop(0) for i in sorted(m): print(m[i], end="") # Driver Codeif __name__ == '__main__': """ Create following Binary Tree 1 / \ 2 3 \ 4 \ 5 \ 6*""" root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.right = newNode(4) root.left.right.right = newNode(5) root.left.right.right.right = newNode(6) print("Following are nodes in top", "view of Binary Tree") topview(root) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) // C# program to print top// view of binary treeusing System;using System.Collections;using System.Collections.Generic; // Class to create a nodeclass Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }}; class QueueObj { public Node node; public int hd; public QueueObj(Node node, int hd) { this.node = node; this.hd = hd; }}; // Class of binary treeclass BinaryTree { Node root; public BinaryTree() { root = null; } // function should print the topView of // the binary tree void TopView(Node root) { Queue q = new Queue(); SortedDictionary<int, Node> topViewMap = new SortedDictionary<int, Node>(); if (root == null) { return; } else { q.Enqueue(new QueueObj(root, 0)); } // count function returns 1 if the container // contains an element whose key is equivalent // to hd, or returns zero otherwise. while (q.Count != 0) { QueueObj tmpNode = (QueueObj)q.Dequeue(); if (!topViewMap.ContainsKey(tmpNode.hd)) { topViewMap[tmpNode.hd] = tmpNode.node; } if (tmpNode.node.left != null) { q.Enqueue(new QueueObj(tmpNode.node.left, tmpNode.hd - 1)); } if (tmpNode.node.right != null) { q.Enqueue(new QueueObj(tmpNode.node.right, tmpNode.hd + 1)); } } foreach(var entry in topViewMap.Values) { Console.Write(entry.data); } } // Driver code public static void Main(string[] args) { /* Create following Binary Tree 1 / \ 2 3 \ 4 \ 5 \ 6*/ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.right = new Node(4); tree.root.left.right.right = new Node(5); tree.root.left.right.right.right = new Node(6); Console.WriteLine("Following are nodes " + "in top view of Binary Tree"); tree.TopView(tree.root); }} // This code is contributed by rutvik_56 <script>// Javascript program to print top// view of binary tree class Node{ constructor(data) { this.data=data; this.left = this.right = null; this.hd = 0; }} // Driver Codefunction topview(root){ if(root == null) return; let q = []; let m = new Map(); let hd = 0; root.hd = hd; q.push(root); while(q.length!=0) { root = q[0]; hd = root.hd; if(!m.has(hd)) m.set(hd,root.data); if(root.left) { root.left.hd = hd - 1; q.push(root.left); } if(root.right) { root.right.hd = hd + 1; q.push(root.right); } q.shift() } let arr = Array.from(m); arr.sort(function(a,b){return a[0]-b[0];}) for (let [key, value] of arr.values()) { document.write(value+" "); }} let root = new Node(1)root.left = new Node(2)root.right = new Node(3)root.left.right = new Node(4)root.left.right.right = new Node(5)root.left.right.right.right = new Node(6)document.write("Following are nodes in top", "view of Binary Tree<br>")topview(root) // This code is contributed by avanitrachhadiya2155</script> Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English default, selected This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Following are nodes in top view of Binary Tree The top view of the tree is : 2 1 3 6 Time complexity : O(n) Auxiliary Space : O(n) Another approach: This approach does not require a queue. Here we use the two variables, one for vertical distance of current node from the root and another for the depth of the current node from the root. We use the vertical distance for indexing. If one node with the same vertical distance comes again, we check if depth of new node is lower or higher with respect to the current node with same vertical distance in the map. If depth of new node is lower, then we replace it. Implementation: C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; // Structure of binary treestruct Node { Node* left; Node* right; int data;}; // function to create a new nodeNode* newNode(int key){ Node* node = new Node(); node->left = node->right = NULL; node->data = key; return node;} // function to fill the mapvoid fillMap(Node* root, int d, int l, map<int, pair<int, int> >& m){ if (root == NULL) return; if (m.count(d) == 0) { m[d] = make_pair(root->data, l); } else if (m[d].second > l) { m[d] = make_pair(root->data, l); } fillMap(root->left, d - 1, l + 1, m); fillMap(root->right, d + 1, l + 1, m);} // function should print the topView of// the binary treevoid topView(struct Node* root){ // map to store the pair of node value and its level // with respect to the vertical distance from root. map<int, pair<int, int> > m; // fillmap(root,vectical_distance_from_root,level_of_node,map) fillMap(root, 0, 0, m); for (auto it = m.begin(); it != m.end(); it++) { cout << it->second.first << " "; }}// Driver Program to test above functionsint main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->right = newNode(4); root->left->right->right = newNode(5); root->left->right->right->right = newNode(6); cout << "Following are nodes in top view of Binary " "Tree\n"; topView(root); return 0;}/* This code is contributed by Akash Debnath */ // Java program to print top// view of binary treeimport java.util.*; class GFG { // Structure of binary tree static class Node { Node left; Node right; int data; } static class pair { int first, second; pair() {} pair(int i, int j) { first = i; second = j; } } // map to store the pair of node value and // its level with respect to the vertical // distance from root. static TreeMap<Integer, pair> m = new TreeMap<>(); // function to create a new node static Node newNode(int key) { Node node = new Node(); node.left = node.right = null; node.data = key; return node; } // function to fill the map static void fillMap(Node root, int d, int l) { if (root == null) return; if (m.get(d) == null) { m.put(d, new pair(root.data, l)); } else if (m.get(d).second > l) { m.put(d, new pair(root.data, l)); } fillMap(root.left, d - 1, l + 1); fillMap(root.right, d + 1, l + 1); } // function should print the topView of // the binary tree static void topView(Node root) { fillMap(root, 0, 0); for (Map.Entry<Integer, pair> entry : m.entrySet()) { System.out.print(entry.getValue().first + " "); } } // Driver Code public static void main(String args[]) { Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.right = newNode(4); root.left.right.right = newNode(5); root.left.right.right.right = newNode(6); System.out.println("Following are nodes in" + " top view of Binary Tree"); topView(root); }} // This code is contributed by Arnab Kundu # Binary Tree Node""" utility that allocates a newNodewith the given key """ class newNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None # function to fill the map def fillMap(root, d, l, m): if(root == None): return if d not in m: m[d] = [root.data, l] elif(m[d][1] > l): m[d] = [root.data, l] fillMap(root.left, d - 1, l + 1, m) fillMap(root.right, d + 1, l + 1, m) # function should print the topView of# the binary tree def topView(root): # map to store the pair of node value and its level # with respect to the vertical distance from root. m = {} fillMap(root, 0, 0, m) for it in sorted(m.keys()): print(m[it][0], end=" ") # Driver Coderoot = newNode(1)root.left = newNode(2)root.right = newNode(3)root.left.right = newNode(4)root.left.right.right = newNode(5)root.left.right.right.right = newNode(6)print("Following are nodes in top view of Binary Tree")topView(root) # This code is contributed by SHUBHAMSINGH10 // C# program to print top// view of binary treeusing System;using System.Collections;using System.Collections.Generic; class GFG { // Structure of binary tree class Node { public Node left; public Node right; public int data; } class pair { public int first, second; public pair(int i, int j) { first = i; second = j; } } // map to store the pair of node value and // its level with respect to the vertical // distance from root. static SortedDictionary<int, pair> m = new SortedDictionary<int, pair>(); // function to create a new node static Node newNode(int key) { Node node = new Node(); node.left = node.right = null; node.data = key; return node; } // function to fill the map static void fillMap(Node root, int d, int l) { if (root == null) return; if (!m.ContainsKey(d)) { m[d] = new pair(root.data, l); } else if (m[d].second > l) { m[d] = new pair(root.data, l); } fillMap(root.left, d - 1, l + 1); fillMap(root.right, d + 1, l + 1); } // function should print the topView of // the binary tree static void topView(Node root) { fillMap(root, 0, 0); foreach(pair entry in m.Values) { Console.Write(entry.first + " "); } } // Driver Code public static void Main(string[] args) { Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.right = newNode(4); root.left.right.right = newNode(5); root.left.right.right.right = newNode(6); Console.WriteLine("Following are nodes in" + " top view of Binary Tree"); topView(root); }} // This code is contributed by pratham76 <script>// Javascript program to print top// view of binary tree // Structure of binary treeclass Node{ constructor() { this.data = 0; this.left = this.right = null; }} class pair{ constructor(i, j) { this.first = i; this.second = j; }} // map to store the pair of node value and // its level with respect to the vertical // distance from root.let m = new Map(); // function to create a new node function newNode(key){ let node = new Node(); node.left = node.right = null; node.data = key; return node;} // function to fill the mapfunction fillMap(root, d, l){ if (root == null) return; if (m.get(d) == null) { m.set(d, new pair(root.data, l)); } else if (m.get(d).second > l) { m.set(d, new pair(root.data, l)); } fillMap(root.left, d - 1, l + 1); fillMap(root.right, d + 1, l + 1);} // function should print the topView of // the binary treefunction topView(root){ fillMap(root, 0, 0); let arr=Array.from(m.keys()); arr.sort(function(a,b){return a-b;}); for (let key of arr.values()) { document.write(m.get(key).first + " "); }} // Driver Codelet root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.right = newNode(4);root.left.right.right = newNode(5);root.left.right.right.right = newNode(6);document.write("Following are nodes in" + " top view of Binary Tree<br>");topView(root); // This code is contributed by rag2127</script> Following are nodes in top view of Binary Tree 2 1 3 6 Time complexity : O(nlogn) Auxiliary Space : O(n) Time Complexity of the above implementation is O(nlogn) where n is the number of nodes in the given binary tree with each insertion operation in Map requiring O(log2n) complexity. Another approach: This approach is based on the level order traversal. We’ll keep record of current max so far left, right horizontal distances from the root.And if we found less distance (or greater in magnitude) then max left so far distance then update it and also push data on this node to a stack (stack is used because in level order traversal the left nodes will appear in reverse order), or if we found greater distance then max right so far distance then update it and also push data on this node to a vector.In this approach, no map is used. This approach is based on the level order traversal. We’ll keep record of current max so far left, right horizontal distances from the root. And if we found less distance (or greater in magnitude) then max left so far distance then update it and also push data on this node to a stack (stack is used because in level order traversal the left nodes will appear in reverse order), or if we found greater distance then max right so far distance then update it and also push data on this node to a vector. In this approach, no map is used. Implementation: C++14 // C++ Program to print Top View of a binary Tree #include <iostream>#include <queue>#include <stack>using namespace std; // class for Tree nodeclass Node {public: Node *left, *right; int data; Node() { left = right = 0; } Node(int data) { left = right = 0; this->data = data; }}; /* 1 / \ 2 3 \ 4 \ 5 \ 6 Top view of the above binary tree is 2 1 3 6*/ // class for Treeclass Tree {public: Node* root; Tree() { root = 0; } void topView() { // queue for holding nodes and their horizontal // distance from the root node queue<pair<Node*, int> > q; // pushing root node with distance 0 q.push(make_pair(root, 0)); // hd is current node's horizontal distance from // root node l is current left min horizontal // distance (or max in magnitude) so far from the // root node r is current right max horizontal // distance so far from the root node int hd = 0, l = 0, r = 0; // stack is for holding left node's data because // they will appear in reverse order that is why // using stack stack<int> left; // vector is for holding right node's data vector<int> right; Node* node; while (q.size()) { node = q.front().first; hd = q.front().second; if (hd < l) { left.push(node->data); l = hd; } else if (hd > r) { right.push_back(node->data); r = hd; } if (node->left) { q.push(make_pair(node->left, hd - 1)); } if (node->right) { q.push(make_pair(node->right, hd + 1)); } q.pop(); } // printing the left node's data in reverse order while (left.size()) { cout << left.top() << " "; left.pop(); } // then printing the root node's data cout << root->data << " "; // finally printing the right node's data for (auto x : right) { cout << x << " "; } }}; // Driver codeint main(){ // Tree object Tree t; t.root = new Node(1); t.root->left = new Node(2); t.root->right = new Node(3); t.root->left->right = new Node(4); t.root->left->right->right = new Node(5); t.root->left->right->right->right = new Node(6); t.topView(); cout << endl; return 0;} 2 1 3 6 As no Map is used, Time Complexity of the above implementation is O(n) where n is the number of nodes in the given binary tree. This article is contributed by Rohan. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Another Approach: This approach is built upon the level order traversal with hash map approach discussed above. I just made a simple tweek to reduce the overall time complexity of the algorithm. Since sorting is involved, the Time Complexity of the below implementation is O(N) where N is the number of nodes in the Binary Tree and the Space Complexity is O((depth of binary tree * 2) – 1) in worst case. Implementation: Python3 # Python program for the above approachfrom queue import deque def topView(root): dic = {} # variable which is going to store # the minimum positional value. mi = float('inf') if not root: return ret q = deque([(root, 0)]) while q: cur = q.popleft() if cur[1] not in dic: dic[cur[1]] = cur[0].data mi = min(mi, cur[1]) if cur[0].left: q.append((cur[0].left, cur[1] - 1)) if cur[0].right: q.append((cur[0].right, cur[1] + 1)) # Starting from the leftmost node and # just incrementing it until # the rightmost node stored in the dic. while mi in dic: print(dic[mi], end=' ') mi += 1 class Node: def __init__(self, val): self.data = val self.left = None self.right = None # Driver Codeif __name__ == '__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.left.right = Node(4) root.left.right.right = Node(5) root.left.right.right.right = Node(6) print("Top view of Binary Tree (from left to right) is as follows:") topView(root) # This code is contributed by Karthikayan Mailsamy. Top view of Binary Tree (from left to right) is as follows: 2 1 3 6 Time Complexity: O(N) Space complexity: O(N) for queue Aarsee AdarshKL Md.Shahazad Uddin SHUBHAMSINGH10 akashdebnath andrew1234 rutvik_56 pratham76 mjustboring karthikayanmailsamy avanitrachhadiya2155 rag2127 Kirti_Mangal ce20b112 deadvikash guptaishan noviced3vq6 hardikkoriintern Amazon BFS Paytm Samsung tree-view Walmart Hash Queue Tree Paytm Amazon Samsung Walmart Hash Queue Tree BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) What is Hashing | A Complete Tutorial Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Count pairs with given sum Breadth First Search or BFS for a Graph Queue in Python Queue Interface In Java Introduction to Data Structures Queue using Stacks
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2022" }, { "code": null, "e": 239, "s": 54, "text": "Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes can be printed in any order." }, { "code": null, "e": 473, "s": 239, "text": "A node x is there in output if x is the topmost node at its horizontal distance. Horizontal distance of left child of a node x is equal to horizontal distance of x minus 1, and that of right child is horizontal distance of x plus 1. " }, { "code": null, "e": 746, "s": 473, "text": " 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\nTop view of the above binary tree is\n4 2 1 3 7\n\n 1\n / \\\n 2 3\n \\ \n 4 \n \\\n 5\n \\\n 6\nTop view of the above binary tree is\n2 1 3 6" }, { "code": null, "e": 1129, "s": 746, "text": "The idea is to do something similar to vertical Order Traversal. Like vertical Order Traversal, we need to put nodes of same horizontal distance together. We do a level order traversal so that the topmost node at a horizontal node is visited before any other node of same horizontal distance below it. Hashing is used to check if a node at given horizontal distance is seen or not. " }, { "code": null, "e": 1145, "s": 1129, "text": "Implementation:" }, { "code": null, "e": 1151, "s": 1145, "text": "C++14" }, { "code": null, "e": 1156, "s": 1151, "text": "Java" }, { "code": null, "e": 1164, "s": 1156, "text": "Python3" }, { "code": null, "e": 1167, "s": 1164, "text": "C#" }, { "code": null, "e": 1178, "s": 1167, "text": "Javascript" }, { "code": "// C++ program to print top// view of binary tree #include <bits/stdc++.h>using namespace std; // Structure of binary treestruct Node{ Node* left; Node* right; int hd; int data;}; // function to create a new nodeNode* newNode(int key){ Node* node = new Node(); node -> left = node -> right = NULL; node -> data = key; return node;} // function should print the topView of// the binary treevoid topview(Node* root){ if (root == NULL) return; queue<Node*> q; map<int, int> m; int hd = 0; root -> hd = hd; // push node and horizontal distance to queue q.push(root); cout << \"The top view of the tree is : \\n\"; while (q.size()) { hd = root -> hd; // count function returns 1 if the container // contains an element whose key is equivalent // to hd, or returns zero otherwise. if (m.count(hd) == 0) m[hd] = root -> data; if (root -> left) { root -> left -> hd = hd - 1; q.push(root -> left); } if (root -> right) { root -> right -> hd = hd + 1; q.push(root -> right); } q.pop(); root = q.front(); } for (auto i = m.begin(); i != m.end(); i++) { cout << i -> second << \" \"; }} // Driver Program to test above functionsint main(){ /* Create following Binary Tree 1 / \\ 2 3 \\ 4 \\ 5 \\ 6*/ Node* root = newNode(1); root -> left = newNode(2); root -> right = newNode(3); root -> left -> right = newNode(4); root -> left -> right -> right = newNode(5); root -> left -> right -> right -> right = newNode(6); cout << \"Following are nodes in top view of Binary \" \"Tree\\n\"; topview(root); return 0;}/* This code is contributed by Niteesh Kumar */", "e": 3048, "s": 1178, "text": null }, { "code": "// Java program to print top// view of binary treeimport java.util.LinkedList;import java.util.Map;import java.util.Map.Entry;import java.util.Queue;import java.util.TreeMap; // class to create a nodeclass Node { int data; Node left, right; public Node(int data) { this.data = data; left = right = null; }} // class of binary treeclass BinaryTree { Node root; public BinaryTree() { root = null; } // function should print the topView of // the binary tree private void TopView(Node root) { class QueueObj { Node node; int hd; QueueObj(Node node, int hd) { this.node = node; this.hd = hd; } } Queue<QueueObj> q = new LinkedList<QueueObj>(); Map<Integer, Node> topViewMap = new TreeMap<Integer, Node>(); if (root == null) { return; } else { q.add(new QueueObj(root, 0)); } System.out.println( \"The top view of the tree is : \"); // count function returns 1 if the container // contains an element whose key is equivalent // to hd, or returns zero otherwise. while (!q.isEmpty()) { QueueObj tmpNode = q.poll(); if (!topViewMap.containsKey(tmpNode.hd)) { topViewMap.put(tmpNode.hd, tmpNode.node); } if (tmpNode.node.left != null) { q.add(new QueueObj(tmpNode.node.left, tmpNode.hd - 1)); } if (tmpNode.node.right != null) { q.add(new QueueObj(tmpNode.node.right, tmpNode.hd + 1)); } } for (Map.Entry<Integer, Node> entry : topViewMap.entrySet()) { System.out.print(entry.getValue().data); } } // Driver Program to test above functions public static void main(String[] args) { /* Create following Binary Tree 1 / \\ 2 3 \\ 4 \\ 5 \\ 6*/ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.right = new Node(4); tree.root.left.right.right = new Node(5); tree.root.left.right.right.right = new Node(6); System.out.println( \"Following are nodes in top view of Binary Tree\"); tree.TopView(tree.root); }}", "e": 5619, "s": 3048, "text": null }, { "code": "# Python3 program to print top# view of binary tree # Binary Tree Node\"\"\" utility that allocates a newNodewith the given key \"\"\" class newNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None self.hd = 0 # function should print the topView# of the binary tree def topview(root): if(root == None): return q = [] m = dict() hd = 0 root.hd = hd # push node and horizontal # distance to queue q.append(root) while(len(q)): root = q[0] hd = root.hd # count function returns 1 if the # container contains an element # whose key is equivalent to hd, # or returns zero otherwise. if hd not in m: m[hd] = root.data if(root.left): root.left.hd = hd - 1 q.append(root.left) if(root.right): root.right.hd = hd + 1 q.append(root.right) q.pop(0) for i in sorted(m): print(m[i], end=\"\") # Driver Codeif __name__ == '__main__': \"\"\" Create following Binary Tree 1 / \\ 2 3 \\ 4 \\ 5 \\ 6*\"\"\" root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.right = newNode(4) root.left.right.right = newNode(5) root.left.right.right.right = newNode(6) print(\"Following are nodes in top\", \"view of Binary Tree\") topview(root) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 7195, "s": 5619, "text": null }, { "code": "// C# program to print top// view of binary treeusing System;using System.Collections;using System.Collections.Generic; // Class to create a nodeclass Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = right = null; }}; class QueueObj { public Node node; public int hd; public QueueObj(Node node, int hd) { this.node = node; this.hd = hd; }}; // Class of binary treeclass BinaryTree { Node root; public BinaryTree() { root = null; } // function should print the topView of // the binary tree void TopView(Node root) { Queue q = new Queue(); SortedDictionary<int, Node> topViewMap = new SortedDictionary<int, Node>(); if (root == null) { return; } else { q.Enqueue(new QueueObj(root, 0)); } // count function returns 1 if the container // contains an element whose key is equivalent // to hd, or returns zero otherwise. while (q.Count != 0) { QueueObj tmpNode = (QueueObj)q.Dequeue(); if (!topViewMap.ContainsKey(tmpNode.hd)) { topViewMap[tmpNode.hd] = tmpNode.node; } if (tmpNode.node.left != null) { q.Enqueue(new QueueObj(tmpNode.node.left, tmpNode.hd - 1)); } if (tmpNode.node.right != null) { q.Enqueue(new QueueObj(tmpNode.node.right, tmpNode.hd + 1)); } } foreach(var entry in topViewMap.Values) { Console.Write(entry.data); } } // Driver code public static void Main(string[] args) { /* Create following Binary Tree 1 / \\ 2 3 \\ 4 \\ 5 \\ 6*/ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.right = new Node(4); tree.root.left.right.right = new Node(5); tree.root.left.right.right.right = new Node(6); Console.WriteLine(\"Following are nodes \" + \"in top view of Binary Tree\"); tree.TopView(tree.root); }} // This code is contributed by rutvik_56", "e": 9627, "s": 7195, "text": null }, { "code": "<script>// Javascript program to print top// view of binary tree class Node{ constructor(data) { this.data=data; this.left = this.right = null; this.hd = 0; }} // Driver Codefunction topview(root){ if(root == null) return; let q = []; let m = new Map(); let hd = 0; root.hd = hd; q.push(root); while(q.length!=0) { root = q[0]; hd = root.hd; if(!m.has(hd)) m.set(hd,root.data); if(root.left) { root.left.hd = hd - 1; q.push(root.left); } if(root.right) { root.right.hd = hd + 1; q.push(root.right); } q.shift() } let arr = Array.from(m); arr.sort(function(a,b){return a[0]-b[0];}) for (let [key, value] of arr.values()) { document.write(value+\" \"); }} let root = new Node(1)root.left = new Node(2)root.right = new Node(3)root.left.right = new Node(4)root.left.right.right = new Node(5)root.left.right.right.right = new Node(6)document.write(\"Following are nodes in top\", \"view of Binary Tree<br>\")topview(root) // This code is contributed by avanitrachhadiya2155</script>", "e": 10830, "s": 9627, "text": null }, { "code": null, "e": 10839, "s": 10830, "text": "Chapters" }, { "code": null, "e": 10866, "s": 10839, "text": "descriptions off, selected" }, { "code": null, "e": 10916, "s": 10866, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 10939, "s": 10916, "text": "captions off, selected" }, { "code": null, "e": 10947, "s": 10939, "text": "English" }, { "code": null, "e": 10965, "s": 10947, "text": "default, selected" }, { "code": null, "e": 10989, "s": 10965, "text": "This is a modal window." }, { "code": null, "e": 11058, "s": 10989, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 11080, "s": 11058, "text": "End of dialog window." }, { "code": null, "e": 11167, "s": 11080, "text": "Following are nodes in top view of Binary Tree\nThe top view of the tree is : \n2 1 3 6 " }, { "code": null, "e": 11213, "s": 11167, "text": "Time complexity : O(n) Auxiliary Space : O(n)" }, { "code": null, "e": 11692, "s": 11213, "text": "Another approach: This approach does not require a queue. Here we use the two variables, one for vertical distance of current node from the root and another for the depth of the current node from the root. We use the vertical distance for indexing. If one node with the same vertical distance comes again, we check if depth of new node is lower or higher with respect to the current node with same vertical distance in the map. If depth of new node is lower, then we replace it." }, { "code": null, "e": 11708, "s": 11692, "text": "Implementation:" }, { "code": null, "e": 11712, "s": 11708, "text": "C++" }, { "code": null, "e": 11717, "s": 11712, "text": "Java" }, { "code": null, "e": 11725, "s": 11717, "text": "Python3" }, { "code": null, "e": 11728, "s": 11725, "text": "C#" }, { "code": null, "e": 11739, "s": 11728, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // Structure of binary treestruct Node { Node* left; Node* right; int data;}; // function to create a new nodeNode* newNode(int key){ Node* node = new Node(); node->left = node->right = NULL; node->data = key; return node;} // function to fill the mapvoid fillMap(Node* root, int d, int l, map<int, pair<int, int> >& m){ if (root == NULL) return; if (m.count(d) == 0) { m[d] = make_pair(root->data, l); } else if (m[d].second > l) { m[d] = make_pair(root->data, l); } fillMap(root->left, d - 1, l + 1, m); fillMap(root->right, d + 1, l + 1, m);} // function should print the topView of// the binary treevoid topView(struct Node* root){ // map to store the pair of node value and its level // with respect to the vertical distance from root. map<int, pair<int, int> > m; // fillmap(root,vectical_distance_from_root,level_of_node,map) fillMap(root, 0, 0, m); for (auto it = m.begin(); it != m.end(); it++) { cout << it->second.first << \" \"; }}// Driver Program to test above functionsint main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->right = newNode(4); root->left->right->right = newNode(5); root->left->right->right->right = newNode(6); cout << \"Following are nodes in top view of Binary \" \"Tree\\n\"; topView(root); return 0;}/* This code is contributed by Akash Debnath */", "e": 13253, "s": 11739, "text": null }, { "code": "// Java program to print top// view of binary treeimport java.util.*; class GFG { // Structure of binary tree static class Node { Node left; Node right; int data; } static class pair { int first, second; pair() {} pair(int i, int j) { first = i; second = j; } } // map to store the pair of node value and // its level with respect to the vertical // distance from root. static TreeMap<Integer, pair> m = new TreeMap<>(); // function to create a new node static Node newNode(int key) { Node node = new Node(); node.left = node.right = null; node.data = key; return node; } // function to fill the map static void fillMap(Node root, int d, int l) { if (root == null) return; if (m.get(d) == null) { m.put(d, new pair(root.data, l)); } else if (m.get(d).second > l) { m.put(d, new pair(root.data, l)); } fillMap(root.left, d - 1, l + 1); fillMap(root.right, d + 1, l + 1); } // function should print the topView of // the binary tree static void topView(Node root) { fillMap(root, 0, 0); for (Map.Entry<Integer, pair> entry : m.entrySet()) { System.out.print(entry.getValue().first + \" \"); } } // Driver Code public static void main(String args[]) { Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.right = newNode(4); root.left.right.right = newNode(5); root.left.right.right.right = newNode(6); System.out.println(\"Following are nodes in\" + \" top view of Binary Tree\"); topView(root); }} // This code is contributed by Arnab Kundu", "e": 15120, "s": 13253, "text": null }, { "code": "# Binary Tree Node\"\"\" utility that allocates a newNodewith the given key \"\"\" class newNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None # function to fill the map def fillMap(root, d, l, m): if(root == None): return if d not in m: m[d] = [root.data, l] elif(m[d][1] > l): m[d] = [root.data, l] fillMap(root.left, d - 1, l + 1, m) fillMap(root.right, d + 1, l + 1, m) # function should print the topView of# the binary tree def topView(root): # map to store the pair of node value and its level # with respect to the vertical distance from root. m = {} fillMap(root, 0, 0, m) for it in sorted(m.keys()): print(m[it][0], end=\" \") # Driver Coderoot = newNode(1)root.left = newNode(2)root.right = newNode(3)root.left.right = newNode(4)root.left.right.right = newNode(5)root.left.right.right.right = newNode(6)print(\"Following are nodes in top view of Binary Tree\")topView(root) # This code is contributed by SHUBHAMSINGH10", "e": 16196, "s": 15120, "text": null }, { "code": "// C# program to print top// view of binary treeusing System;using System.Collections;using System.Collections.Generic; class GFG { // Structure of binary tree class Node { public Node left; public Node right; public int data; } class pair { public int first, second; public pair(int i, int j) { first = i; second = j; } } // map to store the pair of node value and // its level with respect to the vertical // distance from root. static SortedDictionary<int, pair> m = new SortedDictionary<int, pair>(); // function to create a new node static Node newNode(int key) { Node node = new Node(); node.left = node.right = null; node.data = key; return node; } // function to fill the map static void fillMap(Node root, int d, int l) { if (root == null) return; if (!m.ContainsKey(d)) { m[d] = new pair(root.data, l); } else if (m[d].second > l) { m[d] = new pair(root.data, l); } fillMap(root.left, d - 1, l + 1); fillMap(root.right, d + 1, l + 1); } // function should print the topView of // the binary tree static void topView(Node root) { fillMap(root, 0, 0); foreach(pair entry in m.Values) { Console.Write(entry.first + \" \"); } } // Driver Code public static void Main(string[] args) { Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.right = newNode(4); root.left.right.right = newNode(5); root.left.right.right.right = newNode(6); Console.WriteLine(\"Following are nodes in\" + \" top view of Binary Tree\"); topView(root); }} // This code is contributed by pratham76", "e": 18095, "s": 16196, "text": null }, { "code": "<script>// Javascript program to print top// view of binary tree // Structure of binary treeclass Node{ constructor() { this.data = 0; this.left = this.right = null; }} class pair{ constructor(i, j) { this.first = i; this.second = j; }} // map to store the pair of node value and // its level with respect to the vertical // distance from root.let m = new Map(); // function to create a new node function newNode(key){ let node = new Node(); node.left = node.right = null; node.data = key; return node;} // function to fill the mapfunction fillMap(root, d, l){ if (root == null) return; if (m.get(d) == null) { m.set(d, new pair(root.data, l)); } else if (m.get(d).second > l) { m.set(d, new pair(root.data, l)); } fillMap(root.left, d - 1, l + 1); fillMap(root.right, d + 1, l + 1);} // function should print the topView of // the binary treefunction topView(root){ fillMap(root, 0, 0); let arr=Array.from(m.keys()); arr.sort(function(a,b){return a-b;}); for (let key of arr.values()) { document.write(m.get(key).first + \" \"); }} // Driver Codelet root = newNode(1);root.left = newNode(2);root.right = newNode(3);root.left.right = newNode(4);root.left.right.right = newNode(5);root.left.right.right.right = newNode(6);document.write(\"Following are nodes in\" + \" top view of Binary Tree<br>\");topView(root); // This code is contributed by rag2127</script>", "e": 19681, "s": 18095, "text": null }, { "code": null, "e": 19737, "s": 19681, "text": "Following are nodes in top view of Binary Tree\n2 1 3 6 " }, { "code": null, "e": 19787, "s": 19737, "text": "Time complexity : O(nlogn) Auxiliary Space : O(n)" }, { "code": null, "e": 19967, "s": 19787, "text": "Time Complexity of the above implementation is O(nlogn) where n is the number of nodes in the given binary tree with each insertion operation in Map requiring O(log2n) complexity." }, { "code": null, "e": 19985, "s": 19967, "text": "Another approach:" }, { "code": null, "e": 20519, "s": 19985, "text": "This approach is based on the level order traversal. We’ll keep record of current max so far left, right horizontal distances from the root.And if we found less distance (or greater in magnitude) then max left so far distance then update it and also push data on this node to a stack (stack is used because in level order traversal the left nodes will appear in reverse order), or if we found greater distance then max right so far distance then update it and also push data on this node to a vector.In this approach, no map is used." }, { "code": null, "e": 20660, "s": 20519, "text": "This approach is based on the level order traversal. We’ll keep record of current max so far left, right horizontal distances from the root." }, { "code": null, "e": 21021, "s": 20660, "text": "And if we found less distance (or greater in magnitude) then max left so far distance then update it and also push data on this node to a stack (stack is used because in level order traversal the left nodes will appear in reverse order), or if we found greater distance then max right so far distance then update it and also push data on this node to a vector." }, { "code": null, "e": 21055, "s": 21021, "text": "In this approach, no map is used." }, { "code": null, "e": 21071, "s": 21055, "text": "Implementation:" }, { "code": null, "e": 21077, "s": 21071, "text": "C++14" }, { "code": "// C++ Program to print Top View of a binary Tree #include <iostream>#include <queue>#include <stack>using namespace std; // class for Tree nodeclass Node {public: Node *left, *right; int data; Node() { left = right = 0; } Node(int data) { left = right = 0; this->data = data; }}; /* 1 / \\ 2 3 \\ 4 \\ 5 \\ 6 Top view of the above binary tree is 2 1 3 6*/ // class for Treeclass Tree {public: Node* root; Tree() { root = 0; } void topView() { // queue for holding nodes and their horizontal // distance from the root node queue<pair<Node*, int> > q; // pushing root node with distance 0 q.push(make_pair(root, 0)); // hd is current node's horizontal distance from // root node l is current left min horizontal // distance (or max in magnitude) so far from the // root node r is current right max horizontal // distance so far from the root node int hd = 0, l = 0, r = 0; // stack is for holding left node's data because // they will appear in reverse order that is why // using stack stack<int> left; // vector is for holding right node's data vector<int> right; Node* node; while (q.size()) { node = q.front().first; hd = q.front().second; if (hd < l) { left.push(node->data); l = hd; } else if (hd > r) { right.push_back(node->data); r = hd; } if (node->left) { q.push(make_pair(node->left, hd - 1)); } if (node->right) { q.push(make_pair(node->right, hd + 1)); } q.pop(); } // printing the left node's data in reverse order while (left.size()) { cout << left.top() << \" \"; left.pop(); } // then printing the root node's data cout << root->data << \" \"; // finally printing the right node's data for (auto x : right) { cout << x << \" \"; } }}; // Driver codeint main(){ // Tree object Tree t; t.root = new Node(1); t.root->left = new Node(2); t.root->right = new Node(3); t.root->left->right = new Node(4); t.root->left->right->right = new Node(5); t.root->left->right->right->right = new Node(6); t.topView(); cout << endl; return 0;}", "e": 23639, "s": 21077, "text": null }, { "code": null, "e": 23648, "s": 23639, "text": "2 1 3 6 " }, { "code": null, "e": 23776, "s": 23648, "text": "As no Map is used, Time Complexity of the above implementation is O(n) where n is the number of nodes in the given binary tree." }, { "code": null, "e": 23940, "s": 23776, "text": "This article is contributed by Rohan. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 24135, "s": 23940, "text": "Another Approach: This approach is built upon the level order traversal with hash map approach discussed above. I just made a simple tweek to reduce the overall time complexity of the algorithm." }, { "code": null, "e": 24346, "s": 24135, "text": "Since sorting is involved, the Time Complexity of the below implementation is O(N) where N is the number of nodes in the Binary Tree and the Space Complexity is O((depth of binary tree * 2) – 1) in worst case. " }, { "code": null, "e": 24362, "s": 24346, "text": "Implementation:" }, { "code": null, "e": 24370, "s": 24362, "text": "Python3" }, { "code": "# Python program for the above approachfrom queue import deque def topView(root): dic = {} # variable which is going to store # the minimum positional value. mi = float('inf') if not root: return ret q = deque([(root, 0)]) while q: cur = q.popleft() if cur[1] not in dic: dic[cur[1]] = cur[0].data mi = min(mi, cur[1]) if cur[0].left: q.append((cur[0].left, cur[1] - 1)) if cur[0].right: q.append((cur[0].right, cur[1] + 1)) # Starting from the leftmost node and # just incrementing it until # the rightmost node stored in the dic. while mi in dic: print(dic[mi], end=' ') mi += 1 class Node: def __init__(self, val): self.data = val self.left = None self.right = None # Driver Codeif __name__ == '__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.left.right = Node(4) root.left.right.right = Node(5) root.left.right.right.right = Node(6) print(\"Top view of Binary Tree (from left to right) is as follows:\") topView(root) # This code is contributed by Karthikayan Mailsamy.", "e": 25549, "s": 24370, "text": null }, { "code": null, "e": 25618, "s": 25549, "text": "Top view of Binary Tree (from left to right) is as follows:\n2 1 3 6 " }, { "code": null, "e": 25640, "s": 25618, "text": "Time Complexity: O(N)" }, { "code": null, "e": 25673, "s": 25640, "text": "Space complexity: O(N) for queue" }, { "code": null, "e": 25680, "s": 25673, "text": "Aarsee" }, { "code": null, "e": 25689, "s": 25680, "text": "AdarshKL" }, { "code": null, "e": 25707, "s": 25689, "text": "Md.Shahazad Uddin" }, { "code": null, "e": 25722, "s": 25707, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 25735, "s": 25722, "text": "akashdebnath" }, { "code": null, "e": 25746, "s": 25735, "text": "andrew1234" }, { "code": null, "e": 25756, "s": 25746, "text": "rutvik_56" }, { "code": null, "e": 25766, "s": 25756, "text": "pratham76" }, { "code": null, "e": 25778, "s": 25766, "text": "mjustboring" }, { "code": null, "e": 25798, "s": 25778, "text": "karthikayanmailsamy" }, { "code": null, "e": 25819, "s": 25798, "text": "avanitrachhadiya2155" }, { "code": null, "e": 25827, "s": 25819, "text": "rag2127" }, { "code": null, "e": 25840, "s": 25827, "text": "Kirti_Mangal" }, { "code": null, "e": 25849, "s": 25840, "text": "ce20b112" }, { "code": null, "e": 25860, "s": 25849, "text": "deadvikash" }, { "code": null, "e": 25871, "s": 25860, "text": "guptaishan" }, { "code": null, "e": 25883, "s": 25871, "text": "noviced3vq6" }, { "code": null, "e": 25900, "s": 25883, "text": "hardikkoriintern" }, { "code": null, "e": 25907, "s": 25900, "text": "Amazon" }, { "code": null, "e": 25911, "s": 25907, "text": "BFS" }, { "code": null, "e": 25917, "s": 25911, "text": "Paytm" }, { "code": null, "e": 25925, "s": 25917, "text": "Samsung" }, { "code": null, "e": 25935, "s": 25925, "text": "tree-view" }, { "code": null, "e": 25943, "s": 25935, "text": "Walmart" }, { "code": null, "e": 25948, "s": 25943, "text": "Hash" }, { "code": null, "e": 25954, "s": 25948, "text": "Queue" }, { "code": null, "e": 25959, "s": 25954, "text": "Tree" }, { "code": null, "e": 25965, "s": 25959, "text": "Paytm" }, { "code": null, "e": 25972, "s": 25965, "text": "Amazon" }, { "code": null, "e": 25980, "s": 25972, "text": "Samsung" }, { "code": null, "e": 25988, "s": 25980, "text": "Walmart" }, { "code": null, "e": 25993, "s": 25988, "text": "Hash" }, { "code": null, "e": 25999, "s": 25993, "text": "Queue" }, { "code": null, "e": 26004, "s": 25999, "text": "Tree" }, { "code": null, "e": 26008, "s": 26004, "text": "BFS" }, { "code": null, "e": 26106, "s": 26008, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26191, "s": 26106, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 26229, "s": 26191, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 26265, "s": 26229, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 26296, "s": 26265, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 26323, "s": 26296, "text": "Count pairs with given sum" }, { "code": null, "e": 26363, "s": 26323, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 26379, "s": 26363, "text": "Queue in Python" }, { "code": null, "e": 26403, "s": 26379, "text": "Queue Interface In Java" }, { "code": null, "e": 26435, "s": 26403, "text": "Introduction to Data Structures" } ]
Convert Stream to Set in Java
11 Dec, 2018 Below given are some methods which can be used to convert Stream to Set in Java. Stream collect() method takes elements from a stream and stores them in a collection.collect(Collector.toSet()) collects elements from a stream to a Set. Stream.collect() method can be used to collect elements of a stream in a container. The Collector which is returned by Collectors.toSet() can be passed that accumulates the elements of stream into a new Set. // Java code for converting // Stream to Set using Collectorsimport java.util.*;import java.util.stream.Stream;import java.util.stream.Collectors; class GFG { // Driver code public static void main(String[] args) { // Creating a Stream of Integers Stream<Integer> stream = Stream.of(-2, -1, 0, 1, 2); // Using Stream.collect() to collect the // elements of stream in a container. Set<Integer> streamSet = stream.collect(Collectors.toSet()); // Displaying the elements streamSet.forEach(num -> System.out.println(num)); }} -1 0 -2 1 2 The problem of converting Stream into Set can be divided into two parts : 1) Convert Stream to an Array 2) Convert Array to a Set // Java code for converting // Stream to Set using Divide // and Conquerimport java.util.*;import java.util.stream.Stream;import java.util.stream.Collectors; class GFG { // Driver code public static void main(String[] args) { // Creating a Stream of Strings Stream<String> stream = Stream.of("G", "E", "K", "S"); // Converting Stream into an Array String[] arr = stream.toArray(String[] :: new); // Creating a HashSet Set<String> set = new HashSet<>(); // Converting Array to set Collections.addAll(set,arr); // Displaying the elements set.forEach(str -> System.out.println(str)); }} S E G K Note : Output is random because HashSet takes input in random order as generated hash value. Stream can be converted into Set using forEach(). Loop through all elements of the stream using forEach() method and then use set.add() to add each elements into an empty set. // Java code for converting // Stream to Set using forEachimport java.util.*;import java.util.stream.Stream;import java.util.stream.Collectors; class GFG { // Driver code public static void main(String[] args) { // Creating a Stream of Integers Stream<Integer> stream = Stream.of(5, 10, 15, 20, 25); // Creating a HashSet Set<Integer> set = new HashSet<>(); // using set.add() to add elements // of stream into empty set stream.forEach(set::add); // Displaying the elements set.forEach(num -> System.out.println(num)); }} 20 5 25 10 15 Note : If Stream is parallel, then elements may not be processed in original order using forEach() method. To preserve the original order, forEachOrdered() method is used. Convert a Set to Stream in Java Java - util package Java-Collections java-hashset java-set Java-Set-Programs java-stream Java-Stream-programs Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Queue Interface In Java Object Oriented Programming (OOPs) Concept in Java Stack Class in Java Interfaces in Java ArrayList in Java HashMap in Java with Examples Collections in Java ChronoZonedDateTime isAfter() method in Java with Examples Multidimensional Arrays in Java Introduction to Java
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Dec, 2018" }, { "code": null, "e": 135, "s": 54, "text": "Below given are some methods which can be used to convert Stream to Set in Java." }, { "code": null, "e": 289, "s": 135, "text": "Stream collect() method takes elements from a stream and stores them in a collection.collect(Collector.toSet()) collects elements from a stream to a Set." }, { "code": null, "e": 497, "s": 289, "text": "Stream.collect() method can be used to collect elements of a stream in a container. The Collector which is returned by Collectors.toSet() can be passed that accumulates the elements of stream into a new Set." }, { "code": "// Java code for converting // Stream to Set using Collectorsimport java.util.*;import java.util.stream.Stream;import java.util.stream.Collectors; class GFG { // Driver code public static void main(String[] args) { // Creating a Stream of Integers Stream<Integer> stream = Stream.of(-2, -1, 0, 1, 2); // Using Stream.collect() to collect the // elements of stream in a container. Set<Integer> streamSet = stream.collect(Collectors.toSet()); // Displaying the elements streamSet.forEach(num -> System.out.println(num)); }}", "e": 1075, "s": 497, "text": null }, { "code": null, "e": 1088, "s": 1075, "text": "-1\n0\n-2\n1\n2\n" }, { "code": null, "e": 1162, "s": 1088, "text": "The problem of converting Stream into Set can be divided into two parts :" }, { "code": null, "e": 1219, "s": 1162, "text": "1) Convert Stream to an Array\n2) Convert Array to a Set\n" }, { "code": "// Java code for converting // Stream to Set using Divide // and Conquerimport java.util.*;import java.util.stream.Stream;import java.util.stream.Collectors; class GFG { // Driver code public static void main(String[] args) { // Creating a Stream of Strings Stream<String> stream = Stream.of(\"G\", \"E\", \"K\", \"S\"); // Converting Stream into an Array String[] arr = stream.toArray(String[] :: new); // Creating a HashSet Set<String> set = new HashSet<>(); // Converting Array to set Collections.addAll(set,arr); // Displaying the elements set.forEach(str -> System.out.println(str)); }}", "e": 1879, "s": 1219, "text": null }, { "code": null, "e": 1888, "s": 1879, "text": "S\nE\nG\nK\n" }, { "code": null, "e": 1981, "s": 1888, "text": "Note : Output is random because HashSet takes input in random order as generated hash value." }, { "code": null, "e": 2157, "s": 1981, "text": "Stream can be converted into Set using forEach(). Loop through all elements of the stream using forEach() method and then use set.add() to add each elements into an empty set." }, { "code": "// Java code for converting // Stream to Set using forEachimport java.util.*;import java.util.stream.Stream;import java.util.stream.Collectors; class GFG { // Driver code public static void main(String[] args) { // Creating a Stream of Integers Stream<Integer> stream = Stream.of(5, 10, 15, 20, 25); // Creating a HashSet Set<Integer> set = new HashSet<>(); // using set.add() to add elements // of stream into empty set stream.forEach(set::add); // Displaying the elements set.forEach(num -> System.out.println(num)); }}", "e": 2743, "s": 2157, "text": null }, { "code": null, "e": 2758, "s": 2743, "text": "20\n5\n25\n10\n15\n" }, { "code": null, "e": 2930, "s": 2758, "text": "Note : If Stream is parallel, then elements may not be processed in original order using forEach() method. To preserve the original order, forEachOrdered() method is used." }, { "code": null, "e": 2962, "s": 2930, "text": "Convert a Set to Stream in Java" }, { "code": null, "e": 2982, "s": 2962, "text": "Java - util package" }, { "code": null, "e": 2999, "s": 2982, "text": "Java-Collections" }, { "code": null, "e": 3012, "s": 2999, "text": "java-hashset" }, { "code": null, "e": 3021, "s": 3012, "text": "java-set" }, { "code": null, "e": 3039, "s": 3021, "text": "Java-Set-Programs" }, { "code": null, "e": 3051, "s": 3039, "text": "java-stream" }, { "code": null, "e": 3072, "s": 3051, "text": "Java-Stream-programs" }, { "code": null, "e": 3077, "s": 3072, "text": "Java" }, { "code": null, "e": 3082, "s": 3077, "text": "Java" }, { "code": null, "e": 3099, "s": 3082, "text": "Java-Collections" }, { "code": null, "e": 3197, "s": 3099, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3221, "s": 3197, "text": "Queue Interface In Java" }, { "code": null, "e": 3272, "s": 3221, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3292, "s": 3272, "text": "Stack Class in Java" }, { "code": null, "e": 3311, "s": 3292, "text": "Interfaces in Java" }, { "code": null, "e": 3329, "s": 3311, "text": "ArrayList in Java" }, { "code": null, "e": 3359, "s": 3329, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3379, "s": 3359, "text": "Collections in Java" }, { "code": null, "e": 3438, "s": 3379, "text": "ChronoZonedDateTime isAfter() method in Java with Examples" }, { "code": null, "e": 3470, "s": 3438, "text": "Multidimensional Arrays in Java" } ]
Generating sequenced Vectors in R Programming – sequence() Function
15 Jun, 2020 sequence() function in R Language is used to create a vector of sequenced elements. It creates vectors with specified length, and specified differences between elements. It is similar to seq() function. Syntax: sequence(x) Parameters:x: Maximum element of vector Example 1: # R program to create sequence of vectors # Calling sequence() functionsequence(4)sequence(6)sequence(c(4, 6)) Output: [1] 1 2 3 4 [1] 1 2 3 4 5 6 [1] 1 2 3 4 1 2 3 4 5 6 Example 2: # R program to create sequence of vectors # Calling sequence() functionsequence(1:4) # Performing operationsx <- 2 * sequence(4)x Output: [1] 1 1 2 1 2 3 1 2 3 4 [1] 2 4 6 8 R Vector-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R Loops in R (for, while, repeat) How to Split Column Into Multiple Columns in R DataFrame? Printing Output of an R Program Group by function in R using Dplyr How to change Row Names of DataFrame in R ? R Programming Language - Introduction How to Change Axis Scales in R Plots?
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Jun, 2020" }, { "code": null, "e": 231, "s": 28, "text": "sequence() function in R Language is used to create a vector of sequenced elements. It creates vectors with specified length, and specified differences between elements. It is similar to seq() function." }, { "code": null, "e": 251, "s": 231, "text": "Syntax: sequence(x)" }, { "code": null, "e": 291, "s": 251, "text": "Parameters:x: Maximum element of vector" }, { "code": null, "e": 302, "s": 291, "text": "Example 1:" }, { "code": "# R program to create sequence of vectors # Calling sequence() functionsequence(4)sequence(6)sequence(c(4, 6))", "e": 414, "s": 302, "text": null }, { "code": null, "e": 422, "s": 414, "text": "Output:" }, { "code": null, "e": 475, "s": 422, "text": "[1] 1 2 3 4\n[1] 1 2 3 4 5 6\n[1] 1 2 3 4 1 2 3 4 5 6\n" }, { "code": null, "e": 486, "s": 475, "text": "Example 2:" }, { "code": "# R program to create sequence of vectors # Calling sequence() functionsequence(1:4) # Performing operationsx <- 2 * sequence(4)x", "e": 618, "s": 486, "text": null }, { "code": null, "e": 626, "s": 618, "text": "Output:" }, { "code": null, "e": 663, "s": 626, "text": "[1] 1 1 2 1 2 3 1 2 3 4\n[1] 2 4 6 8\n" }, { "code": null, "e": 681, "s": 663, "text": "R Vector-Function" }, { "code": null, "e": 692, "s": 681, "text": "R Language" }, { "code": null, "e": 790, "s": 692, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 842, "s": 790, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 900, "s": 842, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 952, "s": 900, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 984, "s": 952, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 1042, "s": 984, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1074, "s": 1042, "text": "Printing Output of an R Program" }, { "code": null, "e": 1109, "s": 1074, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1153, "s": 1109, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 1191, "s": 1153, "text": "R Programming Language - Introduction" } ]
Deleting MySQL Database Using PHP
If a database is no longer required then it can be deleted forever. You can use pass an SQL command to mysql_query to delete a database. Try out following example to drop a database. <?php $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $sql = 'DROP DATABASE test_db'; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not delete database db_test: ' . mysql_error()); } echo "Database deleted successfully\n"; mysql_close($conn); ?> WARNING − its very dangerous to delete a database and any table. So before deleting any table or database you should make sure you are doing everything intentionally. Its again a matter of issuing one SQL command through mysql_query function to delete any database table. But be very careful while using this command because by doing so you can delete some important information you have in your table. Try out following example to drop a table − <?php $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $sql = 'DROP TABLE employee'; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not delete table employee: ' . mysql_error()); } echo "Table deleted successfully\n";
[ { "code": null, "e": 3028, "s": 2891, "text": "If a database is no longer required then it can be deleted forever. You can use pass an SQL command to mysql_query to delete a database." }, { "code": null, "e": 3074, "s": 3028, "text": "Try out following example to drop a database." }, { "code": null, "e": 3543, "s": 3074, "text": "<?php\n $dbhost = 'localhost:3036';\n $dbuser = 'root';\n $dbpass = 'rootpassword';\n $conn = mysql_connect($dbhost, $dbuser, $dbpass);\n \n if(! $conn ) {\n die('Could not connect: ' . mysql_error());\n }\n \n $sql = 'DROP DATABASE test_db';\n $retval = mysql_query( $sql, $conn );\n \n if(! $retval ) {\n die('Could not delete database db_test: ' . mysql_error());\n }\n \n echo \"Database deleted successfully\\n\";\n \n mysql_close($conn);\n?>" }, { "code": null, "e": 3710, "s": 3543, "text": "WARNING − its very dangerous to delete a database and any table. So before deleting any table or database you should make sure you are doing everything intentionally." }, { "code": null, "e": 3946, "s": 3710, "text": "Its again a matter of issuing one SQL command through mysql_query function to delete any database table. But be very careful while using this command because by doing so you can delete some important information you have in your table." }, { "code": null, "e": 3990, "s": 3946, "text": "Try out following example to drop a table −" } ]
Move matrix elements in given direction and add elements with same value
14 Jun, 2022 Given a matrix m[ ][ ] of size n x n consisting of integers and given a character ‘x’ indicating the direction. Value of ‘x’ can be ‘u’, ‘d’, ‘l’, ‘r’ indicating Up, Down, Left, Right correspondingly. The task is to move the element to given direction such that the consecutive elements having same value are added into single value and shift the rest element. Also, shift the element if the next element in given direction is 0. For example : Consider x = ‘l’ and matrix m[][], 32 3 3 0 0 1 10 10 8After adding 3 in first row, 10 in third row and moving 1 in second row, Matrix will become 32 6 0 1 0 0 20 8 0 Examples : Input : x = 'l' m[][] = { { 32, 3, 3, 3, 3 }, { 0, 0, 1, 0, 0 }, { 10, 10, 8, 1, 2}, { 0, 0, 0, 0, 1}, { 4, 5, 6, 7, 8 } } Output : 32 6 6 0 0 1 0 0 0 0 20 8 1 2 0 1 0 0 0 0 0 4 5 6 7 8 Input : x = 'u' m[][] = { { 10, 3, 32 }, { 10, 0, 96 }, { 5, 32, 96 } } Output : 20 3 32 5 32 192 0 0 0 Approach : The idea is to traverse each row or column (depending on given direction) from side x of row or column towards x’ (opposite of x). For example, if the given value of x is ‘l’ (left) then start scanning each row from left side to right. While traversing, store row or column element in the temporary 1-D array (say temp[]) by skipping elements having value 0 and sum of the consecutive element if they have equal value. After that, start copying the temporary array temp[0..k] to the current row or column from the x side (of row or column) to x’ (opposite of x) and fill reset of the element by 0. Let, x = ‘l’ i.e move towards left. So, start copying each row from left most index to right most index of the row and store in temporary array with processing of ignoring 0s and adding two consecutive element into one if they have same value. Below is the illustration for row 1, Now, for each, copy temporary array to current row from left most index to right most index. Below is illustration for row 1, Below is the implementation of this approach : C++ Java Python3 C# PHP Javascript // C++ code to move matrix elements// in given direction with add// element with same value#include <bits/stdc++.h>using namespace std; #define MAX 50 // Function to shift the matrix// in the given directionvoid moveMatrix(char d[], int n, int a[MAX][MAX]){ // For right shift move. if (d[0] == 'r') { // for each row from // top to bottom for (int i = 0; i < n; i++) { vector<int> v, w; int j; // for each element of // row from right to left for (j = n - 1; j >= 0; j--) { // if not 0 if (a[i][j]) v.push_back(a[i][j]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each row element to 0. for (j = 0; j < n; j++) a[i][j] = 0; j = n - 1; // Copying the temporary // array to the current row. for (auto it = w.begin(); it != w.end(); it++) a[i][j--] = *it; } } // for left shift move else if (d[0] == 'l') { // for each row for (int i = 0; i < n; i++) { vector<int> v, w; int j; // for each element of the // row from left to right for (j = 0; j < n; j++) { // if not 0 if (a[i][j]) v.push_back(a[i][j]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each row element to 0. for (j = 0; j < n; j++) a[i][j] = 0; j = 0; for (auto it = w.begin(); it != w.end(); it++) a[i][j++] = *it; } } // for down shift move. else if (d[0] == 'd') { // for each column for (int i = 0; i < n; i++) { vector<int> v, w; int j; // for each element of // column from bottom to top for (j = n - 1; j >= 0; j--) { // if not 0 if (a[j][i]) v.push_back(a[j][i]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each column element to 0. for (j = 0; j < n; j++) a[j][i] = 0; j = n - 1; // Copying the temporary array // to the current column for (auto it = w.begin(); it != w.end(); it++) a[j--][i] = *it; } } // for up shift move else if (d[0] == 'u') { // for each column for (int i = 0; i < n; i++) { vector<int> v, w; int j; // for each element of column // from top to bottom for (j = 0; j < n; j++) { // if not 0 if (a[j][i]) v.push_back(a[j][i]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each column element to 0. for (j = 0; j < n; j++) a[j][i] = 0; j = 0; // Copying the temporary array // to the current column for (auto it = w.begin(); it != w.end(); it++) a[j++][i] = *it; } }} // Driven Programint main(){ char d[2] = "l"; int n = 5; int a[MAX][MAX] = { { 32, 3, 3, 3, 3 }, { 0, 0, 1, 0, 0 }, { 10, 10, 8, 1, 2 }, { 0, 0, 0, 0, 1 }, { 4, 5, 6, 7, 8 } }; moveMatrix(d, n, a); // Printing the final array for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << a[i][j] << " "; cout << endl; } return 0;} // Java code to move matrix// elements in given direction// with add element with same valueimport java.io.*;import java.util.*; class GFG { // Function to shift the matrix // in the given direction static void moveMatrix(char d, int n, int a[][]) { // For right shift move. if (d == 'r') { // for each row from // top to bottom for (int i = 0; i < n; i++) { ArrayList<Integer> v = new ArrayList<Integer>(); ArrayList<Integer> w = new ArrayList<Integer>(); int j; // for each element of // row from right to left for (j = n - 1; j >= 0; j--) { // if not 0 if (a[i][j] != 0) v.add(a[i][j]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have // same value at // consecutive position. if (j < v.size() - 1 && v.get(j) == v.get(j + 1)) { // insert only one element // as sum of two same element. w.add(2 * v.get(j)); j++; } else w.add(v.get(j)); } // filling the each // row element to 0. for (j = 0; j < n; j++) a[i][j] = 0; j = n - 1; // Copying the temporary // array to the current row. for (int it = 0; it < w.size(); it++) a[i][j--] = w.get(it); } } // for left shift move else if (d == 'l') { // for each row for (int i = 0; i < n; i++) { ArrayList<Integer> v = new ArrayList<Integer>(); ArrayList<Integer> w = new ArrayList<Integer>(); int j; // for each element of the // row from left to right for (j = 0; j < n; j++) { // if not 0 if (a[i][j] != 0) v.add(a[i][j]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have // same value at // consecutive position. if (j < v.size() - 1 && v.get(j) == v.get(j + 1)) { // insert only one // element as sum // of two same element. w.add(2 * v.get(j)); j++; } else w.add(v.get(j)); } // filling the each // row element to 0. for (j = 0; j < n; j++) a[i][j] = 0; j = 0; for (int it = 0; it < w.size(); it++) a[i][j++] = w.get(it); } } // for down shift move. else if (d == 'd') { // for each column for (int i = 0; i < n; i++) { ArrayList<Integer> v = new ArrayList<Integer>(); ArrayList<Integer> w = new ArrayList<Integer>(); int j; // for each element of // column from bottom to top for (j = n - 1; j >= 0; j--) { // if not 0 if (a[j][i] != 0) v.add(a[j][i]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have // same value at consecutive // position. if (j < v.size() - 1 && v.get(j) == v.get(j + 1)) { // insert only one element // as sum of two same element. w.add(2 * v.get(j)); j++; } else w.add(v.get(j)); } // filling the each // column element to 0. for (j = 0; j < n; j++) a[j][i] = 0; j = n - 1; // Copying the temporary array // to the current column for (int it = 0; it < w.size(); it++) a[j--][i] = w.get(it); } } // for up shift move else if (d == 'u') { // for each column for (int i = 0; i < n; i++) { ArrayList<Integer> v = new ArrayList<Integer>(); ArrayList<Integer> w = new ArrayList<Integer>(); int j; // for each element of column // from top to bottom for (j = 0; j < n; j++) { // if not 0 if (a[j][i] != 0) v.add(a[j][i]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have // same value at // consecutive position. if (j < v.size() - 1 && v.get(j) == v.get(j + 1)) { // insert only one element // as sum of two same element. w.add(2 * v.get(j)); j++; } else w.add(v.get(j)); } // filling the each // column element to 0. for (j = 0; j < n; j++) a[j][i] = 0; j = 0; // Copying the temporary // array to the current // column for (int it = 0; it < w.size(); it++) a[j++][i] = w.get(it); } } } // Driver Code public static void main(String args[]) { char d = 'l'; int n = 5; int a[][] = { { 32, 3, 3, 3, 3 }, { 0, 0, 1, 0, 0 }, { 10, 10, 8, 1, 2 }, { 0, 0, 0, 0, 1 }, { 4, 5, 6, 7, 8 } }; moveMatrix(d, n, a); // Printing the // final array for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print(a[i][j] + " "); System.out.println(); } }} // This code is contributed by// Manish Shaw(manishshaw1) # Python3 code to move matrix elements# in given direction with add# element with same valueMAX = 50 # Function to shift the matrix# in the given directiondef moveMatrix(d, n, a): # For right shift move. if (d[0] == 'r'): # For each row from # top to bottom for i in range(n): v = [] w = [] # For each element of # row from right to left for j in range(n - 1, -1, -1): # if not 0 if (a[i][j]): v.append(a[i][j]) # For each temporary array j = 0 while (j < len(v)): # If two element have same # value at consecutive position. if (j < len(v) - 1 and v[j] == v[j + 1]): # Insert only one element # as sum of two same element. w.append(2 * v[j]) j += 1 else: w.append(v[j]) j += 1 # Filling the each row element to 0. for j in range(n): a[i][j] = 0 j = n - 1 # Copying the temporary # array to the current row. for it in w: a[i][j] = it j -= 1 # For left shift move elif (d[0] == 'l'): # For each row for i in range(n): v = [] w = [] # For each element of the # row from left to right for j in range(n): # If not 0 if (a[i][j]): v.append(a[i][j]) # For each temporary array j = 0 while(j < len(v)): # If two element have same # value at consecutive position. if (j < len(v) - 1 and v[j] == v[j + 1]): # Insert only one element # as sum of two same element. w.append(2 * v[j]) j += 1 else: w.append(v[j]) j += 1 # Filling the each row element to 0. for j in range(n): a[i][j] = 0 j = 0 for it in w: a[i][j] = it j += 1 # For down shift move. elif (d[0] == 'd'): # For each column for i in range(n): v = [] w = [] # For each element of # column from bottom to top for j in range(n - 1, -1, -1): # If not 0 if (a[j][i]): v.append(a[j][i]) # For each temporary array j = 0 while(j < len(v)): # If two element have same # value at consecutive position. if (j <len( v) - 1 and v[j] == v[j + 1]): # Insert only one element # as sum of two same element. w.append(2 * v[j]) j += 1 else: w.append(v[j]) j += 1 # Filling the each column element to 0. for j in range(n): a[j][i] = 0 j = n - 1 # Copying the temporary array # to the current column for it in w: a[j][i] = it j -= 1 # For up shift move elif (d[0] == 'u'): # For each column for i in range(n): v = [] w = [] # For each element of column # from top to bottom for j in range(n): # If not 0 if (a[j][i]): v.append(a[j][i]) # For each temporary array j = 0 while(j < len(v)): # If two element have same # value at consecutive position. if (j < len(v) - 1 and v[j] == v[j + 1]): # Insert only one element # as sum of two same element. w.append(2 * v[j]) j += 1 else: w.append(v[j]) j += 1 # Filling the each column element to 0. for j in range(n): a[j][i] = 0 j = 0 # Copying the temporary array # to the current column for it in w: a[j][i] = it j += 1 # Driver Codeif __name__ == "__main__": d = ["l"] * 2 n = 5 a = [ [ 32, 3, 3, 3, 3 ], [ 0, 0, 1, 0, 0 ], [ 10, 10, 8, 1, 2 ], [ 0, 0, 0, 0, 1 ], [ 4, 5, 6, 7, 8 ] ] moveMatrix(d, n, a) # Printing the final array for i in range(n): for j in range(n): print(a[i][j], end = " ") print() # This code is contributed by chitranayal // C# code to move matrix elements// in given direction with add// element with same valueusing System;using System.Collections.Generic; class GFG { // Function to shift the matrix // in the given direction static void moveMatrix(char d, int n, int[, ] a) { // For right shift move. if (d == 'r') { // for each row from // top to bottom for (int i = 0; i < n; i++) { List<int> v = new List<int>(); List<int> w = new List<int>(); int j; // for each element of // row from right to left for (j = n - 1; j >= 0; j--) { // if not 0 if (a[i, j] != 0) v.Add(a[i, j]); } // for each temporary array for (j = 0; j < v.Count; j++) { // if two element have // same value at // consecutive position. if (j < v.Count - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.Add(2 * v[j]); j++; } else w.Add(v[j]); } // filling the each // row element to 0. for (j = 0; j < n; j++) a[i, j] = 0; j = n - 1; // Copying the temporary // array to the current row. for (int it = 0; it < w.Count; it++) a[i, j--] = w[it]; } } // for left shift move else if (d == 'l') { // for each row for (int i = 0; i < n; i++) { List<int> v = new List<int>(); List<int> w = new List<int>(); int j; // for each element of the // row from left to right for (j = 0; j < n; j++) { // if not 0 if (a[i, j] != 0) v.Add(a[i, j]); } // for each temporary array for (j = 0; j < v.Count; j++) { // if two element have // same value at // consecutive position. if (j < v.Count - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.Add(2 * v[j]); j++; } else w.Add(v[j]); } // filling the each // row element to 0. for (j = 0; j < n; j++) a[i, j] = 0; j = 0; for (int it = 0; it < w.Count; it++) a[i, j++] = w[it]; } } // for down shift move. else if (d == 'd') { // for each column for (int i = 0; i < n; i++) { List<int> v = new List<int>(); List<int> w = new List<int>(); int j; // for each element of // column from bottom to top for (j = n - 1; j >= 0; j--) { // if not 0 if (a[j, i] != 0) v.Add(a[j, i]); } // for each temporary array for (j = 0; j < v.Count; j++) { // if two element have same // value at consecutive position. if (j < v.Count - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.Add(2 * v[j]); j++; } else w.Add(v[j]); } // filling the each // column element to 0. for (j = 0; j < n; j++) a[j, i] = 0; j = n - 1; // Copying the temporary array // to the current column for (int it = 0; it < w.Count; it++) a[j--, i] = w[it]; } } // for up shift move else if (d == 'u') { // for each column for (int i = 0; i < n; i++) { List<int> v = new List<int>(); List<int> w = new List<int>(); int j; // for each element of column // from top to bottom for (j = 0; j < n; j++) { // if not 0 if (a[j, i] != 0) v.Add(a[j, i]); } // for each temporary array for (j = 0; j < v.Count; j++) { // if two element have same // value at consecutive position. if (j < v.Count - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.Add(2 * v[j]); j++; } else w.Add(v[j]); } // filling the each // column element to 0. for (j = 0; j < n; j++) a[j, i] = 0; j = 0; // Copying the temporary array // to the current column for (int it = 0; it < w.Count; it++) a[j++, i] = w[it]; } } } // Driven Code static void Main() { char d = 'l'; int n = 5; int[, ] a = new int[, ] { { 32, 3, 3, 3, 3 }, { 0, 0, 1, 0, 0 }, { 10, 10, 8, 1, 2 }, { 0, 0, 0, 0, 1 }, { 4, 5, 6, 7, 8 } }; moveMatrix(d, n, a); // Printing the final array for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) Console.Write(a[i, j] + " "); Console.WriteLine(); } }}// This code is contributed by// Manish Shaw(manishshaw1) <?php// PHP code to move matrix// elements in given// direction with add element// with same value$MAX = 50; // Function to shift the matrix// in the given directionfunction moveMatrix($d, $n, &$a){ global $MAX; // For right shift move. if ($d[0] == 'r') { // for each row from // top to bottom for ($i = 0; $i < $n; $i++) { $v = array(); $w = array(); $j = 0; // for each element of // row from right to left for ($j = $n - 1; $j >= 0; $j--) { // if not 0 if ($a[$i][$j]) array_push($v, $a[$i][$j]); } // for each temporary array for ($j = 0; $j < count($v); $j++) { // if two element have same // value at consecutive position. if ($j < count($v) - 1 && $v[$j] == $v[$j + 1]) { // insert only one element // as sum of two same element. array_push($w, 2 * $v[$j]); $j++; } else array_push($w, $v[$j]); } // filling the each // row element to 0. for ($j = 0; $j < $n; $j++) $a[$i][$j] = 0; $j = $n - 1; // Copying the temporary // array to the current row. for ($it = 0; $it != count($w); $it++) $a[$i][$j--] = $w[$it]; } } // for left shift move else if ($d[0] == 'l') { // for each row for ($i = 0; $i < $n; $i++) { $v = array(); $w = array(); $j = 0; // for each element of the // row from left to right for ($j = 0; $j < $n; $j++) { // if not 0 if ($a[$i][$j]) array_push($v, $a[$i][$j]); } // for each temporary array for ($j = 0; $j < count($v); $j++) { // if two element have // same value at consecutive // position. if ($j < count($v) - 1 && $v[$j] == $v[$j + 1]) { // insert only one element // as sum of two same element. array_push($w, 2 * $v[$j]); $j++; } else array_push($w, $v[$j]); } // filling the each // row element to 0. for ($j = 0; $j < $n; $j++) $a[$i][$j] = 0; $j = 0; for ($it = 0; $it != count($w); $it++) $a[$i][$j++] = $w[$it]; } } // for down shift move. else if ($d[0] == 'd') { // for each column for ($i = 0; $i < $n; $i++) { $v = array(); $w = array(); $j = 0; // for each element // of column from // bottom to top for ($j = $n - 1; $j >= 0; $j--) { // if not 0 if ($a[$j][$i]) array_push($v, $a[$j][$i]); } // for each temporary array for ($j = 0; $j < count($v); $j++) { // if two element have // same value at // consecutive position. if ($j < count($v) - 1 && $v[$j] == $v[$j + 1]) { // insert only one element // as sum of two same element. array_push($w, 2 * $v[$j]); $j++; } else array_push($w, $v[$j]); } // filling the each // column element to 0. for ($j = 0; $j < $n; $j++) $a[$j][$i] = 0; $j = $n - 1; // Copying the temporary array // to the current column for ($it = 0; $it != count($w); $it++) $a[$j--][$i] = $w[$it]; } } // for up shift move else if ($d[0] == 'u') { // for each column for ($i = 0; $i < $n; $i++) { $v = array(); $w = array(); $j = 0; // for each element of column // from top to bottom for ($j = 0; $j < $n; $j++) { // if not 0 if ($a[$j][$i]) array_push($v, $a[$j][$i]); } // for each temporary array for ($j = 0; $j < count($v); $j++) { // if two element have same // value at consecutive position. if ($j < count($v) - 1 && $v[$j] == $v[$j + 1]) { // insert only one element // as sum of two same element. array_push($w, 2 * $v[$j]); $j++; } else array_push($w, $v[$j]); } // filling the each // column element to 0. for ($j = 0; $j < $n; $j++) $a[$j][$i] = 0; $j = 0; // Copying the temporary array // to the current column for ($it = 0; $it != count($w); $it++) $a[$j++][$i] = $w[$it]; } }} // Driven Code$d = array("l");$n = 5;$a = array( array(32, 3, 3, 3, 3), array(0, 0, 1, 0, 0), array(10, 10, 8, 1, 2), array(0, 0, 0, 0, 1), array(4, 5, 6, 7, 8)); moveMatrix($d, $n, $a); // Printing the final arrayfor ($i = 0; $i < $n; $i++){ for ($j = 0; $j < $n; $j++) echo ($a[$i][$j]." "); echo ("\n");} // This code is contributed// by Manish Shaw(manishshaw1)?> <script>// Javascript code to move matrix// elements in given direction// with add element with same value // Function to shift the matrix // in the given direction function moveMatrix(d,n,a) { // For right shift move. if (d == 'r') { // for each row from // top to bottom for (let i = 0; i < n; i++) { let v = [] ; let w = [] ; let j; // for each element of // row from right to left for (j = n - 1; j >= 0; j--) { // if not 0 if (a[i][j] != 0) v.push(a[i][j]); } // for each temporary array for (j = 0; j < v.length; j++) { // if two element have // same value at // consecutive position. if (j < v.length - 1 && v[j] == v[j+1]) { // insert only one element // as sum of two same element. w.push(2 * v[j]); j++; } else w.push(v[j]); } // filling the each // row element to 0. for (j = 0; j < n; j++) a[i][j] = 0; j = n - 1; // Copying the temporary // array to the current row. for (let it = 0; it < w.length; it++) a[i][j--] = w[it]; } } // for left shift move else if (d == 'l') { // for each row for (let i = 0; i < n; i++) { let v = [] ; let w = [] ; let j; // for each element of the // row from left to right for (j = 0; j < n; j++) { // if not 0 if (a[i][j] != 0) v.push(a[i][j]); } // for each temporary array for (j = 0; j < v.length; j++) { // if two element have // same value at // consecutive position. if (j < v.length - 1 && v[j] == v[j+1]) { // insert only one // element as sum // of two same element. w.push(2 * v[j]); j++; } else w.push(v[j]); } // filling the each // row element to 0. for (j = 0; j < n; j++) a[i][j] = 0; j = 0; for (let it = 0; it < w.length; it++) a[i][j++] = w[it]; } } // for down shift move. else if (d == 'd') { // for each column for (let i = 0; i < n; i++) { let v = []; let w = []; let j; // for each element of // column from bottom to top for (j = n - 1; j >= 0; j--) { // if not 0 if (a[j][i] != 0) v.push(a[j][i]); } // for each temporary array for (j = 0; j < v.length; j++) { // if two element have // same value at consecutive // position. if (j < v.length - 1 && v[j] == v[j+1]) { // insert only one element // as sum of two same element. w.push(2 * v[j]); j++; } else w.push(v[j]); } // filling the each // column element to 0. for (j = 0; j < n; j++) a[j][i] = 0; j = n - 1; // Copying the temporary array // to the current column for (let it = 0; it < w.length; it++) a[j--][i] = w[it]; } } // for up shift move else if (d == 'u') { // for each column for (let i = 0; i < n; i++) { let v = []; let w = []; let j; // for each element of column // from top to bottom for (j = 0; j < n; j++) { // if not 0 if (a[j][i] != 0) v.push(a[j][i]); } // for each temporary array for (j = 0; j < v.length; j++) { // if two element have // same value at // consecutive position. if (j < v.length - 1 && v[j] == v[j+1]) { // insert only one element // as sum of two same element. w.push(2 * v[j]); j++; } else w.push(v[j]); } // filling the each // column element to 0. for (j = 0; j < n; j++) a[j][i] = 0; j = 0; // Copying the temporary // array to the current // column for (let it = 0; it < w.length; it++) a[j++][i] = w[it]; } } } // Driver Code let d = 'l'; let n = 5; let a = [ [ 32, 3, 3, 3, 3 ], [ 0, 0, 1, 0, 0 ], [ 10, 10, 8, 1, 2 ], [ 0, 0, 0, 0, 1 ], [ 4, 5, 6, 7, 8 ] ] moveMatrix(d, n, a); // Printing the // final array for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) document.write(a[i][j] + " "); document.write("<br>"); } // This code is contributed by rag2127</script> 32 6 6 0 0 1 0 0 0 0 20 8 1 2 0 1 0 0 0 0 4 5 6 7 8 Time Complexity: O(n2)Auxiliary Space: O(n) manishshaw1 hell_abhi ukasp rag2127 gabaa406 simranarora5sos adi1212 array-rearrange cpp-array cpp-vector Arrays Matrix Arrays Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray Matrix Chain Multiplication | DP-8 Program to find largest element in an array Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7 The Celebrity Problem
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Jun, 2022" }, { "code": null, "e": 485, "s": 54, "text": "Given a matrix m[ ][ ] of size n x n consisting of integers and given a character ‘x’ indicating the direction. Value of ‘x’ can be ‘u’, ‘d’, ‘l’, ‘r’ indicating Up, Down, Left, Right correspondingly. The task is to move the element to given direction such that the consecutive elements having same value are added into single value and shift the rest element. Also, shift the element if the next element in given direction is 0. " }, { "code": null, "e": 666, "s": 485, "text": "For example : Consider x = ‘l’ and matrix m[][], 32 3 3 0 0 1 10 10 8After adding 3 in first row, 10 in third row and moving 1 in second row, Matrix will become 32 6 0 1 0 0 20 8 0" }, { "code": null, "e": 679, "s": 666, "text": "Examples : " }, { "code": null, "e": 1026, "s": 679, "text": "Input : x = 'l'\nm[][] = { { 32, 3, 3, 3, 3 },\n { 0, 0, 1, 0, 0 },\n { 10, 10, 8, 1, 2},\n { 0, 0, 0, 0, 1},\n { 4, 5, 6, 7, 8 } }\nOutput :\n32 6 6 0 0\n1 0 0 0 0\n20 8 1 2 0\n1 0 0 0 0 0\n4 5 6 7 8\n\nInput : x = 'u'\nm[][] = { { 10, 3, 32 },\n { 10, 0, 96 },\n { 5, 32, 96 } }\nOutput :\n20 3 32\n5 32 192\n0 0 0" }, { "code": null, "e": 1635, "s": 1026, "text": "Approach : The idea is to traverse each row or column (depending on given direction) from side x of row or column towards x’ (opposite of x). For example, if the given value of x is ‘l’ (left) then start scanning each row from left side to right. While traversing, store row or column element in the temporary 1-D array (say temp[]) by skipping elements having value 0 and sum of the consecutive element if they have equal value. After that, start copying the temporary array temp[0..k] to the current row or column from the x side (of row or column) to x’ (opposite of x) and fill reset of the element by 0." }, { "code": null, "e": 1918, "s": 1635, "text": "Let, x = ‘l’ i.e move towards left. So, start copying each row from left most index to right most index of the row and store in temporary array with processing of ignoring 0s and adding two consecutive element into one if they have same value. Below is the illustration for row 1, " }, { "code": null, "e": 2046, "s": 1918, "text": "Now, for each, copy temporary array to current row from left most index to right most index. Below is illustration for row 1, " }, { "code": null, "e": 2094, "s": 2046, "text": "Below is the implementation of this approach : " }, { "code": null, "e": 2098, "s": 2094, "text": "C++" }, { "code": null, "e": 2103, "s": 2098, "text": "Java" }, { "code": null, "e": 2111, "s": 2103, "text": "Python3" }, { "code": null, "e": 2114, "s": 2111, "text": "C#" }, { "code": null, "e": 2118, "s": 2114, "text": "PHP" }, { "code": null, "e": 2129, "s": 2118, "text": "Javascript" }, { "code": "// C++ code to move matrix elements// in given direction with add// element with same value#include <bits/stdc++.h>using namespace std; #define MAX 50 // Function to shift the matrix// in the given directionvoid moveMatrix(char d[], int n, int a[MAX][MAX]){ // For right shift move. if (d[0] == 'r') { // for each row from // top to bottom for (int i = 0; i < n; i++) { vector<int> v, w; int j; // for each element of // row from right to left for (j = n - 1; j >= 0; j--) { // if not 0 if (a[i][j]) v.push_back(a[i][j]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each row element to 0. for (j = 0; j < n; j++) a[i][j] = 0; j = n - 1; // Copying the temporary // array to the current row. for (auto it = w.begin(); it != w.end(); it++) a[i][j--] = *it; } } // for left shift move else if (d[0] == 'l') { // for each row for (int i = 0; i < n; i++) { vector<int> v, w; int j; // for each element of the // row from left to right for (j = 0; j < n; j++) { // if not 0 if (a[i][j]) v.push_back(a[i][j]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each row element to 0. for (j = 0; j < n; j++) a[i][j] = 0; j = 0; for (auto it = w.begin(); it != w.end(); it++) a[i][j++] = *it; } } // for down shift move. else if (d[0] == 'd') { // for each column for (int i = 0; i < n; i++) { vector<int> v, w; int j; // for each element of // column from bottom to top for (j = n - 1; j >= 0; j--) { // if not 0 if (a[j][i]) v.push_back(a[j][i]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each column element to 0. for (j = 0; j < n; j++) a[j][i] = 0; j = n - 1; // Copying the temporary array // to the current column for (auto it = w.begin(); it != w.end(); it++) a[j--][i] = *it; } } // for up shift move else if (d[0] == 'u') { // for each column for (int i = 0; i < n; i++) { vector<int> v, w; int j; // for each element of column // from top to bottom for (j = 0; j < n; j++) { // if not 0 if (a[j][i]) v.push_back(a[j][i]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each column element to 0. for (j = 0; j < n; j++) a[j][i] = 0; j = 0; // Copying the temporary array // to the current column for (auto it = w.begin(); it != w.end(); it++) a[j++][i] = *it; } }} // Driven Programint main(){ char d[2] = \"l\"; int n = 5; int a[MAX][MAX] = { { 32, 3, 3, 3, 3 }, { 0, 0, 1, 0, 0 }, { 10, 10, 8, 1, 2 }, { 0, 0, 0, 0, 1 }, { 4, 5, 6, 7, 8 } }; moveMatrix(d, n, a); // Printing the final array for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << a[i][j] << \" \"; cout << endl; } return 0;}", "e": 7651, "s": 2129, "text": null }, { "code": "// Java code to move matrix// elements in given direction// with add element with same valueimport java.io.*;import java.util.*; class GFG { // Function to shift the matrix // in the given direction static void moveMatrix(char d, int n, int a[][]) { // For right shift move. if (d == 'r') { // for each row from // top to bottom for (int i = 0; i < n; i++) { ArrayList<Integer> v = new ArrayList<Integer>(); ArrayList<Integer> w = new ArrayList<Integer>(); int j; // for each element of // row from right to left for (j = n - 1; j >= 0; j--) { // if not 0 if (a[i][j] != 0) v.add(a[i][j]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have // same value at // consecutive position. if (j < v.size() - 1 && v.get(j) == v.get(j + 1)) { // insert only one element // as sum of two same element. w.add(2 * v.get(j)); j++; } else w.add(v.get(j)); } // filling the each // row element to 0. for (j = 0; j < n; j++) a[i][j] = 0; j = n - 1; // Copying the temporary // array to the current row. for (int it = 0; it < w.size(); it++) a[i][j--] = w.get(it); } } // for left shift move else if (d == 'l') { // for each row for (int i = 0; i < n; i++) { ArrayList<Integer> v = new ArrayList<Integer>(); ArrayList<Integer> w = new ArrayList<Integer>(); int j; // for each element of the // row from left to right for (j = 0; j < n; j++) { // if not 0 if (a[i][j] != 0) v.add(a[i][j]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have // same value at // consecutive position. if (j < v.size() - 1 && v.get(j) == v.get(j + 1)) { // insert only one // element as sum // of two same element. w.add(2 * v.get(j)); j++; } else w.add(v.get(j)); } // filling the each // row element to 0. for (j = 0; j < n; j++) a[i][j] = 0; j = 0; for (int it = 0; it < w.size(); it++) a[i][j++] = w.get(it); } } // for down shift move. else if (d == 'd') { // for each column for (int i = 0; i < n; i++) { ArrayList<Integer> v = new ArrayList<Integer>(); ArrayList<Integer> w = new ArrayList<Integer>(); int j; // for each element of // column from bottom to top for (j = n - 1; j >= 0; j--) { // if not 0 if (a[j][i] != 0) v.add(a[j][i]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have // same value at consecutive // position. if (j < v.size() - 1 && v.get(j) == v.get(j + 1)) { // insert only one element // as sum of two same element. w.add(2 * v.get(j)); j++; } else w.add(v.get(j)); } // filling the each // column element to 0. for (j = 0; j < n; j++) a[j][i] = 0; j = n - 1; // Copying the temporary array // to the current column for (int it = 0; it < w.size(); it++) a[j--][i] = w.get(it); } } // for up shift move else if (d == 'u') { // for each column for (int i = 0; i < n; i++) { ArrayList<Integer> v = new ArrayList<Integer>(); ArrayList<Integer> w = new ArrayList<Integer>(); int j; // for each element of column // from top to bottom for (j = 0; j < n; j++) { // if not 0 if (a[j][i] != 0) v.add(a[j][i]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have // same value at // consecutive position. if (j < v.size() - 1 && v.get(j) == v.get(j + 1)) { // insert only one element // as sum of two same element. w.add(2 * v.get(j)); j++; } else w.add(v.get(j)); } // filling the each // column element to 0. for (j = 0; j < n; j++) a[j][i] = 0; j = 0; // Copying the temporary // array to the current // column for (int it = 0; it < w.size(); it++) a[j++][i] = w.get(it); } } } // Driver Code public static void main(String args[]) { char d = 'l'; int n = 5; int a[][] = { { 32, 3, 3, 3, 3 }, { 0, 0, 1, 0, 0 }, { 10, 10, 8, 1, 2 }, { 0, 0, 0, 0, 1 }, { 4, 5, 6, 7, 8 } }; moveMatrix(d, n, a); // Printing the // final array for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print(a[i][j] + \" \"); System.out.println(); } }} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 14434, "s": 7651, "text": null }, { "code": "# Python3 code to move matrix elements# in given direction with add# element with same valueMAX = 50 # Function to shift the matrix# in the given directiondef moveMatrix(d, n, a): # For right shift move. if (d[0] == 'r'): # For each row from # top to bottom for i in range(n): v = [] w = [] # For each element of # row from right to left for j in range(n - 1, -1, -1): # if not 0 if (a[i][j]): v.append(a[i][j]) # For each temporary array j = 0 while (j < len(v)): # If two element have same # value at consecutive position. if (j < len(v) - 1 and v[j] == v[j + 1]): # Insert only one element # as sum of two same element. w.append(2 * v[j]) j += 1 else: w.append(v[j]) j += 1 # Filling the each row element to 0. for j in range(n): a[i][j] = 0 j = n - 1 # Copying the temporary # array to the current row. for it in w: a[i][j] = it j -= 1 # For left shift move elif (d[0] == 'l'): # For each row for i in range(n): v = [] w = [] # For each element of the # row from left to right for j in range(n): # If not 0 if (a[i][j]): v.append(a[i][j]) # For each temporary array j = 0 while(j < len(v)): # If two element have same # value at consecutive position. if (j < len(v) - 1 and v[j] == v[j + 1]): # Insert only one element # as sum of two same element. w.append(2 * v[j]) j += 1 else: w.append(v[j]) j += 1 # Filling the each row element to 0. for j in range(n): a[i][j] = 0 j = 0 for it in w: a[i][j] = it j += 1 # For down shift move. elif (d[0] == 'd'): # For each column for i in range(n): v = [] w = [] # For each element of # column from bottom to top for j in range(n - 1, -1, -1): # If not 0 if (a[j][i]): v.append(a[j][i]) # For each temporary array j = 0 while(j < len(v)): # If two element have same # value at consecutive position. if (j <len( v) - 1 and v[j] == v[j + 1]): # Insert only one element # as sum of two same element. w.append(2 * v[j]) j += 1 else: w.append(v[j]) j += 1 # Filling the each column element to 0. for j in range(n): a[j][i] = 0 j = n - 1 # Copying the temporary array # to the current column for it in w: a[j][i] = it j -= 1 # For up shift move elif (d[0] == 'u'): # For each column for i in range(n): v = [] w = [] # For each element of column # from top to bottom for j in range(n): # If not 0 if (a[j][i]): v.append(a[j][i]) # For each temporary array j = 0 while(j < len(v)): # If two element have same # value at consecutive position. if (j < len(v) - 1 and v[j] == v[j + 1]): # Insert only one element # as sum of two same element. w.append(2 * v[j]) j += 1 else: w.append(v[j]) j += 1 # Filling the each column element to 0. for j in range(n): a[j][i] = 0 j = 0 # Copying the temporary array # to the current column for it in w: a[j][i] = it j += 1 # Driver Codeif __name__ == \"__main__\": d = [\"l\"] * 2 n = 5 a = [ [ 32, 3, 3, 3, 3 ], [ 0, 0, 1, 0, 0 ], [ 10, 10, 8, 1, 2 ], [ 0, 0, 0, 0, 1 ], [ 4, 5, 6, 7, 8 ] ] moveMatrix(d, n, a) # Printing the final array for i in range(n): for j in range(n): print(a[i][j], end = \" \") print() # This code is contributed by chitranayal", "e": 19762, "s": 14434, "text": null }, { "code": "// C# code to move matrix elements// in given direction with add// element with same valueusing System;using System.Collections.Generic; class GFG { // Function to shift the matrix // in the given direction static void moveMatrix(char d, int n, int[, ] a) { // For right shift move. if (d == 'r') { // for each row from // top to bottom for (int i = 0; i < n; i++) { List<int> v = new List<int>(); List<int> w = new List<int>(); int j; // for each element of // row from right to left for (j = n - 1; j >= 0; j--) { // if not 0 if (a[i, j] != 0) v.Add(a[i, j]); } // for each temporary array for (j = 0; j < v.Count; j++) { // if two element have // same value at // consecutive position. if (j < v.Count - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.Add(2 * v[j]); j++; } else w.Add(v[j]); } // filling the each // row element to 0. for (j = 0; j < n; j++) a[i, j] = 0; j = n - 1; // Copying the temporary // array to the current row. for (int it = 0; it < w.Count; it++) a[i, j--] = w[it]; } } // for left shift move else if (d == 'l') { // for each row for (int i = 0; i < n; i++) { List<int> v = new List<int>(); List<int> w = new List<int>(); int j; // for each element of the // row from left to right for (j = 0; j < n; j++) { // if not 0 if (a[i, j] != 0) v.Add(a[i, j]); } // for each temporary array for (j = 0; j < v.Count; j++) { // if two element have // same value at // consecutive position. if (j < v.Count - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.Add(2 * v[j]); j++; } else w.Add(v[j]); } // filling the each // row element to 0. for (j = 0; j < n; j++) a[i, j] = 0; j = 0; for (int it = 0; it < w.Count; it++) a[i, j++] = w[it]; } } // for down shift move. else if (d == 'd') { // for each column for (int i = 0; i < n; i++) { List<int> v = new List<int>(); List<int> w = new List<int>(); int j; // for each element of // column from bottom to top for (j = n - 1; j >= 0; j--) { // if not 0 if (a[j, i] != 0) v.Add(a[j, i]); } // for each temporary array for (j = 0; j < v.Count; j++) { // if two element have same // value at consecutive position. if (j < v.Count - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.Add(2 * v[j]); j++; } else w.Add(v[j]); } // filling the each // column element to 0. for (j = 0; j < n; j++) a[j, i] = 0; j = n - 1; // Copying the temporary array // to the current column for (int it = 0; it < w.Count; it++) a[j--, i] = w[it]; } } // for up shift move else if (d == 'u') { // for each column for (int i = 0; i < n; i++) { List<int> v = new List<int>(); List<int> w = new List<int>(); int j; // for each element of column // from top to bottom for (j = 0; j < n; j++) { // if not 0 if (a[j, i] != 0) v.Add(a[j, i]); } // for each temporary array for (j = 0; j < v.Count; j++) { // if two element have same // value at consecutive position. if (j < v.Count - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.Add(2 * v[j]); j++; } else w.Add(v[j]); } // filling the each // column element to 0. for (j = 0; j < n; j++) a[j, i] = 0; j = 0; // Copying the temporary array // to the current column for (int it = 0; it < w.Count; it++) a[j++, i] = w[it]; } } } // Driven Code static void Main() { char d = 'l'; int n = 5; int[, ] a = new int[, ] { { 32, 3, 3, 3, 3 }, { 0, 0, 1, 0, 0 }, { 10, 10, 8, 1, 2 }, { 0, 0, 0, 0, 1 }, { 4, 5, 6, 7, 8 } }; moveMatrix(d, n, a); // Printing the final array for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) Console.Write(a[i, j] + \" \"); Console.WriteLine(); } }}// This code is contributed by// Manish Shaw(manishshaw1)", "e": 26229, "s": 19762, "text": null }, { "code": "<?php// PHP code to move matrix// elements in given// direction with add element// with same value$MAX = 50; // Function to shift the matrix// in the given directionfunction moveMatrix($d, $n, &$a){ global $MAX; // For right shift move. if ($d[0] == 'r') { // for each row from // top to bottom for ($i = 0; $i < $n; $i++) { $v = array(); $w = array(); $j = 0; // for each element of // row from right to left for ($j = $n - 1; $j >= 0; $j--) { // if not 0 if ($a[$i][$j]) array_push($v, $a[$i][$j]); } // for each temporary array for ($j = 0; $j < count($v); $j++) { // if two element have same // value at consecutive position. if ($j < count($v) - 1 && $v[$j] == $v[$j + 1]) { // insert only one element // as sum of two same element. array_push($w, 2 * $v[$j]); $j++; } else array_push($w, $v[$j]); } // filling the each // row element to 0. for ($j = 0; $j < $n; $j++) $a[$i][$j] = 0; $j = $n - 1; // Copying the temporary // array to the current row. for ($it = 0; $it != count($w); $it++) $a[$i][$j--] = $w[$it]; } } // for left shift move else if ($d[0] == 'l') { // for each row for ($i = 0; $i < $n; $i++) { $v = array(); $w = array(); $j = 0; // for each element of the // row from left to right for ($j = 0; $j < $n; $j++) { // if not 0 if ($a[$i][$j]) array_push($v, $a[$i][$j]); } // for each temporary array for ($j = 0; $j < count($v); $j++) { // if two element have // same value at consecutive // position. if ($j < count($v) - 1 && $v[$j] == $v[$j + 1]) { // insert only one element // as sum of two same element. array_push($w, 2 * $v[$j]); $j++; } else array_push($w, $v[$j]); } // filling the each // row element to 0. for ($j = 0; $j < $n; $j++) $a[$i][$j] = 0; $j = 0; for ($it = 0; $it != count($w); $it++) $a[$i][$j++] = $w[$it]; } } // for down shift move. else if ($d[0] == 'd') { // for each column for ($i = 0; $i < $n; $i++) { $v = array(); $w = array(); $j = 0; // for each element // of column from // bottom to top for ($j = $n - 1; $j >= 0; $j--) { // if not 0 if ($a[$j][$i]) array_push($v, $a[$j][$i]); } // for each temporary array for ($j = 0; $j < count($v); $j++) { // if two element have // same value at // consecutive position. if ($j < count($v) - 1 && $v[$j] == $v[$j + 1]) { // insert only one element // as sum of two same element. array_push($w, 2 * $v[$j]); $j++; } else array_push($w, $v[$j]); } // filling the each // column element to 0. for ($j = 0; $j < $n; $j++) $a[$j][$i] = 0; $j = $n - 1; // Copying the temporary array // to the current column for ($it = 0; $it != count($w); $it++) $a[$j--][$i] = $w[$it]; } } // for up shift move else if ($d[0] == 'u') { // for each column for ($i = 0; $i < $n; $i++) { $v = array(); $w = array(); $j = 0; // for each element of column // from top to bottom for ($j = 0; $j < $n; $j++) { // if not 0 if ($a[$j][$i]) array_push($v, $a[$j][$i]); } // for each temporary array for ($j = 0; $j < count($v); $j++) { // if two element have same // value at consecutive position. if ($j < count($v) - 1 && $v[$j] == $v[$j + 1]) { // insert only one element // as sum of two same element. array_push($w, 2 * $v[$j]); $j++; } else array_push($w, $v[$j]); } // filling the each // column element to 0. for ($j = 0; $j < $n; $j++) $a[$j][$i] = 0; $j = 0; // Copying the temporary array // to the current column for ($it = 0; $it != count($w); $it++) $a[$j++][$i] = $w[$it]; } }} // Driven Code$d = array(\"l\");$n = 5;$a = array( array(32, 3, 3, 3, 3), array(0, 0, 1, 0, 0), array(10, 10, 8, 1, 2), array(0, 0, 0, 0, 1), array(4, 5, 6, 7, 8)); moveMatrix($d, $n, $a); // Printing the final arrayfor ($i = 0; $i < $n; $i++){ for ($j = 0; $j < $n; $j++) echo ($a[$i][$j].\" \"); echo (\"\\n\");} // This code is contributed// by Manish Shaw(manishshaw1)?>", "e": 32273, "s": 26229, "text": null }, { "code": "<script>// Javascript code to move matrix// elements in given direction// with add element with same value // Function to shift the matrix // in the given direction function moveMatrix(d,n,a) { // For right shift move. if (d == 'r') { // for each row from // top to bottom for (let i = 0; i < n; i++) { let v = [] ; let w = [] ; let j; // for each element of // row from right to left for (j = n - 1; j >= 0; j--) { // if not 0 if (a[i][j] != 0) v.push(a[i][j]); } // for each temporary array for (j = 0; j < v.length; j++) { // if two element have // same value at // consecutive position. if (j < v.length - 1 && v[j] == v[j+1]) { // insert only one element // as sum of two same element. w.push(2 * v[j]); j++; } else w.push(v[j]); } // filling the each // row element to 0. for (j = 0; j < n; j++) a[i][j] = 0; j = n - 1; // Copying the temporary // array to the current row. for (let it = 0; it < w.length; it++) a[i][j--] = w[it]; } } // for left shift move else if (d == 'l') { // for each row for (let i = 0; i < n; i++) { let v = [] ; let w = [] ; let j; // for each element of the // row from left to right for (j = 0; j < n; j++) { // if not 0 if (a[i][j] != 0) v.push(a[i][j]); } // for each temporary array for (j = 0; j < v.length; j++) { // if two element have // same value at // consecutive position. if (j < v.length - 1 && v[j] == v[j+1]) { // insert only one // element as sum // of two same element. w.push(2 * v[j]); j++; } else w.push(v[j]); } // filling the each // row element to 0. for (j = 0; j < n; j++) a[i][j] = 0; j = 0; for (let it = 0; it < w.length; it++) a[i][j++] = w[it]; } } // for down shift move. else if (d == 'd') { // for each column for (let i = 0; i < n; i++) { let v = []; let w = []; let j; // for each element of // column from bottom to top for (j = n - 1; j >= 0; j--) { // if not 0 if (a[j][i] != 0) v.push(a[j][i]); } // for each temporary array for (j = 0; j < v.length; j++) { // if two element have // same value at consecutive // position. if (j < v.length - 1 && v[j] == v[j+1]) { // insert only one element // as sum of two same element. w.push(2 * v[j]); j++; } else w.push(v[j]); } // filling the each // column element to 0. for (j = 0; j < n; j++) a[j][i] = 0; j = n - 1; // Copying the temporary array // to the current column for (let it = 0; it < w.length; it++) a[j--][i] = w[it]; } } // for up shift move else if (d == 'u') { // for each column for (let i = 0; i < n; i++) { let v = []; let w = []; let j; // for each element of column // from top to bottom for (j = 0; j < n; j++) { // if not 0 if (a[j][i] != 0) v.push(a[j][i]); } // for each temporary array for (j = 0; j < v.length; j++) { // if two element have // same value at // consecutive position. if (j < v.length - 1 && v[j] == v[j+1]) { // insert only one element // as sum of two same element. w.push(2 * v[j]); j++; } else w.push(v[j]); } // filling the each // column element to 0. for (j = 0; j < n; j++) a[j][i] = 0; j = 0; // Copying the temporary // array to the current // column for (let it = 0; it < w.length; it++) a[j++][i] = w[it]; } } } // Driver Code let d = 'l'; let n = 5; let a = [ [ 32, 3, 3, 3, 3 ], [ 0, 0, 1, 0, 0 ], [ 10, 10, 8, 1, 2 ], [ 0, 0, 0, 0, 1 ], [ 4, 5, 6, 7, 8 ] ] moveMatrix(d, n, a); // Printing the // final array for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) document.write(a[i][j] + \" \"); document.write(\"<br>\"); } // This code is contributed by rag2127</script>", "e": 38509, "s": 32273, "text": null }, { "code": null, "e": 38565, "s": 38509, "text": "32 6 6 0 0 \n1 0 0 0 0 \n20 8 1 2 0 \n1 0 0 0 0 \n4 5 6 7 8" }, { "code": null, "e": 38611, "s": 38567, "text": "Time Complexity: O(n2)Auxiliary Space: O(n)" }, { "code": null, "e": 38623, "s": 38611, "text": "manishshaw1" }, { "code": null, "e": 38633, "s": 38623, "text": "hell_abhi" }, { "code": null, "e": 38639, "s": 38633, "text": "ukasp" }, { "code": null, "e": 38647, "s": 38639, "text": "rag2127" }, { "code": null, "e": 38656, "s": 38647, "text": "gabaa406" }, { "code": null, "e": 38672, "s": 38656, "text": "simranarora5sos" }, { "code": null, "e": 38680, "s": 38672, "text": "adi1212" }, { "code": null, "e": 38696, "s": 38680, "text": "array-rearrange" }, { "code": null, "e": 38706, "s": 38696, "text": "cpp-array" }, { "code": null, "e": 38717, "s": 38706, "text": "cpp-vector" }, { "code": null, "e": 38724, "s": 38717, "text": "Arrays" }, { "code": null, "e": 38731, "s": 38724, "text": "Matrix" }, { "code": null, "e": 38738, "s": 38731, "text": "Arrays" }, { "code": null, "e": 38745, "s": 38738, "text": "Matrix" }, { "code": null, "e": 38843, "s": 38745, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38858, "s": 38843, "text": "Arrays in Java" }, { "code": null, "e": 38904, "s": 38858, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 38972, "s": 38904, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 39016, "s": 38972, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 39048, "s": 39016, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 39083, "s": 39048, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 39127, "s": 39083, "text": "Program to find largest element in an array" }, { "code": null, "e": 39158, "s": 39127, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 39182, "s": 39158, "text": "Sudoku | Backtracking-7" } ]
LocalDate ofEpochDay() method in Java with Examples
21 May, 2020 The ofEpochDay(long epochDay) method of LocalDate class in Java is used to obtain an instance of LocalDate from the epoch day count. Epoch day is 01-01-1970(DD-MM-YYYY). This is considered as a start of the epoch day. The method returns the LocalDate by adding the passed days into Epoch date i.e. 01-01-1970. Suppose 2 is passed as a parameter, the method will return 03-01-1970 (2 is added to ’01’ from the epoch day(DD)). Similarly, if 365 is passed then a whole new year will be added to the epoch date. Syntax: public static LocalDate ofEpochDay(long epochDay) Parameters: This method accepts one parameter epochDay which is the conversion base. Return Value: This method returns the localdate after conversion. Exceptions: This method throws DateTimeException if the epoch day exceeds the supported date range. Below programs illustrate the ofEpochDay(long epochDay) method in Java: Program 1: // Java program to demonstrate// LocalDate.ofEpochDay(long epochDay) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalDate object LocalDate localdate = LocalDate.ofEpochDay(100); // Display full date System.out.println("Date: " + localdate); }} Date: 1970-04-11 Program 2: // Java program to demonstrate// LocalDate.ofEpochDay(long epochDay) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalDate object LocalDate localdate = LocalDate.ofEpochDay(365); // Display date System.out.println("Date: " + localdate); }} Date: 1971-01-01 References:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#ofEpochDay(long) Java-Functions Java-LocalDate Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n21 May, 2020" }, { "code": null, "e": 536, "s": 28, "text": "The ofEpochDay(long epochDay) method of LocalDate class in Java is used to obtain an instance of LocalDate from the epoch day count. Epoch day is 01-01-1970(DD-MM-YYYY). This is considered as a start of the epoch day. The method returns the LocalDate by adding the passed days into Epoch date i.e. 01-01-1970. Suppose 2 is passed as a parameter, the method will return 03-01-1970 (2 is added to ’01’ from the epoch day(DD)). Similarly, if 365 is passed then a whole new year will be added to the epoch date." }, { "code": null, "e": 544, "s": 536, "text": "Syntax:" }, { "code": null, "e": 595, "s": 544, "text": "public static LocalDate ofEpochDay(long epochDay)\n" }, { "code": null, "e": 680, "s": 595, "text": "Parameters: This method accepts one parameter epochDay which is the conversion base." }, { "code": null, "e": 746, "s": 680, "text": "Return Value: This method returns the localdate after conversion." }, { "code": null, "e": 846, "s": 746, "text": "Exceptions: This method throws DateTimeException if the epoch day exceeds the supported date range." }, { "code": null, "e": 918, "s": 846, "text": "Below programs illustrate the ofEpochDay(long epochDay) method in Java:" }, { "code": null, "e": 929, "s": 918, "text": "Program 1:" }, { "code": "// Java program to demonstrate// LocalDate.ofEpochDay(long epochDay) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalDate object LocalDate localdate = LocalDate.ofEpochDay(100); // Display full date System.out.println(\"Date: \" + localdate); }}", "e": 1333, "s": 929, "text": null }, { "code": null, "e": 1351, "s": 1333, "text": "Date: 1970-04-11\n" }, { "code": null, "e": 1362, "s": 1351, "text": "Program 2:" }, { "code": "// Java program to demonstrate// LocalDate.ofEpochDay(long epochDay) method import java.time.*;import java.time.temporal.*; public class GFG { public static void main(String[] args) { // Create LocalDate object LocalDate localdate = LocalDate.ofEpochDay(365); // Display date System.out.println(\"Date: \" + localdate); }}", "e": 1761, "s": 1362, "text": null }, { "code": null, "e": 1779, "s": 1761, "text": "Date: 1971-01-01\n" }, { "code": null, "e": 1875, "s": 1779, "text": "References:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#ofEpochDay(long)" }, { "code": null, "e": 1890, "s": 1875, "text": "Java-Functions" }, { "code": null, "e": 1905, "s": 1890, "text": "Java-LocalDate" }, { "code": null, "e": 1910, "s": 1905, "text": "Java" }, { "code": null, "e": 1915, "s": 1910, "text": "Java" }, { "code": null, "e": 2013, "s": 1915, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2028, "s": 2013, "text": "Stream In Java" }, { "code": null, "e": 2049, "s": 2028, "text": "Introduction to Java" }, { "code": null, "e": 2070, "s": 2049, "text": "Constructors in Java" }, { "code": null, "e": 2089, "s": 2070, "text": "Exceptions in Java" }, { "code": null, "e": 2106, "s": 2089, "text": "Generics in Java" }, { "code": null, "e": 2136, "s": 2106, "text": "Functional Interfaces in Java" }, { "code": null, "e": 2162, "s": 2136, "text": "Java Programming Examples" }, { "code": null, "e": 2178, "s": 2162, "text": "Strings in Java" }, { "code": null, "e": 2215, "s": 2178, "text": "Differences between JDK, JRE and JVM" } ]
Properties keys() method in Java with Examples
30 Sep, 2019 The keys() method of Properties class is used to get the enumeration of the keys in this Properties object. This enumeration can be used to traverse and iterate the keys sequentially. Syntax: public Enumeration keys() Parameters: This method accepts no parameters Returns: This method returns an Enumeration of the keys of this Properties object sequentially. Below programs show the implementation of int keys() method. Program 1: // Java code to show the implementation of// keys() method import java.util.*;public class GfG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put("Pen", 10); properties.put("Book", 500); properties.put("Clothes", 400); properties.put("Mobile", 5000); // Print Properties details System.out.println("Properties: " + properties.toString()); // Creating an empty enumeration to store Enumeration enu = properties.keys(); System.out.println("The enumeration of keys are:"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }} Properties: {Book=500, Mobile=5000, Pen=10, Clothes=400} The enumeration of keys are: Book Mobile Pen Clothes Program 2: // Java program to demonstrate// keys() method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); // Inserting elements into the properties properties.put("Geeks", 10); properties.put("4", 15); properties.put("Geeks", 20); properties.put("Welcomes", 25); properties.put("You", 30); // Print Properties details System.out.println("Current Properties: " + properties.toString()); // Creating an empty enumeration to store Enumeration enu = properties.keys(); System.out.println("The enumeration of keys are:"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }} Current Properties: {You=30, Welcomes=25, 4=15, Geeks=20} The enumeration of keys are: You Welcomes 4 Geeks References: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#keys– Akanksha_Rai Java - util package Java-Functions Java-Properties Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Sep, 2019" }, { "code": null, "e": 212, "s": 28, "text": "The keys() method of Properties class is used to get the enumeration of the keys in this Properties object. This enumeration can be used to traverse and iterate the keys sequentially." }, { "code": null, "e": 220, "s": 212, "text": "Syntax:" }, { "code": null, "e": 246, "s": 220, "text": "public Enumeration keys()" }, { "code": null, "e": 292, "s": 246, "text": "Parameters: This method accepts no parameters" }, { "code": null, "e": 388, "s": 292, "text": "Returns: This method returns an Enumeration of the keys of this Properties object sequentially." }, { "code": null, "e": 449, "s": 388, "text": "Below programs show the implementation of int keys() method." }, { "code": null, "e": 460, "s": 449, "text": "Program 1:" }, { "code": "// Java code to show the implementation of// keys() method import java.util.*;public class GfG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put(\"Pen\", 10); properties.put(\"Book\", 500); properties.put(\"Clothes\", 400); properties.put(\"Mobile\", 5000); // Print Properties details System.out.println(\"Properties: \" + properties.toString()); // Creating an empty enumeration to store Enumeration enu = properties.keys(); System.out.println(\"The enumeration of keys are:\"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }}", "e": 1303, "s": 460, "text": null }, { "code": null, "e": 1414, "s": 1303, "text": "Properties: {Book=500, Mobile=5000, Pen=10, Clothes=400}\nThe enumeration of keys are:\nBook\nMobile\nPen\nClothes\n" }, { "code": null, "e": 1425, "s": 1414, "text": "Program 2:" }, { "code": "// Java program to demonstrate// keys() method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); // Inserting elements into the properties properties.put(\"Geeks\", 10); properties.put(\"4\", 15); properties.put(\"Geeks\", 20); properties.put(\"Welcomes\", 25); properties.put(\"You\", 30); // Print Properties details System.out.println(\"Current Properties: \" + properties.toString()); // Creating an empty enumeration to store Enumeration enu = properties.keys(); System.out.println(\"The enumeration of keys are:\"); // Displaying the Enumeration while (enu.hasMoreElements()) { System.out.println(enu.nextElement()); } }}", "e": 2347, "s": 1425, "text": null }, { "code": null, "e": 2456, "s": 2347, "text": "Current Properties: {You=30, Welcomes=25, 4=15, Geeks=20}\nThe enumeration of keys are:\nYou\nWelcomes\n4\nGeeks\n" }, { "code": null, "e": 2542, "s": 2456, "text": "References: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#keys–" }, { "code": null, "e": 2555, "s": 2542, "text": "Akanksha_Rai" }, { "code": null, "e": 2575, "s": 2555, "text": "Java - util package" }, { "code": null, "e": 2590, "s": 2575, "text": "Java-Functions" }, { "code": null, "e": 2606, "s": 2590, "text": "Java-Properties" }, { "code": null, "e": 2611, "s": 2606, "text": "Java" }, { "code": null, "e": 2616, "s": 2611, "text": "Java" }, { "code": null, "e": 2714, "s": 2616, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2729, "s": 2714, "text": "Stream In Java" }, { "code": null, "e": 2750, "s": 2729, "text": "Introduction to Java" }, { "code": null, "e": 2771, "s": 2750, "text": "Constructors in Java" }, { "code": null, "e": 2790, "s": 2771, "text": "Exceptions in Java" }, { "code": null, "e": 2807, "s": 2790, "text": "Generics in Java" }, { "code": null, "e": 2837, "s": 2807, "text": "Functional Interfaces in Java" }, { "code": null, "e": 2863, "s": 2837, "text": "Java Programming Examples" }, { "code": null, "e": 2879, "s": 2863, "text": "Strings in Java" }, { "code": null, "e": 2916, "s": 2879, "text": "Differences between JDK, JRE and JVM" } ]
Segment tree | Efficient implementation
29 Mar, 2022 Let us consider the following problem to understand Segment Trees without recursion.We have an array arr[0 . . . n-1]. We should be able to, Find the sum of elements from index l to r where 0 <= l <= r <= n-1Change the value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 <= i <= n-1. Find the sum of elements from index l to r where 0 <= l <= r <= n-1 Change the value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 <= i <= n-1. A simple solution is to run a loop from l to r and calculate the sum of elements in the given range. To update a value, simply do arr[i] = x. The first operation takes O(n) time and the second operation takes O(1) time. Another solution is to create another array and store the sum from start to i at the ith index in this array. The sum of a given range can now be calculated in O(1) time, but the update operation takes O(n) time now. This works well if the number of query operations is large and there are very few updates.What if the number of queries and updates are equal? Can we perform both the operations in O(log n) time once given the array? We can use a Segment Tree to do both operations in O(Logn) time. We have discussed the complete implementation of segment trees in our previous post. In this post, we will discuss the easier and yet efficient implementation of segment trees than in the previous post.Consider the array and segment tree as shown below: You can see from the above image that the original array is at the bottom and is 0-indexed with 16 elements. The tree contains a total of 31 nodes where the leaf nodes or the elements of the original array start from node 16. So, we can easily construct a segment tree for this array using a 2*N sized array where N is the number of elements in the original array. The leaf nodes will start from index N in this array and will go up to index (2*N – 1). Therefore, the element at index i in the original array will be at index (i + N) in the segment tree array. Now to calculate the parents, we will start from the index (N – 1) and move upward. For index i , the left child will be at (2 * i) and the right child will be at (2*i + 1) index. So the values at nodes at (2 * i) and (2*i + 1) are combined at i-th node to construct the tree. As you can see in the above figure, we can query in this tree in an interval [L,R) with left index(L) included and right (R) excluded.We will implement all of these multiplication and addition operations using bitwise operators.Let us have a look at the complete implementation: C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; // limit for array sizeconst int N = 100000; int n; // array size // Max size of treeint tree[2 * N]; // function to build the treevoid build( int arr[]){ // insert leaf nodes in tree for (int i=0; i<n; i++) tree[n+i] = arr[i]; // build the tree by calculating parents for (int i = n - 1; i > 0; --i) tree[i] = tree[i<<1] + tree[i<<1 | 1]; } // function to update a tree nodevoid updateTreeNode(int p, int value){ // set value at position p tree[p+n] = value; p = p+n; // move upward and update parents for (int i=p; i > 1; i >>= 1) tree[i>>1] = tree[i] + tree[i^1];} // function to get sum on interval [l, r)int query(int l, int r){ int res = 0; // loop to find the sum in the range for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if (l&1) res += tree[l++]; if (r&1) res += tree[--r]; } return res;} // driver program to test the above functionint main(){ int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; // n is global n = sizeof(a)/sizeof(a[0]); // build tree build(a); // print the sum in range(1,2) index-based cout << query(1, 3)<<endl; // modify element at 2nd index updateTreeNode(2, 1); // print the sum in range(1,2) index-based cout << query(1, 3)<<endl; return 0;} import java.io.*; public class GFG { // limit for array size static int N = 100000; static int n; // array size // Max size of tree static int []tree = new int[2 * N]; // function to build the tree static void build( int []arr) { // insert leaf nodes in tree for (int i = 0; i < n; i++) tree[n + i] = arr[i]; // build the tree by calculating // parents for (int i = n - 1; i > 0; --i) tree[i] = tree[i << 1] + tree[i << 1 | 1]; } // function to update a tree node static void updateTreeNode(int p, int value) { // set value at position p tree[p + n] = value; p = p + n; // move upward and update parents for (int i = p; i > 1; i >>= 1) tree[i >> 1] = tree[i] + tree[i^1]; } // function to get sum on // interval [l, r) static int query(int l, int r) { int res = 0; // loop to find the sum in the range for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if ((l & 1) > 0) res += tree[l++]; if ((r & 1) > 0) res += tree[--r]; } return res; } // driver program to test the // above function static public void main (String[] args) { int []a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; // n is global n = a.length; // build tree build(a); // print the sum in range(1,2) // index-based System.out.println(query(1, 3)); // modify element at 2nd index updateTreeNode(2, 1); // print the sum in range(1,2) // index-based System.out.println(query(1, 3)); }} // This code is contributed by vt_m. # Python3 Code Addition # limit for array sizeN = 100000; # Max size of treetree = [0] * (2 * N); # function to build the treedef build(arr) : # insert leaf nodes in tree for i in range(n) : tree[n + i] = arr[i]; # build the tree by calculating parents for i in range(n - 1, 0, -1) : tree[i] = tree[i << 1] + tree[i << 1 | 1]; # function to update a tree nodedef updateTreeNode(p, value) : # set value at position p tree[p + n] = value; p = p + n; # move upward and update parents i = p; while i > 1 : tree[i >> 1] = tree[i] + tree[i ^ 1]; i >>= 1; # function to get sum on interval [l, r)def query(l, r) : res = 0; # loop to find the sum in the range l += n; r += n; while l < r : if (l & 1) : res += tree[l]; l += 1 if (r & 1) : r -= 1; res += tree[r]; l >>= 1; r >>= 1 return res; # Driver Codeif __name__ == "__main__" : a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; # n is global n = len(a); # build tree build(a); # print the sum in range(1,2) index-based print(query(1, 3)); # modify element at 2nd index updateTreeNode(2, 1); # print the sum in range(1,2) index-based print(query(1, 3)); # This code is contributed by AnkitRai01 using System; public class GFG { // limit for array size static int N = 100000; static int n; // array size // Max size of tree static int []tree = new int[2 * N]; // function to build the tree static void build( int []arr) { // insert leaf nodes in tree for (int i = 0; i < n; i++) tree[n + i] = arr[i]; // build the tree by calculating // parents for (int i = n - 1; i > 0; --i) tree[i] = tree[i << 1] + tree[i << 1 | 1]; } // function to update a tree node static void updateTreeNode(int p, int value) { // set value at position p tree[p + n] = value; p = p + n; // move upward and update parents for (int i = p; i > 1; i >>= 1) tree[i >> 1] = tree[i] + tree[i^1]; } // function to get sum on // interval [l, r) static int query(int l, int r) { int res = 0; // loop to find the sum in the range for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if ((l & 1) > 0) res += tree[l++]; if ((r & 1) > 0) res += tree[--r]; } return res; } // driver program to test the // above function static public void Main () { int []a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; // n is global n = a.Length; // build tree build(a); // print the sum in range(1,2) // index-based Console.WriteLine(query(1, 3)); // modify element at 2nd index updateTreeNode(2, 1); // print the sum in range(1,2) // index-based Console.WriteLine(query(1, 3)); }} // This code is contributed by vt_m. <script> // limit for array size let N = 100000; let n; // array size // Max size of tree let tree = new Array(2 * N); tree.fill(0); // function to build the tree function build(arr) { // insert leaf nodes in tree for (let i = 0; i < n; i++) tree[n + i] = arr[i]; // build the tree by calculating // parents for (let i = n - 1; i > 0; --i) tree[i] = tree[i << 1] + tree[i << 1 | 1]; } // function to update a tree node function updateTreeNode(p, value) { // set value at position p tree[p + n] = value; p = p + n; // move upward and update parents for (let i = p; i > 1; i >>= 1) tree[i >> 1] = tree[i] + tree[i^1]; } // function to get sum on // interval [l, r) function query(l, r) { let res = 0; // loop to find the sum in the range for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if ((l & 1) > 0) res += tree[l++]; if ((r & 1) > 0) res += tree[--r]; } return res; } let a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; // n is global n = a.length; // build tree build(a); // print the sum in range(1,2) // index-based document.write(query(1, 3) + "</br>"); // modify element at 2nd index updateTreeNode(2, 1); // print the sum in range(1,2) // index-based document.write(query(1, 3)); </script> Output: 5 3 Yes! That is all. The complete implementation of the segment tree includes the query and update functions in a lower number of lines of code than the previous recursive one. Let us now understand how each of the functions works: 1. The picture makes it clear that the leaf nodes are stored at i+n, so we can clearly insert all leaf nodes directly. 2. The next step is to build the tree and it takes O(n) time. The parent always has its less index than its children, so we just process all the nodes in decreasing order, calculating the value of the parent node. If the code inside the build function to calculate parents seems confusing, then you can see this code. It is equivalent to that inside the build function. tree[i]=tree[2*i]+tree[2*i+1] 3. Updating a value at any position is also simple and the time taken will be proportional to the height of the tree. We only update values in the parents of the given node which is being changed. So to get the parent, we just go up to the parent node, which is p/2 or p>>1, for node p. p^1 turns (2*i) to (2*i + 1) and vice versa to get the second child of p. 4. Computing the sum also works in O(log(n)) time. If we work through an interval of [3,11), we need to calculate only for nodes 19,26,12, and 5 in that order. The idea behind the query function is whether we should include an element in the sum or whether we should include its parent. Let’s look at the image once again for proper understanding. Consider that L is the left border of an interval and R is the right border of the interval [L,R). It is clear from the image that if L is odd, then it means that it is the right child of its parent and our interval includes only L and not the parent. So we will simply include this node to sum and move to the parent of its next node by doing L = (L+1)/2. Now, if L is even, then it is the left child of its parent and the interval includes its parent also unless the right borders interfere. Similar conditions are applied to the right border also for faster computation. We will stop this iteration once the left and right borders meet.The theoretical time complexities of both previous implementation and this implementation is the same, but practically, it is found to be much more efficient as there are no recursive calls. We simply iterate over the elements that we need. Also, this is very easy to implement. Time Complexities: Tree Construction: O( n ) Query in Range: O( Log n ) Updating an element: O( Log n ). Auxiliary Space: O(2*N)This article is contributed by Striver. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m ankthon suresh07 rishavnitro Segment-Tree Advanced Data Structure Segment-Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. AVL Tree | Set 1 (Insertion) Trie | (Insert and Search) LRU Cache Implementation Introduction of B-Tree Red-Black Tree | Set 1 (Introduction) Agents in Artificial Intelligence Decision Tree Introduction with example Binary Indexed Tree or Fenwick Tree Count of strings whose prefix match with the given string to a given length k Ordered Set and GNU C++ PBDS
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Mar, 2022" }, { "code": null, "e": 195, "s": 52, "text": "Let us consider the following problem to understand Segment Trees without recursion.We have an array arr[0 . . . n-1]. We should be able to, " }, { "code": null, "e": 380, "s": 195, "text": "Find the sum of elements from index l to r where 0 <= l <= r <= n-1Change the value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 <= i <= n-1. " }, { "code": null, "e": 448, "s": 380, "text": "Find the sum of elements from index l to r where 0 <= l <= r <= n-1" }, { "code": null, "e": 566, "s": 448, "text": "Change the value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 <= i <= n-1. " }, { "code": null, "e": 786, "s": 566, "text": "A simple solution is to run a loop from l to r and calculate the sum of elements in the given range. To update a value, simply do arr[i] = x. The first operation takes O(n) time and the second operation takes O(1) time." }, { "code": null, "e": 1541, "s": 786, "text": "Another solution is to create another array and store the sum from start to i at the ith index in this array. The sum of a given range can now be calculated in O(1) time, but the update operation takes O(n) time now. This works well if the number of query operations is large and there are very few updates.What if the number of queries and updates are equal? Can we perform both the operations in O(log n) time once given the array? We can use a Segment Tree to do both operations in O(Logn) time. We have discussed the complete implementation of segment trees in our previous post. In this post, we will discuss the easier and yet efficient implementation of segment trees than in the previous post.Consider the array and segment tree as shown below: " }, { "code": null, "e": 2660, "s": 1541, "text": "You can see from the above image that the original array is at the bottom and is 0-indexed with 16 elements. The tree contains a total of 31 nodes where the leaf nodes or the elements of the original array start from node 16. So, we can easily construct a segment tree for this array using a 2*N sized array where N is the number of elements in the original array. The leaf nodes will start from index N in this array and will go up to index (2*N – 1). Therefore, the element at index i in the original array will be at index (i + N) in the segment tree array. Now to calculate the parents, we will start from the index (N – 1) and move upward. For index i , the left child will be at (2 * i) and the right child will be at (2*i + 1) index. So the values at nodes at (2 * i) and (2*i + 1) are combined at i-th node to construct the tree. As you can see in the above figure, we can query in this tree in an interval [L,R) with left index(L) included and right (R) excluded.We will implement all of these multiplication and addition operations using bitwise operators.Let us have a look at the complete implementation: " }, { "code": null, "e": 2664, "s": 2660, "text": "C++" }, { "code": null, "e": 2669, "s": 2664, "text": "Java" }, { "code": null, "e": 2677, "s": 2669, "text": "Python3" }, { "code": null, "e": 2680, "s": 2677, "text": "C#" }, { "code": null, "e": 2691, "s": 2680, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // limit for array sizeconst int N = 100000; int n; // array size // Max size of treeint tree[2 * N]; // function to build the treevoid build( int arr[]){ // insert leaf nodes in tree for (int i=0; i<n; i++) tree[n+i] = arr[i]; // build the tree by calculating parents for (int i = n - 1; i > 0; --i) tree[i] = tree[i<<1] + tree[i<<1 | 1]; } // function to update a tree nodevoid updateTreeNode(int p, int value){ // set value at position p tree[p+n] = value; p = p+n; // move upward and update parents for (int i=p; i > 1; i >>= 1) tree[i>>1] = tree[i] + tree[i^1];} // function to get sum on interval [l, r)int query(int l, int r){ int res = 0; // loop to find the sum in the range for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if (l&1) res += tree[l++]; if (r&1) res += tree[--r]; } return res;} // driver program to test the above functionint main(){ int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; // n is global n = sizeof(a)/sizeof(a[0]); // build tree build(a); // print the sum in range(1,2) index-based cout << query(1, 3)<<endl; // modify element at 2nd index updateTreeNode(2, 1); // print the sum in range(1,2) index-based cout << query(1, 3)<<endl; return 0;}", "e": 4109, "s": 2691, "text": null }, { "code": "import java.io.*; public class GFG { // limit for array size static int N = 100000; static int n; // array size // Max size of tree static int []tree = new int[2 * N]; // function to build the tree static void build( int []arr) { // insert leaf nodes in tree for (int i = 0; i < n; i++) tree[n + i] = arr[i]; // build the tree by calculating // parents for (int i = n - 1; i > 0; --i) tree[i] = tree[i << 1] + tree[i << 1 | 1]; } // function to update a tree node static void updateTreeNode(int p, int value) { // set value at position p tree[p + n] = value; p = p + n; // move upward and update parents for (int i = p; i > 1; i >>= 1) tree[i >> 1] = tree[i] + tree[i^1]; } // function to get sum on // interval [l, r) static int query(int l, int r) { int res = 0; // loop to find the sum in the range for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if ((l & 1) > 0) res += tree[l++]; if ((r & 1) > 0) res += tree[--r]; } return res; } // driver program to test the // above function static public void main (String[] args) { int []a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; // n is global n = a.length; // build tree build(a); // print the sum in range(1,2) // index-based System.out.println(query(1, 3)); // modify element at 2nd index updateTreeNode(2, 1); // print the sum in range(1,2) // index-based System.out.println(query(1, 3)); }} // This code is contributed by vt_m.", "e": 6066, "s": 4109, "text": null }, { "code": "# Python3 Code Addition # limit for array sizeN = 100000; # Max size of treetree = [0] * (2 * N); # function to build the treedef build(arr) : # insert leaf nodes in tree for i in range(n) : tree[n + i] = arr[i]; # build the tree by calculating parents for i in range(n - 1, 0, -1) : tree[i] = tree[i << 1] + tree[i << 1 | 1]; # function to update a tree nodedef updateTreeNode(p, value) : # set value at position p tree[p + n] = value; p = p + n; # move upward and update parents i = p; while i > 1 : tree[i >> 1] = tree[i] + tree[i ^ 1]; i >>= 1; # function to get sum on interval [l, r)def query(l, r) : res = 0; # loop to find the sum in the range l += n; r += n; while l < r : if (l & 1) : res += tree[l]; l += 1 if (r & 1) : r -= 1; res += tree[r]; l >>= 1; r >>= 1 return res; # Driver Codeif __name__ == \"__main__\" : a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; # n is global n = len(a); # build tree build(a); # print the sum in range(1,2) index-based print(query(1, 3)); # modify element at 2nd index updateTreeNode(2, 1); # print the sum in range(1,2) index-based print(query(1, 3)); # This code is contributed by AnkitRai01", "e": 7478, "s": 6066, "text": null }, { "code": "using System; public class GFG { // limit for array size static int N = 100000; static int n; // array size // Max size of tree static int []tree = new int[2 * N]; // function to build the tree static void build( int []arr) { // insert leaf nodes in tree for (int i = 0; i < n; i++) tree[n + i] = arr[i]; // build the tree by calculating // parents for (int i = n - 1; i > 0; --i) tree[i] = tree[i << 1] + tree[i << 1 | 1]; } // function to update a tree node static void updateTreeNode(int p, int value) { // set value at position p tree[p + n] = value; p = p + n; // move upward and update parents for (int i = p; i > 1; i >>= 1) tree[i >> 1] = tree[i] + tree[i^1]; } // function to get sum on // interval [l, r) static int query(int l, int r) { int res = 0; // loop to find the sum in the range for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if ((l & 1) > 0) res += tree[l++]; if ((r & 1) > 0) res += tree[--r]; } return res; } // driver program to test the // above function static public void Main () { int []a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; // n is global n = a.Length; // build tree build(a); // print the sum in range(1,2) // index-based Console.WriteLine(query(1, 3)); // modify element at 2nd index updateTreeNode(2, 1); // print the sum in range(1,2) // index-based Console.WriteLine(query(1, 3)); }} // This code is contributed by vt_m.", "e": 9404, "s": 7478, "text": null }, { "code": "<script> // limit for array size let N = 100000; let n; // array size // Max size of tree let tree = new Array(2 * N); tree.fill(0); // function to build the tree function build(arr) { // insert leaf nodes in tree for (let i = 0; i < n; i++) tree[n + i] = arr[i]; // build the tree by calculating // parents for (let i = n - 1; i > 0; --i) tree[i] = tree[i << 1] + tree[i << 1 | 1]; } // function to update a tree node function updateTreeNode(p, value) { // set value at position p tree[p + n] = value; p = p + n; // move upward and update parents for (let i = p; i > 1; i >>= 1) tree[i >> 1] = tree[i] + tree[i^1]; } // function to get sum on // interval [l, r) function query(l, r) { let res = 0; // loop to find the sum in the range for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if ((l & 1) > 0) res += tree[l++]; if ((r & 1) > 0) res += tree[--r]; } return res; } let a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; // n is global n = a.length; // build tree build(a); // print the sum in range(1,2) // index-based document.write(query(1, 3) + \"</br>\"); // modify element at 2nd index updateTreeNode(2, 1); // print the sum in range(1,2) // index-based document.write(query(1, 3)); </script>", "e": 11063, "s": 9404, "text": null }, { "code": null, "e": 11072, "s": 11063, "text": "Output: " }, { "code": null, "e": 11076, "s": 11072, "text": "5\n3" }, { "code": null, "e": 11307, "s": 11076, "text": "Yes! That is all. The complete implementation of the segment tree includes the query and update functions in a lower number of lines of code than the previous recursive one. Let us now understand how each of the functions works: " }, { "code": null, "e": 11426, "s": 11307, "text": "1. The picture makes it clear that the leaf nodes are stored at i+n, so we can clearly insert all leaf nodes directly." }, { "code": null, "e": 11797, "s": 11426, "text": "2. The next step is to build the tree and it takes O(n) time. The parent always has its less index than its children, so we just process all the nodes in decreasing order, calculating the value of the parent node. If the code inside the build function to calculate parents seems confusing, then you can see this code. It is equivalent to that inside the build function. " }, { "code": null, "e": 11827, "s": 11797, "text": "tree[i]=tree[2*i]+tree[2*i+1]" }, { "code": null, "e": 12190, "s": 11829, "text": "3. Updating a value at any position is also simple and the time taken will be proportional to the height of the tree. We only update values in the parents of the given node which is being changed. So to get the parent, we just go up to the parent node, which is p/2 or p>>1, for node p. p^1 turns (2*i) to (2*i + 1) and vice versa to get the second child of p." }, { "code": null, "e": 12350, "s": 12190, "text": "4. Computing the sum also works in O(log(n)) time. If we work through an interval of [3,11), we need to calculate only for nodes 19,26,12, and 5 in that order." }, { "code": null, "e": 13456, "s": 12350, "text": "The idea behind the query function is whether we should include an element in the sum or whether we should include its parent. Let’s look at the image once again for proper understanding. Consider that L is the left border of an interval and R is the right border of the interval [L,R). It is clear from the image that if L is odd, then it means that it is the right child of its parent and our interval includes only L and not the parent. So we will simply include this node to sum and move to the parent of its next node by doing L = (L+1)/2. Now, if L is even, then it is the left child of its parent and the interval includes its parent also unless the right borders interfere. Similar conditions are applied to the right border also for faster computation. We will stop this iteration once the left and right borders meet.The theoretical time complexities of both previous implementation and this implementation is the same, but practically, it is found to be much more efficient as there are no recursive calls. We simply iterate over the elements that we need. Also, this is very easy to implement." }, { "code": null, "e": 13475, "s": 13456, "text": "Time Complexities:" }, { "code": null, "e": 13501, "s": 13475, "text": "Tree Construction: O( n )" }, { "code": null, "e": 13528, "s": 13501, "text": "Query in Range: O( Log n )" }, { "code": null, "e": 13561, "s": 13528, "text": "Updating an element: O( Log n )." }, { "code": null, "e": 14000, "s": 13561, "text": "Auxiliary Space: O(2*N)This article is contributed by Striver. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 14005, "s": 14000, "text": "vt_m" }, { "code": null, "e": 14013, "s": 14005, "text": "ankthon" }, { "code": null, "e": 14022, "s": 14013, "text": "suresh07" }, { "code": null, "e": 14034, "s": 14022, "text": "rishavnitro" }, { "code": null, "e": 14047, "s": 14034, "text": "Segment-Tree" }, { "code": null, "e": 14071, "s": 14047, "text": "Advanced Data Structure" }, { "code": null, "e": 14084, "s": 14071, "text": "Segment-Tree" }, { "code": null, "e": 14182, "s": 14084, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14211, "s": 14182, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 14238, "s": 14211, "text": "Trie | (Insert and Search)" }, { "code": null, "e": 14263, "s": 14238, "text": "LRU Cache Implementation" }, { "code": null, "e": 14286, "s": 14263, "text": "Introduction of B-Tree" }, { "code": null, "e": 14324, "s": 14286, "text": "Red-Black Tree | Set 1 (Introduction)" }, { "code": null, "e": 14358, "s": 14324, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 14398, "s": 14358, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 14434, "s": 14398, "text": "Binary Indexed Tree or Fenwick Tree" }, { "code": null, "e": 14512, "s": 14434, "text": "Count of strings whose prefix match with the given string to a given length k" } ]
Kotlin - Environment Setup
One of the key features of Kotlin is that it has interoperability with Java i.e. You can write Kotlin and Java code in the same application. Like Java, Kotlin also runs on JVM therefore to install Kotlin on Windows directly and work with it using the command line You need to make sure you have JDK installed in your system. To verify Java installation − Open command prompt and verify the current version of Java using the javac version command − C:\Users\TP>javac -version javac 1.8.0_261 If you doesn’t have Java installed in your system it generates the following error C:\Users\Krishna Kasyap>javac -v 'javac' is not recognized as an internal or external command, operable program or batch file. You can install JDK by following the steps given below Open the following Oracle Java Downloads page. Click on the JDK Download link under Java SE 8 section. This will redirect to the page that contains JDK software for various platforms, select the desired version (.exe) and download it. After downloading the file JDK file (assume we have downloaded jdk_windows-x64_bin.exe), start the installation by running it. By default, Java will be installed in the path C:\Program Files\Java\jdk1.8.0_301\ you can change the path by clicking on the Change... button. After the completion of the installation click on the Close button. Kotlin command line compiler is available at the JetBrains Kotlin GitHub releases page. Download the latest version. Unzip the downloaded file and place it in the desired folder. The Bin directory of the downloaded folder contains all the binary files to run Kotlin. Now, set Path environment variable to this folder. Right click on My computer or This PC, select Properties. Click on Advanced System Settings. Then, click on the Environment Variables... button. In the Environment Variables window, under System Variables select the Path variable and edit the variables using the Edit... button. Click on the New button and add the path of the bin folder of installed JDK and Kotlin folders. To verify the installation, open command prompt and type java or javac command, if your installation is successful, you can see the output as shown below: Kotlin is developed by the JetBrains that develops IDEs like AppCode, CLion, DataGrip, DataSpell, GoLand, IntelliJ IDEA etc. The IntelliJ IDEA internally have Kotlin plugin bundled with it. To develop Kotlin download and install IntelliJ. To install a recent version of IntelliJ IDEA: Open JetBrains Downloads page, you can download the free community edition. If you run the downloaded file, it starts the installation process. Proceed with the installation by providing the required details and finally complete the installation. The Plugins tab of IntelliJ displays all the available plugins. By default, Kotlin plugin is activated, in any case if it is not activated. Open the plugin tab, search for Kotlin and install it. To create first application, click on NewProject. Select Kotlin/JVM and click Next. Name the project and select the desired location. Now, create a new Kotlin file under the source(src) folder and let’s name it as Test. You can create a sample function as shown below. You can run this by pressing Ctrl + Shift + F10. You can also execute Kotlin programs in eclipse to do so, you need to have “Eclipse IDE for Java developers” installed in your system. To do so, follow the steps given below. Download the latest version of eclipse installer from the page: https://www.eclipse.org/downloads/ Run the downloaded file and click on the Eclipse IDE for Java developers. Select the installation directory and click on install. Open eclipse in the Help menu select Eclipse Marketplace. Search for Kotlin and check all the matches and when you find Kotlin click on Install. Once you have installed Kotlin plugin in your eclipse to create your first application. In the File menu click on Project. This will take you to Select a wizard. Under Kotlin (dropdown menu), click on select “Kotlin Project” and click on the “Next” button. Then, enter the desired name for the application and click on Next. Right click on the src folder of the created project click on other. Select the Kotlin File wizard click on Next and name the file as Hello.kt. Your development environment is ready now. Go ahead and add the following piece of code in the “Hello.kt” file. fun main(args: Array) { println("Hello, World!") } Run it as a Kotlin application and see the output in the console as shown in the following screenshot. For better understanding and availability, we will be using our coding ground tool.
[ { "code": null, "e": 2884, "s": 2559, "text": "One of the key features of Kotlin is that it has interoperability with Java i.e. You can write Kotlin and Java code in the same application. Like Java, Kotlin also runs on JVM therefore to install Kotlin on Windows directly and work with it using the command line You need to make sure you have JDK installed in your system." }, { "code": null, "e": 2914, "s": 2884, "text": "To verify Java installation −" }, { "code": null, "e": 3007, "s": 2914, "text": "Open command prompt and verify the current version of Java using the javac version command −" }, { "code": null, "e": 3051, "s": 3007, "text": "C:\\Users\\TP>javac -version\njavac 1.8.0_261\n" }, { "code": null, "e": 3134, "s": 3051, "text": "If you doesn’t have Java installed in your system it generates the following error" }, { "code": null, "e": 3262, "s": 3134, "text": "C:\\Users\\Krishna Kasyap>javac -v\n'javac' is not recognized as an internal or external command,\noperable program or batch file.\n" }, { "code": null, "e": 3317, "s": 3262, "text": "You can install JDK by following the steps given below" }, { "code": null, "e": 3364, "s": 3317, "text": "Open the following Oracle Java Downloads page." }, { "code": null, "e": 3420, "s": 3364, "text": "Click on the JDK Download link under Java SE 8 section." }, { "code": null, "e": 3552, "s": 3420, "text": "This will redirect to the page that contains JDK software for various platforms, select the desired version (.exe) and download it." }, { "code": null, "e": 3679, "s": 3552, "text": "After downloading the file JDK file (assume we have downloaded jdk_windows-x64_bin.exe), start the installation by running it." }, { "code": null, "e": 3823, "s": 3679, "text": "By default, Java will be installed in the path C:\\Program Files\\Java\\jdk1.8.0_301\\ you can change the path by clicking on the Change... button." }, { "code": null, "e": 3891, "s": 3823, "text": "After the completion of the installation click on the Close button." }, { "code": null, "e": 3979, "s": 3891, "text": "Kotlin command line compiler is available at the JetBrains Kotlin GitHub releases page." }, { "code": null, "e": 4008, "s": 3979, "text": "Download the latest version." }, { "code": null, "e": 4070, "s": 4008, "text": "Unzip the downloaded file and place it in the desired folder." }, { "code": null, "e": 4158, "s": 4070, "text": "The Bin directory of the downloaded folder contains all the binary files to run Kotlin." }, { "code": null, "e": 4209, "s": 4158, "text": "Now, set Path environment variable to this folder." }, { "code": null, "e": 4267, "s": 4209, "text": "Right click on My computer or This PC, select Properties." }, { "code": null, "e": 4302, "s": 4267, "text": "Click on Advanced System Settings." }, { "code": null, "e": 4354, "s": 4302, "text": "Then, click on the Environment Variables... button." }, { "code": null, "e": 4488, "s": 4354, "text": "In the Environment Variables window, under System Variables select the Path variable and edit the variables using the Edit... button." }, { "code": null, "e": 4584, "s": 4488, "text": "Click on the New button and add the path of the bin folder of installed JDK and Kotlin folders." }, { "code": null, "e": 4739, "s": 4584, "text": "To verify the installation, open command prompt and type java or javac command, if your installation is successful, you can see the output as shown below:" }, { "code": null, "e": 4864, "s": 4739, "text": "Kotlin is developed by the JetBrains that develops IDEs like AppCode, CLion, DataGrip, DataSpell, GoLand, IntelliJ IDEA etc." }, { "code": null, "e": 4978, "s": 4864, "text": "The IntelliJ IDEA internally have Kotlin plugin bundled with it. To develop Kotlin download and install IntelliJ." }, { "code": null, "e": 5024, "s": 4978, "text": "To install a recent version of IntelliJ IDEA:" }, { "code": null, "e": 5100, "s": 5024, "text": "Open JetBrains Downloads page, you can download the free community edition." }, { "code": null, "e": 5168, "s": 5100, "text": "If you run the downloaded file, it starts the installation process." }, { "code": null, "e": 5271, "s": 5168, "text": "Proceed with the installation by providing the required details and finally complete the installation." }, { "code": null, "e": 5466, "s": 5271, "text": "The Plugins tab of IntelliJ displays all the available plugins. By default, Kotlin plugin is activated, in any case if it is not activated. Open the plugin tab, search for Kotlin and install it." }, { "code": null, "e": 5516, "s": 5466, "text": "To create first application, click on NewProject." }, { "code": null, "e": 5550, "s": 5516, "text": "Select Kotlin/JVM and click Next." }, { "code": null, "e": 5600, "s": 5550, "text": "Name the project and select the desired location." }, { "code": null, "e": 5686, "s": 5600, "text": "Now, create a new Kotlin file under the source(src) folder and let’s name it as Test." }, { "code": null, "e": 5784, "s": 5686, "text": "You can create a sample function as shown below. You can run this by pressing Ctrl + Shift + F10." }, { "code": null, "e": 5959, "s": 5784, "text": "You can also execute Kotlin programs in eclipse to do so, you need to have “Eclipse IDE for Java developers” installed in your system. To do so, follow the steps given below." }, { "code": null, "e": 6058, "s": 5959, "text": "Download the latest version of eclipse installer from the page: https://www.eclipse.org/downloads/" }, { "code": null, "e": 6132, "s": 6058, "text": "Run the downloaded file and click on the Eclipse IDE for Java developers." }, { "code": null, "e": 6188, "s": 6132, "text": "Select the installation directory and click on install." }, { "code": null, "e": 6246, "s": 6188, "text": "Open eclipse in the Help menu select Eclipse Marketplace." }, { "code": null, "e": 6333, "s": 6246, "text": "Search for Kotlin and check all the matches and when you find Kotlin click on Install." }, { "code": null, "e": 6421, "s": 6333, "text": "Once you have installed Kotlin plugin in your eclipse to create your first application." }, { "code": null, "e": 6456, "s": 6421, "text": "In the File menu click on Project." }, { "code": null, "e": 6590, "s": 6456, "text": "This will take you to Select a wizard. Under Kotlin (dropdown menu), click on select “Kotlin Project” and click on the “Next” button." }, { "code": null, "e": 6658, "s": 6590, "text": "Then, enter the desired name for the application and click on Next." }, { "code": null, "e": 6727, "s": 6658, "text": "Right click on the src folder of the created project click on other." }, { "code": null, "e": 6802, "s": 6727, "text": "Select the Kotlin File wizard click on Next and name the file as Hello.kt." }, { "code": null, "e": 6914, "s": 6802, "text": "Your development environment is ready now. Go ahead and add the following piece of code in the “Hello.kt” file." }, { "code": null, "e": 6968, "s": 6914, "text": "fun main(args: Array) {\n println(\"Hello, World!\")\n}" } ]
PyCairo – Drawing Bezier curve
23 Jan, 2022 In this article we will learn how we can draw a simple bezier curve using PyCairo in python. A Bezier curve is a versatile mathematical curve that can be used to create a wide variety of different shapes in vector graphics. PyCairo : Pycairo is a Python module providing bindings for the cairo graphics library.This library is used for creating SVG i.e vector files in python. The easiest and quickest way to open an SVG file to view it (read only) is with a modern web browser like Chrome, Firefox, Edge, or Internet Explorer—nearly all of them should provide some sort of rendering support for the SVG format. SVG file is a graphics file that uses a two-dimensional vector graphic format created by the World Wide Web Consortium (W3C). It describes images using a text format that is based on XML. SVG files are developed as a standard format for displaying vector graphics on the web. Steps of Implementation : Import the Pycairo module.Create a SVG surface object and add context to it.Creating curve using curve_to ( )Setting context color and width Import the Pycairo module. Create a SVG surface object and add context to it. Creating curve using curve_to ( ) Setting context color and width Below is the Implementation : Python3 # importing pycairoimport cairo # creating a SVG surface# here geek95 is file name & 700, 700 is dimensionwith cairo.SVGSurface("geek95.svg", 700, 700) as surface: # creating a cairo context object for SVG surface # using Context method context = cairo.Context(surface) # move the context to x,y position context.move_to(50, 200) # Drawing Curve context.curve_to(150, 75, 225, 50, 350, 150) # setting color of the context context.set_source_rgb(1, 0, 0) # setting width of the context context.set_line_width(4) # stroke out the color and width property context.stroke() # printing message when file is savedprint("File Saved") Output : saurabh1990aror Python-PyCairo Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jan, 2022" }, { "code": null, "e": 253, "s": 28, "text": "In this article we will learn how we can draw a simple bezier curve using PyCairo in python. A Bezier curve is a versatile mathematical curve that can be used to create a wide variety of different shapes in vector graphics. " }, { "code": null, "e": 643, "s": 253, "text": "PyCairo : Pycairo is a Python module providing bindings for the cairo graphics library.This library is used for creating SVG i.e vector files in python. The easiest and quickest way to open an SVG file to view it (read only) is with a modern web browser like Chrome, Firefox, Edge, or Internet Explorer—nearly all of them should provide some sort of rendering support for the SVG format. " }, { "code": null, "e": 919, "s": 643, "text": "SVG file is a graphics file that uses a two-dimensional vector graphic format created by the World Wide Web Consortium (W3C). It describes images using a text format that is based on XML. SVG files are developed as a standard format for displaying vector graphics on the web." }, { "code": null, "e": 945, "s": 919, "text": "Steps of Implementation :" }, { "code": null, "e": 1086, "s": 945, "text": "Import the Pycairo module.Create a SVG surface object and add context to it.Creating curve using curve_to ( )Setting context color and width" }, { "code": null, "e": 1113, "s": 1086, "text": "Import the Pycairo module." }, { "code": null, "e": 1164, "s": 1113, "text": "Create a SVG surface object and add context to it." }, { "code": null, "e": 1198, "s": 1164, "text": "Creating curve using curve_to ( )" }, { "code": null, "e": 1230, "s": 1198, "text": "Setting context color and width" }, { "code": null, "e": 1260, "s": 1230, "text": "Below is the Implementation :" }, { "code": null, "e": 1268, "s": 1260, "text": "Python3" }, { "code": "# importing pycairoimport cairo # creating a SVG surface# here geek95 is file name & 700, 700 is dimensionwith cairo.SVGSurface(\"geek95.svg\", 700, 700) as surface: # creating a cairo context object for SVG surface # using Context method context = cairo.Context(surface) # move the context to x,y position context.move_to(50, 200) # Drawing Curve context.curve_to(150, 75, 225, 50, 350, 150) # setting color of the context context.set_source_rgb(1, 0, 0) # setting width of the context context.set_line_width(4) # stroke out the color and width property context.stroke() # printing message when file is savedprint(\"File Saved\")", "e": 1936, "s": 1268, "text": null }, { "code": null, "e": 1945, "s": 1936, "text": "Output :" }, { "code": null, "e": 1961, "s": 1945, "text": "saurabh1990aror" }, { "code": null, "e": 1976, "s": 1961, "text": "Python-PyCairo" }, { "code": null, "e": 1983, "s": 1976, "text": "Python" }, { "code": null, "e": 2081, "s": 1983, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2099, "s": 2081, "text": "Python Dictionary" }, { "code": null, "e": 2141, "s": 2099, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2163, "s": 2141, "text": "Enumerate() in Python" }, { "code": null, "e": 2198, "s": 2163, "text": "Read a file line by line in Python" }, { "code": null, "e": 2224, "s": 2198, "text": "Python String | replace()" }, { "code": null, "e": 2256, "s": 2224, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2285, "s": 2256, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2312, "s": 2285, "text": "Python Classes and Objects" }, { "code": null, "e": 2342, "s": 2312, "text": "Iterate over a list in Python" } ]
How to pass an array by reference in C++
If we pass the address of an array while calling a function, then this is called function call by reference. The function declaration should have a pointer as a parameter to receive the passed address, when we pass an address as an argument. Live Demo #include <iostream> using namespace std; void show( int *num) { cout<<*num; } int main() { int a[] = {3,2,1,6,7,4,5,0,10,8}; for (int i=0; i<10; i++) { show (&a[i]); } return 0; } 32167450108
[ { "code": null, "e": 1429, "s": 1187, "text": "If we pass the address of an array while calling a function, then this is called function call by reference. The function declaration should have a pointer as a parameter to receive the passed address, when we pass an address as an argument." }, { "code": null, "e": 1440, "s": 1429, "text": " Live Demo" }, { "code": null, "e": 1641, "s": 1440, "text": "#include <iostream>\nusing namespace std;\nvoid show( int *num) {\n cout<<*num;\n}\nint main() {\n int a[] = {3,2,1,6,7,4,5,0,10,8};\n for (int i=0; i<10; i++) {\n show (&a[i]);\n }\n return 0;\n}" }, { "code": null, "e": 1653, "s": 1641, "text": "32167450108" } ]
Printing triangle star pattern using a single loop
29 Apr, 2021 Given a number N, the task is to print the star pattern in single loop. Examples: Input: N = 9 Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Input: N = 5 Output: * * * * * * * * * * * * * * * Please Refer article for printing the pattern in two loops as:Triangle pattern in Java Approach: The idea is to break a column into three parts and solve each part independently of the others. Case 1: Spaces before the first *, which takes care of printing white spaces. Case 2: Starting of the first * and the ending of the last * in the row, which takes care of printing alternating white spaces and *. Case 3: The ending star essentially tells to print a new line or end the program if we have already finished n rows.Refer to the image below Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of printing// star pattern in single loop #include <iostream>using namespace std; // Function to print the star// pattern in single loopvoid pattern(int n){ int i, k, flag = 1; // Loop to handle number of rows and // columns in this case for (i = 1, k = 0; i <= 2 * n - 1; i++) { // Handles case 1 if (i < n - k) cout << " "; // Handles case 2 else { if (flag) cout << "*"; else cout << " "; flag = 1 - flag; } // Condition to check case 3 if (i == n + k) { k++; cout << endl; // Since for nth row we have // 2 * n- 1 columns if (i == 2 * n - 1) break; // Reinitializing i as 0, // for next row i = 0; flag = 1; } }} // Driver Codeint main(){ int n = 6; // Function Call pattern(n); return 0;} // Java implementation of printing// star pattern in single loopimport java.util.*; class GFG{ // Function to print the star// pattern in single loopstatic void pattern(int n){ int i, k, flag = 1; // Loop to handle number of rows and // columns in this case for(i = 1, k = 0; i <= 2 * n - 1; i++) { // Handles case 1 if (i < n - k) System.out.print(" "); // Handles case 2 else { if (flag == 1) System.out.print("*"); else System.out.print(" "); flag = 1 - flag; } // Condition to check case 3 if (i == n + k) { k++; System.out.println(); // Since for nth row we have // 2 * n- 1 columns if (i == 2 * n - 1) break; // Reinitializing i as 0, // for next row i = 0; flag = 1; } }} // Driver codepublic static void main(String[] args){ int n = 6; // Function Call pattern(n);}} // This code is contributed by offbeat # Python3 implementation of# printing star pattern in# single loop # Function to print the star# pattern in single loopdef pattern(n): flag = 1 # Loop to handle number # of rows and columns # in this case i = 1 k = 0 while i <= 2 * n - 1: # Handles case 1 if (i < n - k): print(" ", end = "") # Handles case 2 else: if (flag): print("*", end = "") else: print(" ", end = "") flag = 1 - flag # Condition to check case 3 if (i == n + k): k += 1 print() # Since for nth row we # have 2 * n- 1 columns if (i == 2 * n - 1): break # Reinitializing i as 0, # for next row i = 0 flag = 1 i += 1 # Driver Codeif __name__ == "__main__": n = 6 # Function Call pattern(n) # This code is contributed by Chitranayal // C# implementation of printing// star pattern in single loopusing System; class GFG{ // Function to print the star// pattern in single loopstatic void pattern(int n){ int i, k, flag = 1; // Loop to handle number of rows and // columns in this case for(i = 1, k = 0; i <= 2 * n - 1; i++) { // Handles case 1 if (i < n - k) Console.Write(" "); // Handles case 2 else { if (flag == 1) Console.Write("*"); else Console.Write(" "); flag = 1 - flag; } // Condition to check case 3 if (i == n + k) { k++; Console.WriteLine(); // Since for nth row we have // 2 * n- 1 columns if (i == 2 * n - 1) break; // Reinitializing i as 0, // for next row i = 0; flag = 1; } }} // Driver codepublic static void Main(){ int n = 6; // Function call pattern(n);}} // This code is contributed by sanjoy_62 <script> // JavaScript implementation of printing // star pattern in single loop // Function to print the star // pattern in single loop function pattern(n) { var i, k, flag = 1; // Loop to handle number of rows and // columns in this case for (i = 1, k = 0; i <= 2 * n - 1; i++) { // Handles case 1 if (i < n - k) document.write(" "); // Handles case 2 else { if (flag) document.write("*"); else document.write(" "); flag = 1 - flag; } // Condition to check case 3 if (i == n + k) { k++; document.write("<br>"); // Since for nth row we have // 2 * n- 1 columns if (i == 2 * n - 1) break; // Reinitializing i as 0, // for next row i = 0; flag = 1; } } } // Driver Code var n = 6; // Function Call pattern(n); </script> * * * * * * * * * * * * * * * * * * * * * offbeat sanjoy_62 ukasp rdtank loop pattern-printing School Programming pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction To PYTHON Interfaces in Java C++ Classes and Objects C++ Data Types Operator Overloading in C++ Polymorphism in C++ Types of Operating Systems Constructors in C++ Constructors in Java Exceptions in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Apr, 2021" }, { "code": null, "e": 124, "s": 52, "text": "Given a number N, the task is to print the star pattern in single loop." }, { "code": null, "e": 135, "s": 124, "text": "Examples: " }, { "code": null, "e": 401, "s": 135, "text": "Input: N = 9\nOutput: \n * \n * * \n * * * \n * * * * \n * * * * * \n * * * * * * \n * * * * * * * \n * * * * * * * * \n * * * * * * * * * \n\nInput: N = 5\nOutput:\n * \n * * \n * * * \n * * * * \n * * * * * " }, { "code": null, "e": 488, "s": 401, "text": "Please Refer article for printing the pattern in two loops as:Triangle pattern in Java" }, { "code": null, "e": 594, "s": 488, "text": "Approach: The idea is to break a column into three parts and solve each part independently of the others." }, { "code": null, "e": 672, "s": 594, "text": "Case 1: Spaces before the first *, which takes care of printing white spaces." }, { "code": null, "e": 806, "s": 672, "text": "Case 2: Starting of the first * and the ending of the last * in the row, which takes care of printing alternating white spaces and *." }, { "code": null, "e": 947, "s": 806, "text": "Case 3: The ending star essentially tells to print a new line or end the program if we have already finished n rows.Refer to the image below" }, { "code": null, "e": 998, "s": 947, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1002, "s": 998, "text": "C++" }, { "code": null, "e": 1007, "s": 1002, "text": "Java" }, { "code": null, "e": 1015, "s": 1007, "text": "Python3" }, { "code": null, "e": 1018, "s": 1015, "text": "C#" }, { "code": null, "e": 1029, "s": 1018, "text": "Javascript" }, { "code": "// C++ implementation of printing// star pattern in single loop #include <iostream>using namespace std; // Function to print the star// pattern in single loopvoid pattern(int n){ int i, k, flag = 1; // Loop to handle number of rows and // columns in this case for (i = 1, k = 0; i <= 2 * n - 1; i++) { // Handles case 1 if (i < n - k) cout << \" \"; // Handles case 2 else { if (flag) cout << \"*\"; else cout << \" \"; flag = 1 - flag; } // Condition to check case 3 if (i == n + k) { k++; cout << endl; // Since for nth row we have // 2 * n- 1 columns if (i == 2 * n - 1) break; // Reinitializing i as 0, // for next row i = 0; flag = 1; } }} // Driver Codeint main(){ int n = 6; // Function Call pattern(n); return 0;}", "e": 2027, "s": 1029, "text": null }, { "code": "// Java implementation of printing// star pattern in single loopimport java.util.*; class GFG{ // Function to print the star// pattern in single loopstatic void pattern(int n){ int i, k, flag = 1; // Loop to handle number of rows and // columns in this case for(i = 1, k = 0; i <= 2 * n - 1; i++) { // Handles case 1 if (i < n - k) System.out.print(\" \"); // Handles case 2 else { if (flag == 1) System.out.print(\"*\"); else System.out.print(\" \"); flag = 1 - flag; } // Condition to check case 3 if (i == n + k) { k++; System.out.println(); // Since for nth row we have // 2 * n- 1 columns if (i == 2 * n - 1) break; // Reinitializing i as 0, // for next row i = 0; flag = 1; } }} // Driver codepublic static void main(String[] args){ int n = 6; // Function Call pattern(n);}} // This code is contributed by offbeat", "e": 3162, "s": 2027, "text": null }, { "code": "# Python3 implementation of# printing star pattern in# single loop # Function to print the star# pattern in single loopdef pattern(n): flag = 1 # Loop to handle number # of rows and columns # in this case i = 1 k = 0 while i <= 2 * n - 1: # Handles case 1 if (i < n - k): print(\" \", end = \"\") # Handles case 2 else: if (flag): print(\"*\", end = \"\") else: print(\" \", end = \"\") flag = 1 - flag # Condition to check case 3 if (i == n + k): k += 1 print() # Since for nth row we # have 2 * n- 1 columns if (i == 2 * n - 1): break # Reinitializing i as 0, # for next row i = 0 flag = 1 i += 1 # Driver Codeif __name__ == \"__main__\": n = 6 # Function Call pattern(n) # This code is contributed by Chitranayal", "e": 4148, "s": 3162, "text": null }, { "code": "// C# implementation of printing// star pattern in single loopusing System; class GFG{ // Function to print the star// pattern in single loopstatic void pattern(int n){ int i, k, flag = 1; // Loop to handle number of rows and // columns in this case for(i = 1, k = 0; i <= 2 * n - 1; i++) { // Handles case 1 if (i < n - k) Console.Write(\" \"); // Handles case 2 else { if (flag == 1) Console.Write(\"*\"); else Console.Write(\" \"); flag = 1 - flag; } // Condition to check case 3 if (i == n + k) { k++; Console.WriteLine(); // Since for nth row we have // 2 * n- 1 columns if (i == 2 * n - 1) break; // Reinitializing i as 0, // for next row i = 0; flag = 1; } }} // Driver codepublic static void Main(){ int n = 6; // Function call pattern(n);}} // This code is contributed by sanjoy_62", "e": 5254, "s": 4148, "text": null }, { "code": "<script> // JavaScript implementation of printing // star pattern in single loop // Function to print the star // pattern in single loop function pattern(n) { var i, k, flag = 1; // Loop to handle number of rows and // columns in this case for (i = 1, k = 0; i <= 2 * n - 1; i++) { // Handles case 1 if (i < n - k) document.write(\" \"); // Handles case 2 else { if (flag) document.write(\"*\"); else document.write(\" \"); flag = 1 - flag; } // Condition to check case 3 if (i == n + k) { k++; document.write(\"<br>\"); // Since for nth row we have // 2 * n- 1 columns if (i == 2 * n - 1) break; // Reinitializing i as 0, // for next row i = 0; flag = 1; } } } // Driver Code var n = 6; // Function Call pattern(n); </script>", "e": 6341, "s": 5254, "text": null }, { "code": null, "e": 6398, "s": 6341, "text": " *\n * *\n * * *\n * * * *\n * * * * *\n* * * * * *" }, { "code": null, "e": 6406, "s": 6398, "text": "offbeat" }, { "code": null, "e": 6416, "s": 6406, "text": "sanjoy_62" }, { "code": null, "e": 6422, "s": 6416, "text": "ukasp" }, { "code": null, "e": 6429, "s": 6422, "text": "rdtank" }, { "code": null, "e": 6434, "s": 6429, "text": "loop" }, { "code": null, "e": 6451, "s": 6434, "text": "pattern-printing" }, { "code": null, "e": 6470, "s": 6451, "text": "School Programming" }, { "code": null, "e": 6487, "s": 6470, "text": "pattern-printing" }, { "code": null, "e": 6585, "s": 6487, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6608, "s": 6585, "text": "Introduction To PYTHON" }, { "code": null, "e": 6627, "s": 6608, "text": "Interfaces in Java" }, { "code": null, "e": 6651, "s": 6627, "text": "C++ Classes and Objects" }, { "code": null, "e": 6666, "s": 6651, "text": "C++ Data Types" }, { "code": null, "e": 6694, "s": 6666, "text": "Operator Overloading in C++" }, { "code": null, "e": 6714, "s": 6694, "text": "Polymorphism in C++" }, { "code": null, "e": 6741, "s": 6714, "text": "Types of Operating Systems" }, { "code": null, "e": 6761, "s": 6741, "text": "Constructors in C++" }, { "code": null, "e": 6782, "s": 6761, "text": "Constructors in Java" } ]
How to Calculate the determinant of a matrix using NumPy?
05 Sep, 2020 A special number that can be calculated from a square matrix is known as the Determinant of a square matrix. The Numpy provides us the feature to calculate the determinant of a square matrix using numpy.linalg.det() function. Syntax: numpy.linalg.det(array) Example 1: Calculating Determinant of a 2X2 Numpy matrix using numpy.linalg.det() function Python3 # importing Numpy packageimport numpy as np # creating a 2X2 Numpy matrixn_array = np.array([[50, 29], [30, 44]]) # Displaying the Matrixprint("Numpy Matrix is:")print(n_array) # calculating the determinant of matrixdet = np.linalg.det(n_array) print("\nDeterminant of given 2X2 matrix:")print(int(det)) Output: In the above example, we calculate the Determinant of the 2X2 square matrix. Example 2: Calculating Determinant of a 3X3 Numpy matrix using numpy.linalg.det() function Python3 # importing Numpy packageimport numpy as np # creating a 3X3 Numpy matrixn_array = np.array([[55, 25, 15], [30, 44, 2], [11, 45, 77]]) # Displaying the Matrixprint("Numpy Matrix is:")print(n_array) # calculating the determinant of matrixdet = np.linalg.det(n_array) print("\nDeterminant of given 3X3 square matrix:")print(int(det)) Output: In the above example, we calculate the Determinant of the 3X3 square matrix. Example 3: Calculating Determinant of a 5X5 Numpy matrix using numpy.linalg.det() function Python3 # importing Numpy packageimport numpy as np # creating a 5X5 Numpy matrixn_array = np.array([[5, 2, 1, 4, 6], [9, 4, 2, 5, 2], [11, 5, 7, 3, 9], [5, 6, 6, 7, 2], [7, 5, 9, 3, 3]]) # Displaying the Matrixprint("Numpy Matrix is:")print(n_array) # calculating the determinant of matrixdet = np.linalg.det(n_array) print("\nDeterminant of given 5X5 square matrix:")print(int(det)) Output: In the above example, we calculate the Determinant of the 5X5 square matrix. Python numpy-Matrix Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 53, "s": 25, "text": "\n05 Sep, 2020" }, { "code": null, "e": 279, "s": 53, "text": "A special number that can be calculated from a square matrix is known as the Determinant of a square matrix. The Numpy provides us the feature to calculate the determinant of a square matrix using numpy.linalg.det() function." }, { "code": null, "e": 287, "s": 279, "text": "Syntax:" }, { "code": null, "e": 312, "s": 287, "text": "numpy.linalg.det(array)\n" }, { "code": null, "e": 403, "s": 312, "text": "Example 1: Calculating Determinant of a 2X2 Numpy matrix using numpy.linalg.det() function" }, { "code": null, "e": 411, "s": 403, "text": "Python3" }, { "code": "# importing Numpy packageimport numpy as np # creating a 2X2 Numpy matrixn_array = np.array([[50, 29], [30, 44]]) # Displaying the Matrixprint(\"Numpy Matrix is:\")print(n_array) # calculating the determinant of matrixdet = np.linalg.det(n_array) print(\"\\nDeterminant of given 2X2 matrix:\")print(int(det))", "e": 719, "s": 411, "text": null }, { "code": null, "e": 727, "s": 719, "text": "Output:" }, { "code": null, "e": 804, "s": 727, "text": "In the above example, we calculate the Determinant of the 2X2 square matrix." }, { "code": null, "e": 895, "s": 804, "text": "Example 2: Calculating Determinant of a 3X3 Numpy matrix using numpy.linalg.det() function" }, { "code": null, "e": 903, "s": 895, "text": "Python3" }, { "code": "# importing Numpy packageimport numpy as np # creating a 3X3 Numpy matrixn_array = np.array([[55, 25, 15], [30, 44, 2], [11, 45, 77]]) # Displaying the Matrixprint(\"Numpy Matrix is:\")print(n_array) # calculating the determinant of matrixdet = np.linalg.det(n_array) print(\"\\nDeterminant of given 3X3 square matrix:\")print(int(det))", "e": 1277, "s": 903, "text": null }, { "code": null, "e": 1285, "s": 1277, "text": "Output:" }, { "code": null, "e": 1362, "s": 1285, "text": "In the above example, we calculate the Determinant of the 3X3 square matrix." }, { "code": null, "e": 1453, "s": 1362, "text": "Example 3: Calculating Determinant of a 5X5 Numpy matrix using numpy.linalg.det() function" }, { "code": null, "e": 1461, "s": 1453, "text": "Python3" }, { "code": "# importing Numpy packageimport numpy as np # creating a 5X5 Numpy matrixn_array = np.array([[5, 2, 1, 4, 6], [9, 4, 2, 5, 2], [11, 5, 7, 3, 9], [5, 6, 6, 7, 2], [7, 5, 9, 3, 3]]) # Displaying the Matrixprint(\"Numpy Matrix is:\")print(n_array) # calculating the determinant of matrixdet = np.linalg.det(n_array) print(\"\\nDeterminant of given 5X5 square matrix:\")print(int(det))", "e": 1918, "s": 1461, "text": null }, { "code": null, "e": 1926, "s": 1918, "text": "Output:" }, { "code": null, "e": 2003, "s": 1926, "text": "In the above example, we calculate the Determinant of the 5X5 square matrix." }, { "code": null, "e": 2032, "s": 2003, "text": "Python numpy-Matrix Function" }, { "code": null, "e": 2045, "s": 2032, "text": "Python-numpy" }, { "code": null, "e": 2052, "s": 2045, "text": "Python" }, { "code": null, "e": 2150, "s": 2052, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2182, "s": 2150, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2209, "s": 2182, "text": "Python Classes and Objects" }, { "code": null, "e": 2230, "s": 2209, "text": "Python OOPs Concepts" }, { "code": null, "e": 2253, "s": 2230, "text": "Introduction To PYTHON" }, { "code": null, "e": 2284, "s": 2253, "text": "Python | os.path.join() method" }, { "code": null, "e": 2340, "s": 2284, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2382, "s": 2340, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2424, "s": 2382, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2463, "s": 2424, "text": "Python | Get unique values from a list" } ]
AbstractList in Java with Examples - GeeksforGeeks
11 Nov, 2020 The AbstractList class in Java is a part of the Java Collection Framework and implements the Collection interface and the AbstractCollection class. This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a Random Access data store (such as an array). For sequential access data (such as a linked list), AbstractSequentialList should be used in preference to this class. To implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement the get(int) and the size() methods. To implement a modifiable list, for which one additionally override the set​(int index, E element) method (which otherwise throws an UnsupportedOperationException). If the list is variable-size, for which one should override the add(int, E) and remove(int) methods. Class Hierarchy: Declaration: public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> where E is the type of elements maintained by this collection. Constructor: protected AbstractList() – The default constructor, but being protected, it doesn’t allow to create an AbstractList object. AbstractList<E> al = new ArrayList<E>(); Example 1: AbstractList is an abstract class, so it should be assigned an instance of its subclasses such as ArrayList, LinkedList, or Vector. Java // Java code to illustrate AbstractListimport java.util.*; public class AbstractListDemo { public static void main(String args[]) { // Creating an empty AbstractList AbstractList<String> list = new ArrayList<String>(); // Use add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // Displaying the AbstractList System.out.println("AbstractList:" + list); }} Output: AbstractList:[Geeks, for, Geeks, 10, 20] Example 2: Java // Java code to illustrate // methods of AbstractCollection import java.util.*; public class AbstractListDemo { public static void main(String args[]) { // Creating an empty AbstractList AbstractList<String> list = new LinkedList<String>(); // Using add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // Output the list System.out.println("AbstractList: " + list); // Remove the head using remove() list.remove(3); // Print the final list System.out.println("Final AbstractList: " + list); // getting the index of last occurence // using lastIndexOf() method int lastindex = list.lastIndexOf("A"); // printing the Index System.out.println("Last index of A : " + lastindex); } } Output: AbstractList: [Geeks, for, Geeks, 10, 20] Final AbstractList: [Geeks, for, Geeks, 20] Last index of A : -1 METHOD DESCRIPTION addAll​(int index, Collection<? extends E> c) METHOD DESCRIPTION METHOD DESCRIPTION Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array. METHOD DESCRIPTION Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s iterator (optional operation). Returns an array containing all of the elements in this list in proper sequence (from first to last element) ; the runtime type of the returned array is that of the specified array. Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/AbstractList.html Ganeshchowdharysadanala Java - util package Java-AbstractList Java-Collections Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Initialize an ArrayList in Java Reverse a string in Java Interfaces in Java HashMap in Java with Examples Object Oriented Programming (OOPs) Concept in Java ArrayList in Java
[ { "code": null, "e": 23714, "s": 23686, "text": "\n11 Nov, 2020" }, { "code": null, "e": 24166, "s": 23714, "text": "The AbstractList class in Java is a part of the Java Collection Framework and implements the Collection interface and the AbstractCollection class. This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a Random Access data store (such as an array). For sequential access data (such as a linked list), AbstractSequentialList should be used in preference to this class." }, { "code": null, "e": 24577, "s": 24166, "text": "To implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement the get(int) and the size() methods. To implement a modifiable list, for which one additionally override the set​(int index, E element) method (which otherwise throws an UnsupportedOperationException). If the list is variable-size, for which one should override the add(int, E) and remove(int) methods." }, { "code": null, "e": 24595, "s": 24577, "text": "Class Hierarchy: " }, { "code": null, "e": 24609, "s": 24595, "text": "Declaration: " }, { "code": null, "e": 24761, "s": 24609, "text": "public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>\n\nwhere E is the type of elements maintained by this collection.\n" }, { "code": null, "e": 24898, "s": 24761, "text": "Constructor: protected AbstractList() – The default constructor, but being protected, it doesn’t allow to create an AbstractList object." }, { "code": null, "e": 24939, "s": 24898, "text": "AbstractList<E> al = new ArrayList<E>();" }, { "code": null, "e": 25083, "s": 24939, "text": "Example 1: AbstractList is an abstract class, so it should be assigned an instance of its subclasses such as ArrayList, LinkedList, or Vector. " }, { "code": null, "e": 25088, "s": 25083, "text": "Java" }, { "code": "// Java code to illustrate AbstractListimport java.util.*; public class AbstractListDemo { public static void main(String args[]) { // Creating an empty AbstractList AbstractList<String> list = new ArrayList<String>(); // Use add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Displaying the AbstractList System.out.println(\"AbstractList:\" + list); }}", "e": 25606, "s": 25088, "text": null }, { "code": null, "e": 25616, "s": 25606, "text": " Output:" }, { "code": null, "e": 25657, "s": 25616, "text": "AbstractList:[Geeks, for, Geeks, 10, 20]" }, { "code": null, "e": 25668, "s": 25657, "text": "Example 2:" }, { "code": null, "e": 25673, "s": 25668, "text": "Java" }, { "code": "// Java code to illustrate // methods of AbstractCollection import java.util.*; public class AbstractListDemo { public static void main(String args[]) { // Creating an empty AbstractList AbstractList<String> list = new LinkedList<String>(); // Using add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Output the list System.out.println(\"AbstractList: \" + list); // Remove the head using remove() list.remove(3); // Print the final list System.out.println(\"Final AbstractList: \" + list); // getting the index of last occurence // using lastIndexOf() method int lastindex = list.lastIndexOf(\"A\"); // printing the Index System.out.println(\"Last index of A : \" + lastindex); } } ", "e": 26646, "s": 25673, "text": null }, { "code": null, "e": 26654, "s": 26646, "text": "Output:" }, { "code": null, "e": 26761, "s": 26654, "text": "AbstractList: [Geeks, for, Geeks, 10, 20]\nFinal AbstractList: [Geeks, for, Geeks, 20]\nLast index of A : -1" }, { "code": null, "e": 26768, "s": 26761, "text": "METHOD" }, { "code": null, "e": 26780, "s": 26768, "text": "DESCRIPTION" }, { "code": null, "e": 26800, "s": 26780, "text": "addAll​(int index, " }, { "code": null, "e": 26827, "s": 26800, "text": "Collection<? extends E> c)" }, { "code": null, "e": 26834, "s": 26827, "text": "METHOD" }, { "code": null, "e": 26846, "s": 26834, "text": "DESCRIPTION" }, { "code": null, "e": 26853, "s": 26846, "text": "METHOD" }, { "code": null, "e": 26865, "s": 26853, "text": "DESCRIPTION" }, { "code": null, "e": 26943, "s": 26865, "text": "Returns an array containing all of the elements in this collection, using the" }, { "code": null, "e": 27004, "s": 26943, "text": " provided generator function to allocate the returned array." }, { "code": null, "e": 27011, "s": 27004, "text": "METHOD" }, { "code": null, "e": 27023, "s": 27011, "text": "DESCRIPTION" }, { "code": null, "e": 27122, "s": 27023, "text": "Appends all of the elements in the specified collection to the end of this list, in the order that" }, { "code": null, "e": 27202, "s": 27122, "text": " they are returned by the specified collection’s iterator (optional operation)." }, { "code": null, "e": 27311, "s": 27202, "text": "Returns an array containing all of the elements in this list in proper sequence (from first to last element)" }, { "code": null, "e": 27384, "s": 27311, "text": "; the runtime type of the returned array is that of the specified array." }, { "code": null, "e": 27484, "s": 27384, "text": "Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/AbstractList.html" }, { "code": null, "e": 27508, "s": 27484, "text": "Ganeshchowdharysadanala" }, { "code": null, "e": 27528, "s": 27508, "text": "Java - util package" }, { "code": null, "e": 27546, "s": 27528, "text": "Java-AbstractList" }, { "code": null, "e": 27563, "s": 27546, "text": "Java-Collections" }, { "code": null, "e": 27568, "s": 27563, "text": "Java" }, { "code": null, "e": 27573, "s": 27568, "text": "Java" }, { "code": null, "e": 27590, "s": 27573, "text": "Java-Collections" }, { "code": null, "e": 27688, "s": 27590, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27697, "s": 27688, "text": "Comments" }, { "code": null, "e": 27710, "s": 27697, "text": "Old Comments" }, { "code": null, "e": 27725, "s": 27710, "text": "Arrays in Java" }, { "code": null, "e": 27769, "s": 27725, "text": "Split() String method in Java with examples" }, { "code": null, "e": 27791, "s": 27769, "text": "For-each loop in Java" }, { "code": null, "e": 27827, "s": 27791, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 27859, "s": 27827, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27884, "s": 27859, "text": "Reverse a string in Java" }, { "code": null, "e": 27903, "s": 27884, "text": "Interfaces in Java" }, { "code": null, "e": 27933, "s": 27903, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27984, "s": 27933, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Difference between Inverted Index and Forward Index
Inverted Index and Forward Index are data structures used to search text in a document or set of documents. Inverted Index stores the words as index and document name(s) as mapped reference(s). Forward Index stores the document name as index and word(s) as mapped reference(s). The following are some of the important differences between the Inverted Index and Forward Index. Scan the document, prepare a list of unique words. Scan the document, prepare a list of unique words. Prepare a list of indexes of all unique words and map them to document search. Prepare a list of indexes of all unique words and map them to document search. Repeat the above steps for all the documents. Repeat the above steps for all the documents. Scan the document, prepare list of unique words. Scan the document, prepare list of unique words. Map all the words to document as an index. Map all the words to document as an index. Repeat the above steps for all the documents. Repeat the above steps for all the documents. Word Documents ------------------------- Welcome doc1 Hello doc1, doc3 Hi doc2 ------------------------- Word Documents ------------------------- doc1 Welcome, Hello doc2 Hi doc3 Hello -------------------------
[ { "code": null, "e": 1170, "s": 1062, "text": "Inverted Index and Forward Index are data structures used to search text in a document or set of documents." }, { "code": null, "e": 1256, "s": 1170, "text": "Inverted Index stores the words as index and document name(s) as mapped reference(s)." }, { "code": null, "e": 1340, "s": 1256, "text": "Forward Index stores the document name as index and word(s) as mapped reference(s)." }, { "code": null, "e": 1438, "s": 1340, "text": "The following are some of the important differences between the Inverted Index and Forward Index." }, { "code": null, "e": 1489, "s": 1438, "text": "Scan the document, prepare a list of unique words." }, { "code": null, "e": 1540, "s": 1489, "text": "Scan the document, prepare a list of unique words." }, { "code": null, "e": 1619, "s": 1540, "text": "Prepare a list of indexes of all unique words and map them to document search." }, { "code": null, "e": 1698, "s": 1619, "text": "Prepare a list of indexes of all unique words and map them to document search." }, { "code": null, "e": 1744, "s": 1698, "text": "Repeat the above steps for all the documents." }, { "code": null, "e": 1790, "s": 1744, "text": "Repeat the above steps for all the documents." }, { "code": null, "e": 1839, "s": 1790, "text": "Scan the document, prepare list of unique words." }, { "code": null, "e": 1888, "s": 1839, "text": "Scan the document, prepare list of unique words." }, { "code": null, "e": 1931, "s": 1888, "text": "Map all the words to document as an index." }, { "code": null, "e": 1974, "s": 1931, "text": "Map all the words to document as an index." }, { "code": null, "e": 2020, "s": 1974, "text": "Repeat the above steps for all the documents." }, { "code": null, "e": 2066, "s": 2020, "text": "Repeat the above steps for all the documents." }, { "code": null, "e": 2171, "s": 2066, "text": "Word Documents\n-------------------------\nWelcome doc1\nHello doc1, doc3\nHi doc2\n-------------------------" }, { "code": null, "e": 2277, "s": 2171, "text": "Word Documents\n-------------------------\ndoc1 Welcome, Hello\ndoc2 Hi\ndoc3 Hello\n-------------------------" } ]
Face detection using Face-Api.js and Flask | by Karthikraj Naidu | Towards Data Science
There are numerous face detection systems available online for Python like Dlib, OpenCV, and other Object Detection Systems by Deep Learning. We may have already used OpenCV to use a frame for capturing video from webcam and doing facial landmark detection using Dlib, MTCNN, etc. But I always got fed up that in a project I wasn’t able to add it in the UI or there are too many frame skips due to the load on CPU. Most of the people use Flask as the goto framework for deploying their ML/DL model and beauty of creating UI from HTML and managing backend from python server works like a charm. But whenever you try to include webcam face detection for your web app you get stuck with a dialog box from Opencv imshow() and bust up the UX. The development of TF.js has empowered us to develop complex models on the browser itself. But python freaks like us with minimal knowledge on Node.js and other web development terminologies had to know on how to use these tools in our Flask playground In this article, we would be creating a Flask web app with face recognition integrating into the browser Advantages Embed the video stream of data and inference into browser content Less Utilization of Resources and improved FPS No need to shift projects from Python to Node.js As I was looking by a solution for face detection for Flask I came across a JavaScript API for face detection and face recognition in the browser made by Vincent Mühler who has done awesome work on creating APIs for TF.js implementation of Face detection and Recognization. These API can be used to extract data from the Webcam video and also to draw the landmarks on the Video frames itself. github.com Our project requires the following dependencies to be installed Flask pip install Flaskconda install -c anaconda flask Flask-SocketIO pip install Flask-SocketIOconda install -c conda-forge flask-socketio Our Flask app creation consists of 3 parts Step 1: Creating a static webpage using Face-Api.js for landmark detection Step 2: Adding the webpage in Flask Server and Passing inferences from the webpage asynchronously to the flask backend to process In this step, we will be using Face-Api.js to create static webpages for face detection and logging the inferences on the console. The File Structure which I am using is as follows |--static| |--js| | |--face-api.min.js| | |--index.js| |--styles| | |--style.js| |--models| | |-- // All the models from Face-Api.js|--template| |--index.html|-app.py The latest face-api.min.js is available to download here and the weights to be included in the models’ folder can be downloaded here We will create a basic HTML file with a video tag to show the output and add all the script and CSS files to the document in template/index.html To improve the basic UI CSS is added in static/styles/style.css Here comes the Magic... using Face-Api.js for face landmark detection. All the code is added in the static/js/index.js The above code is used to load the models and initialize the Face-api.js Then we would access the webcam and start to stream video data The startVideo() function is invoked once the face API is loaded After the video data is loaded we would add listeners to the video stream and add face-api.js inferences That’s it .... now you can view the webpage by using VS Code Live Server or by Web Server for Chrome ...select the folder and start the server and enter the URL in chrome tab Yay !! we have completed the first step of using face-api.js to do face landmark detection But still, we aren’t able to get this data in python. So let’s head to step 2... Let’s work on creating a basic flask app to view the webpage. Create a basic Flask app to render the webpage we created at app.py This might view the webpage but still, there is no way there is contact between the webpage and flask app to send and receive inference data. So we would be using Sockets for continuous data transfer Enter SocketIO Socket IO is useful to create client-server sockets between webpage and servers. The complexities of connection and sending and receiving data are carried by SocketIO functions so that we can focus on the main processing of data socket.io Creating a web socket in Flask App After installing the Flask-SocketIO dependencies we can update the app.py as per the following The above code creates a server-side socket for our App. So we need to create a client-side socket for our web app As you might know, connecting static files in Flask uses url_for(). Adding SocketIO dependencies to index.html and to link other static files in folders update the code accordingly To create a socket on Javascript side first initialize socket and test connection Due to the creation of the flask server, the face-api.js is not able to directly locate model weights as we had initialized before so need to update the models’ folder location in index.js To send the Data using socket add the following piece inside the setInterval() This will constantly send a stream of data to Flask. That’s All...Your data from the Browser will be sent to the flask Backend and will be printed on the terminal. you can do the post-processing accordingly To sum up the code implementation Demo of Face Detection using Flask I hope this was an interesting read for you guys. Thanks to thirumalainambi Yadav for support on the JS part of the project. Face-Api.js by Vincent Mühler from https://justadudewhohacks.github.io/face-api.js/docs/globals.html SocketIO example programs from here The entire project code is available in the following Github Repository github.com Thanks for having a read For Contacting Drop me a mail at [email protected] Or connect me through the following links
[ { "code": null, "e": 587, "s": 172, "text": "There are numerous face detection systems available online for Python like Dlib, OpenCV, and other Object Detection Systems by Deep Learning. We may have already used OpenCV to use a frame for capturing video from webcam and doing facial landmark detection using Dlib, MTCNN, etc. But I always got fed up that in a project I wasn’t able to add it in the UI or there are too many frame skips due to the load on CPU." }, { "code": null, "e": 1163, "s": 587, "text": "Most of the people use Flask as the goto framework for deploying their ML/DL model and beauty of creating UI from HTML and managing backend from python server works like a charm. But whenever you try to include webcam face detection for your web app you get stuck with a dialog box from Opencv imshow() and bust up the UX. The development of TF.js has empowered us to develop complex models on the browser itself. But python freaks like us with minimal knowledge on Node.js and other web development terminologies had to know on how to use these tools in our Flask playground" }, { "code": null, "e": 1268, "s": 1163, "text": "In this article, we would be creating a Flask web app with face recognition integrating into the browser" }, { "code": null, "e": 1279, "s": 1268, "text": "Advantages" }, { "code": null, "e": 1345, "s": 1279, "text": "Embed the video stream of data and inference into browser content" }, { "code": null, "e": 1392, "s": 1345, "text": "Less Utilization of Resources and improved FPS" }, { "code": null, "e": 1441, "s": 1392, "text": "No need to shift projects from Python to Node.js" }, { "code": null, "e": 1835, "s": 1441, "text": "As I was looking by a solution for face detection for Flask I came across a JavaScript API for face detection and face recognition in the browser made by Vincent Mühler who has done awesome work on creating APIs for TF.js implementation of Face detection and Recognization. These API can be used to extract data from the Webcam video and also to draw the landmarks on the Video frames itself." }, { "code": null, "e": 1846, "s": 1835, "text": "github.com" }, { "code": null, "e": 1910, "s": 1846, "text": "Our project requires the following dependencies to be installed" }, { "code": null, "e": 1916, "s": 1910, "text": "Flask" }, { "code": null, "e": 1965, "s": 1916, "text": "pip install Flaskconda install -c anaconda flask" }, { "code": null, "e": 1980, "s": 1965, "text": "Flask-SocketIO" }, { "code": null, "e": 2050, "s": 1980, "text": "pip install Flask-SocketIOconda install -c conda-forge flask-socketio" }, { "code": null, "e": 2093, "s": 2050, "text": "Our Flask app creation consists of 3 parts" }, { "code": null, "e": 2168, "s": 2093, "text": "Step 1: Creating a static webpage using Face-Api.js for landmark detection" }, { "code": null, "e": 2298, "s": 2168, "text": "Step 2: Adding the webpage in Flask Server and Passing inferences from the webpage asynchronously to the flask backend to process" }, { "code": null, "e": 2429, "s": 2298, "text": "In this step, we will be using Face-Api.js to create static webpages for face detection and logging the inferences on the console." }, { "code": null, "e": 2479, "s": 2429, "text": "The File Structure which I am using is as follows" }, { "code": null, "e": 2694, "s": 2479, "text": "|--static| |--js| | |--face-api.min.js| | |--index.js| |--styles| | |--style.js| |--models| | |-- // All the models from Face-Api.js|--template| |--index.html|-app.py" }, { "code": null, "e": 2827, "s": 2694, "text": "The latest face-api.min.js is available to download here and the weights to be included in the models’ folder can be downloaded here" }, { "code": null, "e": 2972, "s": 2827, "text": "We will create a basic HTML file with a video tag to show the output and add all the script and CSS files to the document in template/index.html" }, { "code": null, "e": 3036, "s": 2972, "text": "To improve the basic UI CSS is added in static/styles/style.css" }, { "code": null, "e": 3155, "s": 3036, "text": "Here comes the Magic... using Face-Api.js for face landmark detection. All the code is added in the static/js/index.js" }, { "code": null, "e": 3228, "s": 3155, "text": "The above code is used to load the models and initialize the Face-api.js" }, { "code": null, "e": 3291, "s": 3228, "text": "Then we would access the webcam and start to stream video data" }, { "code": null, "e": 3356, "s": 3291, "text": "The startVideo() function is invoked once the face API is loaded" }, { "code": null, "e": 3461, "s": 3356, "text": "After the video data is loaded we would add listeners to the video stream and add face-api.js inferences" }, { "code": null, "e": 3636, "s": 3461, "text": "That’s it .... now you can view the webpage by using VS Code Live Server or by Web Server for Chrome ...select the folder and start the server and enter the URL in chrome tab" }, { "code": null, "e": 3727, "s": 3636, "text": "Yay !! we have completed the first step of using face-api.js to do face landmark detection" }, { "code": null, "e": 3808, "s": 3727, "text": "But still, we aren’t able to get this data in python. So let’s head to step 2..." }, { "code": null, "e": 3938, "s": 3808, "text": "Let’s work on creating a basic flask app to view the webpage. Create a basic Flask app to render the webpage we created at app.py" }, { "code": null, "e": 4138, "s": 3938, "text": "This might view the webpage but still, there is no way there is contact between the webpage and flask app to send and receive inference data. So we would be using Sockets for continuous data transfer" }, { "code": null, "e": 4153, "s": 4138, "text": "Enter SocketIO" }, { "code": null, "e": 4382, "s": 4153, "text": "Socket IO is useful to create client-server sockets between webpage and servers. The complexities of connection and sending and receiving data are carried by SocketIO functions so that we can focus on the main processing of data" }, { "code": null, "e": 4392, "s": 4382, "text": "socket.io" }, { "code": null, "e": 4427, "s": 4392, "text": "Creating a web socket in Flask App" }, { "code": null, "e": 4522, "s": 4427, "text": "After installing the Flask-SocketIO dependencies we can update the app.py as per the following" }, { "code": null, "e": 4637, "s": 4522, "text": "The above code creates a server-side socket for our App. So we need to create a client-side socket for our web app" }, { "code": null, "e": 4818, "s": 4637, "text": "As you might know, connecting static files in Flask uses url_for(). Adding SocketIO dependencies to index.html and to link other static files in folders update the code accordingly" }, { "code": null, "e": 4900, "s": 4818, "text": "To create a socket on Javascript side first initialize socket and test connection" }, { "code": null, "e": 5089, "s": 4900, "text": "Due to the creation of the flask server, the face-api.js is not able to directly locate model weights as we had initialized before so need to update the models’ folder location in index.js" }, { "code": null, "e": 5221, "s": 5089, "text": "To send the Data using socket add the following piece inside the setInterval() This will constantly send a stream of data to Flask." }, { "code": null, "e": 5375, "s": 5221, "text": "That’s All...Your data from the Browser will be sent to the flask Backend and will be printed on the terminal. you can do the post-processing accordingly" }, { "code": null, "e": 5409, "s": 5375, "text": "To sum up the code implementation" }, { "code": null, "e": 5444, "s": 5409, "text": "Demo of Face Detection using Flask" }, { "code": null, "e": 5569, "s": 5444, "text": "I hope this was an interesting read for you guys. Thanks to thirumalainambi Yadav for support on the JS part of the project." }, { "code": null, "e": 5671, "s": 5569, "text": "Face-Api.js by Vincent Mühler from https://justadudewhohacks.github.io/face-api.js/docs/globals.html" }, { "code": null, "e": 5707, "s": 5671, "text": "SocketIO example programs from here" }, { "code": null, "e": 5779, "s": 5707, "text": "The entire project code is available in the following Github Repository" }, { "code": null, "e": 5790, "s": 5779, "text": "github.com" }, { "code": null, "e": 5815, "s": 5790, "text": "Thanks for having a read" }, { "code": null, "e": 5830, "s": 5815, "text": "For Contacting" }, { "code": null, "e": 5877, "s": 5830, "text": "Drop me a mail at [email protected]" } ]
How to place the cursor (auto focus) in the text box when a page gets loaded with HTML?
Use the autofocus attribute to place the cursor in the text box when a page loads. The autofocus attribute is a Boolean attribute. When present, it specifies that an <input> element should automatically get focus when the page loads. Here is an example − <!DOCTYPE html> <html> <body> <form action = "/new.php"> Name: <input type = "text" name = "name" autofocus><br> Subject: <input type = "text" name = "sub"><br> <input type = "submit"> </form> </body> </html>
[ { "code": null, "e": 1317, "s": 1062, "text": "Use the autofocus attribute to place the cursor in the text box when a page loads. The autofocus attribute is a Boolean attribute. When present, it specifies that an <input> element should automatically get focus when the page loads. Here is an example −" }, { "code": null, "e": 1573, "s": 1317, "text": "<!DOCTYPE html>\n<html>\n <body>\n\n <form action = \"/new.php\">\n Name: <input type = \"text\" name = \"name\" autofocus><br>\n Subject: <input type = \"text\" name = \"sub\"><br>\n <input type = \"submit\">\n </form>\n\n </body>\n</html>" } ]
How to check the current configuration of MongoDB?
In order to check the current configuration of MongoDB, you can use getCmdLineOpts. The query is as follows − > db._adminCommand( {getCmdLineOpts: 1}); The following is the output − { "argv" : [ "mongod" ], "parsed" : { }, "ok" : 1 } In order to check live settings, you can use the below query − > db._adminCommand({getParameter:"*"}); The following is the output &minus { "AsyncRequestsSenderUseBaton" : true, "KeysRotationIntervalSec" : 7776000, "ShardingTaskExecutorPoolHostTimeoutMS" : 300000, "ShardingTaskExecutorPoolMaxConnecting" : 2, "ShardingTaskExecutorPoolMaxSize" : -1, "ShardingTaskExecutorPoolMinSize" : 1, "ShardingTaskExecutorPoolRefreshRequirementMS" : 60000, "ShardingTaskExecutorPoolRefreshTimeoutMS" : 20000, "TransactionRecordMinimumLifetimeMinutes" : 30, "adaptiveServiceExecutorIdlePctThreshold" : 60, "adaptiveServiceExecutorMaxQueueLatencyMicros" : 500, "adaptiveServiceExecutorRecursionLimit" : 8, "adaptiveServiceExecutorReservedThreads" : -1, "adaptiveServiceExecutorRunTimeJitterMillis" : 500, "adaptiveServiceExecutorRunTimeMillis" : 5000, "adaptiveServiceExecutorStuckThreadTimeoutMillis" : 250, "allowSecondaryReadsDuringBatchApplication" : true, "authSchemaVersion" : 5, "authenticationMechanisms" : [ "MONGODB-X509", "SCRAM-SHA-1", "SCRAM-SHA-256" ], "bgSyncOplogFetcherBatchSize" : 13981010, "clientCursorMonitorFrequencySecs" : 4, "cloudFreeMonitoringEndpointURL" : "https://cloud.mongodb.com/freemonitoring/mongo", "clusterAuthMode" : "undefined", "collectionClonerBatchSize" : -1, "connPoolMaxConnsPerHost" : 200, "connPoolMaxInUseConnsPerHost" : 2147483647, "connPoolMaxShardedConnsPerHost" : 200, "connPoolMaxShardedInUseConnsPerHost" : 2147483647, "createRollbackDataFiles" : true, "createTimestampSafeUniqueIndex" : false, "cursorTimeoutMillis" : NumberLong(600000), "debugCollectionUUIDs" : false, "diagnosticDataCollectionDirectorySizeMB" : 200, "diagnosticDataCollectionEnabled" : true, "diagnosticDataCollectionFileSizeMB" : 10, "diagnosticDataCollectionPeriodMillis" : 1000, "diagnosticDataCollectionSamplesPerChunk" : 300, "diagnosticDataCollectionSamplesPerInterimUpdate" : 10, "disableJavaScriptJIT" : true, "disableLogicalSessionCacheRefresh" : false, "disableNonSSLConnectionLogging" : false, "disabledSecureAllocatorDomains" : [ ], "enableElectionHandoff" : true, "enableInMemoryTransactions" : false, "enableLocalhostAuthBypass" : true, "enableTestCommands" : false, "failIndexKeyTooLong" : true, "featureCompatibilityVersion" : { "version" : "4.0" }, "forceRollbackViaRefetch" : false, "globalConnPoolIdleTimeoutMinutes" : 2147483647, "initialSyncOplogBuffer" : "collection", "initialSyncOplogBufferPeekCacheSize" : 10000, "initialSyncOplogFetcherBatchSize" : 13981010, "internalDocumentSourceCursorBatchSizeBytes" : 4194304, "internalDocumentSourceLookupCacheSizeBytes" : 104857600, "internalGeoNearQuery2DMaxCoveringCells" : 16, "internalGeoPredicateQuery2DMaxCoveringCells" : 16, "internalInsertMaxBatchSize" : 64, "internalProhibitShardOperationRetry" : false, "internalQueryAlwaysMergeOnPrimaryShard" : false, "internalQueryCacheEvictionRatio" : 10, "internalQueryCacheFeedbacksStored" : 20, "internalQueryCacheSize" : 5000, "internalQueryEnumerationMaxIntersectPerAnd" : 3, "internalQueryEnumerationMaxOrSolutions" : 10, "internalQueryExecMaxBlockingSortBytes" : 33554432, "internalQueryExecYieldIterations" : 128, "internalQueryExecYieldPeriodMS" : 10, "internalQueryFacetBufferSizeBytes" : 104857600, "internalQueryForceIntersectionPlans" : false, "internalQueryIgnoreUnknownJSONSchemaKeywords" : false, "internalQueryMaxScansToExplode" : 200, "internalQueryPlanEvaluationCollFraction" : 0.3, "internalQueryPlanEvaluationMaxResults" : 101, "internalQueryPlanEvaluationWorks" : 10000, "internalQueryPlanOrChildrenIndependently" : true, "internalQueryPlannerEnableHashIntersection" : false, "internalQueryPlannerEnableIndexIntersection" : true, "internalQueryPlannerGenerateCoveredWholeIndexScans" : false, "internalQueryPlannerMaxIndexedSolutions" : 64, "internalQueryProhibitBlockingMergeOnMongoS" : false, "internalQueryProhibitMergingOnMongoS" : false, "internalQueryS2GeoCoarsestLevel" : 0, "internalQueryS2GeoFinestLevel" : 23, "internalQueryS2GeoMaxCells" : 20, "internalValidateFeaturesAsMaster" : true, "javascriptProtection" : false, "journalCommitInterval" : 0, "jsHeapLimitMB" : 1100, "localLogicalSessionTimeoutMinutes" : 30, "logComponentVerbosity" : { "verbosity" : 0, "accessControl" : { "verbosity" : -1 }, "command" : { "verbosity" : -1 }, "control" : { "verbosity" : -1 }, "executor" : { "verbosity" : -1 }, "geo" : { "verbosity" : -1 }, "index" : { "verbosity" : -1 }, "network" : { "verbosity" : -1, "asio" : { "verbosity" : -1 }, "bridge" : { "verbosity" : -1 } }, "query" : { "verbosity" : -1 }, "replication" : { "verbosity" : -1, "heartbeats" : { "verbosity" : -1 }, "rollback" : { "verbosity" : -1 } }, "sharding" : { "verbosity" : -1, "shardingCatalogRefresh" : { "verbosity" : -1 } }, "storage" : { "verbosity" : -1, "recovery" : { "verbosity" : -1 }, "journal" : { "verbosity" : -1 } }, "write" : { "verbosity" : -1 }, "ftdc" : { "verbosity" : -1 }, "tracking" : { "verbosity" : -1 }, "transaction" : { "verbosity" : -1 } }, "logLevel" : 0, "logicalSessionRefreshMillis" : 300000, "maxAcceptableLogicalClockDriftSecs" : NumberLong(31536000), "maxBSONDepth" : 200, "maxIndexBuildMemoryUsageMegabytes" : 500, "maxLogSizeKB" : 10, "maxNumInitialSyncCollectionClonerCursors" : 1, "maxSessions" : 1000000, "maxSyncSourceLagSecs" : 30, "maxTransactionLockRequestTimeoutMillis" : 5, "migrateCloneInsertionBatchDelayMS" : 0, "migrateCloneInsertionBatchSize" : 0, "newCollectionsUsePowerOf2Sizes" : true, "notablescan" : false, "numInitialSyncAttempts" : 10, "numInitialSyncCollectionCountAttempts" : 3, "numInitialSyncCollectionFindAttempts" : 3, "numInitialSyncConnectAttempts" : 10, "numInitialSyncListCollectionsAttempts" : 3, "numInitialSyncListDatabasesAttempts" : 3, "numInitialSyncListIndexesAttempts" : 3, "numInitialSyncOplogFindAttempts" : 3, "opensslCipherConfig" : "", "opensslDiffieHellmanParameters" : "", "oplogFetcherInitialSyncMaxFetcherRestarts" : 10, "oplogFetcherSteadyStateMaxFetcherRestarts" : 1, "oplogInitialFindMaxSeconds" : 60, "oplogRetriedFindMaxSeconds" : 2, "orphanCleanupDelaySecs" : 900, "periodicNoopIntervalSecs" : 10, "priorityTakeoverFreshnessWindowSeconds" : 2, "quiet" : false, "rangeDeleterBatchDelayMS" : 20, "rangeDeleterBatchSize" : 0, "recoverFromOplogAsStandalone" : false, "replBatchLimitOperations" : 5000, "replElectionTimeoutOffsetLimitFraction" : 0.15, "replIndexPrefetch" : "uninitialized", "replWriterThreadCount" : 16, "reservedServiceExecutorRecursionLimit" : 8, "rollbackRemoteOplogQueryBatchSize" : 2000, "rollbackTimeLimitSecs" : 86400, "saslHostName" : "DESKTOP-QN2RB3H", "saslServiceName" : "mongodb", "saslauthdPath" : "", "scramIterationCount" : 10000, "scramSHA256IterationCount" : 15000, "scriptingEngineInterruptIntervalMS" : 1000, "shardedConnPoolIdleTimeoutMinutes" : 2147483647, "skipCorruptDocumentsWhenCloning" : false, "skipShardingConfigurationChecks" : false, "sslMode" : "disabled", "sslWithholdClientCertificate" : false, "startupAuthSchemaValidation" : true, "suppressNoTLSPeerCertificateWarning" : false, "syncdelay" : 60, "synchronousServiceExecutorRecursionLimit" : 8, "taskExecutorPoolSize" : 1, "tcmallocAggressiveMemoryDecommit" : 0, "tcmallocEnableMarkThreadTemporarilyIdle" : false, "tcmallocMaxTotalThreadCacheBytes" : NumberLong(1073741824), "testingSnapshotBehaviorInIsolation" : false, "traceExceptions" : false, "traceWriteConflictExceptions" : false, "transactionLifetimeLimitSeconds" : 60, "ttlMonitorEnabled" : true, "ttlMonitorSleepSecs" : 60, "waitForSecondaryBeforeNoopWriteMS" : 10, "wiredTigerConcurrentReadTransactions" : 128, "wiredTigerConcurrentWriteTransactions" : 128, "wiredTigerCursorCacheSize" : -100, "wiredTigerEngineRuntimeConfig" : "", "writePeriodicNoops" : true, "ok" : 1 }
[ { "code": null, "e": 1172, "s": 1062, "text": "In order to check the current configuration of MongoDB, you can use getCmdLineOpts. The query is as follows −" }, { "code": null, "e": 1214, "s": 1172, "text": "> db._adminCommand( {getCmdLineOpts: 1});" }, { "code": null, "e": 1244, "s": 1214, "text": "The following is the output −" }, { "code": null, "e": 1296, "s": 1244, "text": "{ \"argv\" : [ \"mongod\" ], \"parsed\" : { }, \"ok\" : 1 }" }, { "code": null, "e": 1359, "s": 1296, "text": "In order to check live settings, you can use the below query −" }, { "code": null, "e": 1399, "s": 1359, "text": "> db._adminCommand({getParameter:\"*\"});" }, { "code": null, "e": 1434, "s": 1399, "text": "The following is the output &minus" }, { "code": null, "e": 9957, "s": 1434, "text": "{\n \"AsyncRequestsSenderUseBaton\" : true,\n \"KeysRotationIntervalSec\" : 7776000,\n \"ShardingTaskExecutorPoolHostTimeoutMS\" : 300000,\n \"ShardingTaskExecutorPoolMaxConnecting\" : 2,\n \"ShardingTaskExecutorPoolMaxSize\" : -1,\n \"ShardingTaskExecutorPoolMinSize\" : 1,\n \"ShardingTaskExecutorPoolRefreshRequirementMS\" : 60000,\n \"ShardingTaskExecutorPoolRefreshTimeoutMS\" : 20000,\n \"TransactionRecordMinimumLifetimeMinutes\" : 30,\n \"adaptiveServiceExecutorIdlePctThreshold\" : 60,\n \"adaptiveServiceExecutorMaxQueueLatencyMicros\" : 500,\n \"adaptiveServiceExecutorRecursionLimit\" : 8,\n \"adaptiveServiceExecutorReservedThreads\" : -1,\n \"adaptiveServiceExecutorRunTimeJitterMillis\" : 500,\n \"adaptiveServiceExecutorRunTimeMillis\" : 5000,\n \"adaptiveServiceExecutorStuckThreadTimeoutMillis\" : 250,\n \"allowSecondaryReadsDuringBatchApplication\" : true,\n \"authSchemaVersion\" : 5,\n \"authenticationMechanisms\" : [\n \"MONGODB-X509\",\n \"SCRAM-SHA-1\",\n \"SCRAM-SHA-256\"\n ],\n \"bgSyncOplogFetcherBatchSize\" : 13981010,\n \"clientCursorMonitorFrequencySecs\" : 4,\n \"cloudFreeMonitoringEndpointURL\" : \"https://cloud.mongodb.com/freemonitoring/mongo\",\n \"clusterAuthMode\" : \"undefined\",\n \"collectionClonerBatchSize\" : -1,\n \"connPoolMaxConnsPerHost\" : 200,\n \"connPoolMaxInUseConnsPerHost\" : 2147483647,\n \"connPoolMaxShardedConnsPerHost\" : 200,\n \"connPoolMaxShardedInUseConnsPerHost\" : 2147483647,\n \"createRollbackDataFiles\" : true,\n \"createTimestampSafeUniqueIndex\" : false,\n \"cursorTimeoutMillis\" : NumberLong(600000),\n \"debugCollectionUUIDs\" : false,\n \"diagnosticDataCollectionDirectorySizeMB\" : 200,\n \"diagnosticDataCollectionEnabled\" : true,\n \"diagnosticDataCollectionFileSizeMB\" : 10,\n \"diagnosticDataCollectionPeriodMillis\" : 1000,\n \"diagnosticDataCollectionSamplesPerChunk\" : 300,\n \"diagnosticDataCollectionSamplesPerInterimUpdate\" : 10,\n \"disableJavaScriptJIT\" : true,\n \"disableLogicalSessionCacheRefresh\" : false,\n \"disableNonSSLConnectionLogging\" : false,\n \"disabledSecureAllocatorDomains\" : [ ],\n \"enableElectionHandoff\" : true,\n \"enableInMemoryTransactions\" : false,\n \"enableLocalhostAuthBypass\" : true,\n \"enableTestCommands\" : false,\n \"failIndexKeyTooLong\" : true,\n \"featureCompatibilityVersion\" : {\n \"version\" : \"4.0\"\n },\n \"forceRollbackViaRefetch\" : false,\n \"globalConnPoolIdleTimeoutMinutes\" : 2147483647,\n \"initialSyncOplogBuffer\" : \"collection\",\n \"initialSyncOplogBufferPeekCacheSize\" : 10000,\n \"initialSyncOplogFetcherBatchSize\" : 13981010,\n \"internalDocumentSourceCursorBatchSizeBytes\" : 4194304,\n \"internalDocumentSourceLookupCacheSizeBytes\" : 104857600,\n \"internalGeoNearQuery2DMaxCoveringCells\" : 16,\n \"internalGeoPredicateQuery2DMaxCoveringCells\" : 16,\n \"internalInsertMaxBatchSize\" : 64,\n \"internalProhibitShardOperationRetry\" : false,\n \"internalQueryAlwaysMergeOnPrimaryShard\" : false,\n \"internalQueryCacheEvictionRatio\" : 10,\n \"internalQueryCacheFeedbacksStored\" : 20,\n \"internalQueryCacheSize\" : 5000,\n \"internalQueryEnumerationMaxIntersectPerAnd\" : 3,\n \"internalQueryEnumerationMaxOrSolutions\" : 10,\n \"internalQueryExecMaxBlockingSortBytes\" : 33554432,\n \"internalQueryExecYieldIterations\" : 128,\n \"internalQueryExecYieldPeriodMS\" : 10,\n \"internalQueryFacetBufferSizeBytes\" : 104857600,\n \"internalQueryForceIntersectionPlans\" : false,\n \"internalQueryIgnoreUnknownJSONSchemaKeywords\" : false,\n \"internalQueryMaxScansToExplode\" : 200,\n \"internalQueryPlanEvaluationCollFraction\" : 0.3,\n \"internalQueryPlanEvaluationMaxResults\" : 101,\n \"internalQueryPlanEvaluationWorks\" : 10000,\n \"internalQueryPlanOrChildrenIndependently\" : true,\n \"internalQueryPlannerEnableHashIntersection\" : false,\n \"internalQueryPlannerEnableIndexIntersection\" : true,\n \"internalQueryPlannerGenerateCoveredWholeIndexScans\" : false,\n \"internalQueryPlannerMaxIndexedSolutions\" : 64,\n \"internalQueryProhibitBlockingMergeOnMongoS\" : false,\n \"internalQueryProhibitMergingOnMongoS\" : false,\n \"internalQueryS2GeoCoarsestLevel\" : 0,\n \"internalQueryS2GeoFinestLevel\" : 23,\n \"internalQueryS2GeoMaxCells\" : 20,\n \"internalValidateFeaturesAsMaster\" : true,\n \"javascriptProtection\" : false,\n \"journalCommitInterval\" : 0,\n \"jsHeapLimitMB\" : 1100,\n \"localLogicalSessionTimeoutMinutes\" : 30,\n \"logComponentVerbosity\" : {\n \"verbosity\" : 0,\n \"accessControl\" : {\n \"verbosity\" : -1\n },\n \"command\" : {\n \"verbosity\" : -1\n },\n \"control\" : {\n \"verbosity\" : -1\n },\n \"executor\" : {\n \"verbosity\" : -1\n },\n \"geo\" : {\n \"verbosity\" : -1\n },\n \"index\" : {\n \"verbosity\" : -1\n },\n \"network\" : {\n \"verbosity\" : -1,\n \"asio\" : {\n \"verbosity\" : -1\n },\n \"bridge\" : {\n \"verbosity\" : -1\n }\n },\n \"query\" : {\n \"verbosity\" : -1\n },\n \"replication\" : {\n \"verbosity\" : -1,\n \"heartbeats\" : {\n \"verbosity\" : -1\n },\n \"rollback\" : {\n \"verbosity\" : -1\n }\n },\n \"sharding\" : {\n \"verbosity\" : -1,\n \"shardingCatalogRefresh\" : {\n \"verbosity\" : -1\n }\n },\n \"storage\" : {\n \"verbosity\" : -1,\n \"recovery\" : {\n \"verbosity\" : -1\n },\n \"journal\" : {\n \"verbosity\" : -1\n }\n },\n \"write\" : {\n \"verbosity\" : -1\n },\n \"ftdc\" : {\n \"verbosity\" : -1\n },\n \"tracking\" : {\n \"verbosity\" : -1\n },\n \"transaction\" : {\n \"verbosity\" : -1\n }\n },\n \"logLevel\" : 0,\n \"logicalSessionRefreshMillis\" : 300000,\n \"maxAcceptableLogicalClockDriftSecs\" : NumberLong(31536000),\n \"maxBSONDepth\" : 200,\n \"maxIndexBuildMemoryUsageMegabytes\" : 500,\n \"maxLogSizeKB\" : 10,\n \"maxNumInitialSyncCollectionClonerCursors\" : 1,\n \"maxSessions\" : 1000000,\n \"maxSyncSourceLagSecs\" : 30,\n \"maxTransactionLockRequestTimeoutMillis\" : 5,\n \"migrateCloneInsertionBatchDelayMS\" : 0,\n \"migrateCloneInsertionBatchSize\" : 0,\n \"newCollectionsUsePowerOf2Sizes\" : true,\n \"notablescan\" : false,\n \"numInitialSyncAttempts\" : 10,\n \"numInitialSyncCollectionCountAttempts\" : 3,\n \"numInitialSyncCollectionFindAttempts\" : 3,\n \"numInitialSyncConnectAttempts\" : 10,\n \"numInitialSyncListCollectionsAttempts\" : 3,\n \"numInitialSyncListDatabasesAttempts\" : 3,\n \"numInitialSyncListIndexesAttempts\" : 3,\n \"numInitialSyncOplogFindAttempts\" : 3,\n \"opensslCipherConfig\" : \"\",\n \"opensslDiffieHellmanParameters\" : \"\",\n \"oplogFetcherInitialSyncMaxFetcherRestarts\" : 10,\n \"oplogFetcherSteadyStateMaxFetcherRestarts\" : 1,\n \"oplogInitialFindMaxSeconds\" : 60,\n \"oplogRetriedFindMaxSeconds\" : 2,\n \"orphanCleanupDelaySecs\" : 900,\n \"periodicNoopIntervalSecs\" : 10,\n \"priorityTakeoverFreshnessWindowSeconds\" : 2,\n \"quiet\" : false,\n \"rangeDeleterBatchDelayMS\" : 20,\n \"rangeDeleterBatchSize\" : 0,\n \"recoverFromOplogAsStandalone\" : false,\n \"replBatchLimitOperations\" : 5000,\n \"replElectionTimeoutOffsetLimitFraction\" : 0.15,\n \"replIndexPrefetch\" : \"uninitialized\",\n \"replWriterThreadCount\" : 16,\n \"reservedServiceExecutorRecursionLimit\" : 8,\n \"rollbackRemoteOplogQueryBatchSize\" : 2000,\n \"rollbackTimeLimitSecs\" : 86400,\n \"saslHostName\" : \"DESKTOP-QN2RB3H\",\n \"saslServiceName\" : \"mongodb\",\n \"saslauthdPath\" : \"\",\n \"scramIterationCount\" : 10000,\n \"scramSHA256IterationCount\" : 15000,\n \"scriptingEngineInterruptIntervalMS\" : 1000,\n \"shardedConnPoolIdleTimeoutMinutes\" : 2147483647,\n \"skipCorruptDocumentsWhenCloning\" : false,\n \"skipShardingConfigurationChecks\" : false,\n \"sslMode\" : \"disabled\",\n \"sslWithholdClientCertificate\" : false,\n \"startupAuthSchemaValidation\" : true,\n \"suppressNoTLSPeerCertificateWarning\" : false,\n \"syncdelay\" : 60,\n \"synchronousServiceExecutorRecursionLimit\" : 8,\n \"taskExecutorPoolSize\" : 1,\n \"tcmallocAggressiveMemoryDecommit\" : 0,\n \"tcmallocEnableMarkThreadTemporarilyIdle\" : false,\n \"tcmallocMaxTotalThreadCacheBytes\" : NumberLong(1073741824),\n \"testingSnapshotBehaviorInIsolation\" : false,\n \"traceExceptions\" : false,\n \"traceWriteConflictExceptions\" : false,\n \"transactionLifetimeLimitSeconds\" : 60,\n \"ttlMonitorEnabled\" : true,\n \"ttlMonitorSleepSecs\" : 60,\n \"waitForSecondaryBeforeNoopWriteMS\" : 10,\n \"wiredTigerConcurrentReadTransactions\" : 128,\n \"wiredTigerConcurrentWriteTransactions\" : 128,\n \"wiredTigerCursorCacheSize\" : -100,\n \"wiredTigerEngineRuntimeConfig\" : \"\",\n \"writePeriodicNoops\" : true,\n \"ok\" : 1\n}" } ]
How to get the list of all drivers registered with the DriverManager using JDBC?
The java.sql.DriverManager class manages JDBC drivers in your application. This class maintains a list of required drivers and load them whenever it is initialized. Therefore, you need to register the driver class before using it. However, you need to do it only once per application. One way to register a driver class object to Driver manager is the registerDriver() method of the DriverManager class. To this method you need to pass the Driver object as a parameter. //Instantiating a driver class Driver driver = new com.mysql.jdbc.Driver(); //Registering the Driver DriverManager.registerDriver(driver); You can get the list of all the drivers registered with this DriverManager class using the getDrivers() method of it. This method returns an Enumeration containing the list of drivers. //Retrieving the list of all the Drivers Enumeration<Driver> e = DriverManager.getDrivers(); //Printing the list while(e.hasMoreElements()) { System.out.println(e.nextElement().getClass()); } Following JDBC program registers a bunch of JDBC drivers using the registerDriver() method and, displays the list of them using the getDrivers() method. import java.sql.Driver; import java.sql.DriverManager; import java.util.Enumeration; public class DriversList_DriverManager { public static void main(String args[])throws Exception { //Registering MySQL driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Registering SQLite driver DriverManager.registerDriver(new org.sqlite.JDBC()); //Registering Oracle driver DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); //Registering Derby-client driver DriverManager.registerDriver(new org.apache.derby.jdbc.ClientDriver()); //Registering Derby-autoloaded driver DriverManager.registerDriver(new org.apache.derby.jdbc.AutoloadedDriver()); //Registering HSQLDb-JDBC driver DriverManager.registerDriver(new org.hsqldb.jdbc.JDBCDriver()); System.out.println("List of all the Drivers registered with the DriverManager:"); //Retrieving the list of all the Drivers Enumeration<Driver> e = DriverManager.getDrivers(); //Printing the list while(e.hasMoreElements()) { System.out.println(e.nextElement().getClass()); } System.out.println(); } } List of all the Drivers registered with the DriverManager: class org.sqlite.JDBC class org.apache.derby.jdbc.ClientDriver class org.apache.derby.jdbc.AutoloadedDriver class org.hsqldb.jdbc.JDBCDriver class com.mysql.jdbc.Driver class oracle.jdbc.driver.OracleDriver
[ { "code": null, "e": 1227, "s": 1062, "text": "The java.sql.DriverManager class manages JDBC drivers in your application. This class maintains a list of required drivers and load them whenever it is initialized." }, { "code": null, "e": 1347, "s": 1227, "text": "Therefore, you need to register the driver class before using it. However, you need to do it only once per application." }, { "code": null, "e": 1532, "s": 1347, "text": "One way to register a driver class object to Driver manager is the registerDriver() method of the DriverManager class. To this method you need to pass the Driver object as a parameter." }, { "code": null, "e": 1671, "s": 1532, "text": "//Instantiating a driver class Driver driver = new com.mysql.jdbc.Driver();\n//Registering the Driver DriverManager.registerDriver(driver);" }, { "code": null, "e": 1856, "s": 1671, "text": "You can get the list of all the drivers registered with this DriverManager class using the getDrivers() method of it. This method returns an Enumeration containing the list of drivers." }, { "code": null, "e": 2051, "s": 1856, "text": "//Retrieving the list of all the Drivers\nEnumeration<Driver> e = DriverManager.getDrivers();\n//Printing the list\nwhile(e.hasMoreElements()) {\n System.out.println(e.nextElement().getClass());\n}" }, { "code": null, "e": 2204, "s": 2051, "text": "Following JDBC program registers a bunch of JDBC drivers using the registerDriver() method and, displays the list of them using the getDrivers() method." }, { "code": null, "e": 3397, "s": 2204, "text": "import java.sql.Driver;\nimport java.sql.DriverManager;\nimport java.util.Enumeration;\npublic class DriversList_DriverManager {\n public static void main(String args[])throws Exception {\n //Registering MySQL driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Registering SQLite driver\n DriverManager.registerDriver(new org.sqlite.JDBC());\n //Registering Oracle driver\n DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());\n //Registering Derby-client driver\n DriverManager.registerDriver(new org.apache.derby.jdbc.ClientDriver());\n //Registering Derby-autoloaded driver\n DriverManager.registerDriver(new org.apache.derby.jdbc.AutoloadedDriver());\n //Registering HSQLDb-JDBC driver\n DriverManager.registerDriver(new org.hsqldb.jdbc.JDBCDriver());\n System.out.println(\"List of all the Drivers registered with the DriverManager:\");\n //Retrieving the list of all the Drivers\n Enumeration<Driver> e = DriverManager.getDrivers();\n //Printing the list\n while(e.hasMoreElements()) {\n System.out.println(e.nextElement().getClass());\n }\n System.out.println();\n }\n}" }, { "code": null, "e": 3663, "s": 3397, "text": "List of all the Drivers registered with the DriverManager:\nclass org.sqlite.JDBC\nclass org.apache.derby.jdbc.ClientDriver\nclass org.apache.derby.jdbc.AutoloadedDriver\nclass org.hsqldb.jdbc.JDBCDriver\nclass com.mysql.jdbc.Driver\nclass oracle.jdbc.driver.OracleDriver" } ]
Jupyter has a perfect code editor | by Dimitris Poulopoulos | Towards Data Science
Notebooks have always been a tool for the incremental development of software ideas. Data scientists use Jupyter to journal their work, explore and experiment with novel algorithms, quickly sketch new approaches and immediately observe the outcomes. Moreover, JupyterLab is moving towards becoming a full-fledged IDE; just not an IDE you are used to. With its great extensions and libraries like kale and nbdev, it is certainly capable of doing much more than just drafting an idea. Check the story below to find out more. towardsdatascience.com However, once every blue moon, we may want to edit a .py file. This file may hold some utility functions we import in the Notebook or define our models' classes. It’s a good practice to work like that, so we don’t pollute the Notebooks with many definitions. But the text editor bundled with JupyterLab is just that: a simple, featureless text editor. So, what can we do? There are efforts like this one, which tries to integrate the monaco editor (the code editor which powers VS Code) into JupyterLab. Still, as the contributors explicitly mention in the README file, “this extension is merely a ‘proof-of-concept’ implementation and nowhere near production status.” Also, the last commit was 3 years ago (at the time of writing), so it doesn’t seem like a very active project. But we do not need any extension. We have a terminal. Thus, we can have ViM. And ViM has everything we need; it just takes some time to master. If you love ViM, you know what I’m talking about. If you don’t, don’t shy away yet! This story shows you how to turn ViM into a Python IDE and use it side-by-side with Jupyter. Learning Rate is a newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news and articles. Subscribe here! Let’s get to the point. The first step is actually to install ViM if it’s not already there. In this story, I assume that we are working in a hoster JupyterLab environment. If you’re working locally, there’s nothing to stop you from firing up VS Code if you prefer that over ViM. So, my guess is that you’re working inside a VM on the Cloud. That usually means a Linux environment. To install ViM on Debian distributions, run the following commands: sudo apt-get remove vim-tinysudo apt-get updatesudo apt-get install vim Note that some Linux distributions come with vim-tiny pre-installed. Thus, we need to remove it first and then install the full version. Then, let’s verify we have everything we need. Run vim --version and pay attention to two things: You should have installed VIM > 7.3Check for a +python or +python3 feature You should have installed VIM > 7.3 Check for a +python or +python3 feature We are ready. Next, we need a good plugin manager. I find that Vundle is an excellent and simple to use plugin manager. Thus, we will use this for installing everything we need. To install Vundle we need two things. First, git clone the project in an appropriate directory: git clone https://github.com/gmarik/Vundle.vim.git ~/.vim/bundle/Vundle.vim Then, we need to create a .vimrc file in our home directory and add some lines on top. So, first, create the file: touch ~/.vimrc Then, add the following lines: set nocompatible " requiredfiletype off " required" set the runtime path to include Vundleset rtp+=~/.vim/bundle/Vundle.vimcall vundle#begin()" let Vundle manage Vundle, requiredPlugin 'gmarik/Vundle.vim'" add all your plugins here between the vundle#begin() and "vundle#end() calls" All of your Plugins must be added before the following linecall vundle#end() " requiredfiletype plugin indent on " required See the line that calls vundle#begin()? Between this and the vundle#end() call we can add any plugin we want. As a matter of fact, we have done this already: we have added the gmarik/Vundle.vim plugin. Installing a new plugin is as easy as copying and pasting its unique GitHub path. We will see how later. For now, launch ViM, enter the command mode by pressing : and execute PluginInstall. Let’s move. The first plugin we will install enables folding. Have you ever seen the numpy source code? Usually, the docstring of a function takes up the whole space. Let’s fold it by default. Install the plugin by adding this line between the begin and end calls we saw earlier: Plugin 'tmhedberg/SimpylFold' A reminder: every time you add a new plugin, don’t forget to install it with the PluginInstall command we saw. To enable the docstring folding by default, add the following setting, outside the begin-end block. let g:SimpylFold_docstring_preview=1 Next, let’s enable auto-indentation. Install the following plugin (now you know how): Plugin 'vim-scripts/indentpython.vim' Moreover, you can tell ViM how you want it to treat .py files by adding the following options in the vimrc file: au BufNewFile,BufRead *.py \ set tabstop=4 | \ set softtabstop=4 | \ set shiftwidth=4 | \ set textwidth=79 | \ set expandtab | \ set autoindent | \ set fileformat=unix The names of these settings are pretty much self-explanatory. The autoindent setting does most of the things right, but install the vim-scripts/indentpython.vim plugin, which is python specific, to keep your peace of mind. Last but not least, you need auto-complete. The best tool for this job is YouCompleteMe. However, its installation is a bit more involved. First, install the plugin with the following line: Bundle 'Valloric/YouCompleteMe' It will most probably show you an error at the end. Don’t worry. Proceed and install the necessary dependencies: apt install build-essential cmake python3-devapt install mono-complete golang nodejs default-jdk npm Finally, compile the plugin: cd ~/.vim/bundle/YouCompleteMepython3 install.py --all That’s it! You have most of the things you need to turn ViM into a Python IDE. Other plugins you might want to consider are: vim-syntastic/syntastic: Python syntax highlighting nvie/vim-flake8: PEP8 checking scrooloose/nerdtree: folder structure explorer tpope/vim-fugitive: git integration Here is a complete but not exhaustive .vimrc configuration. If you have more goodies to add, please comment! Notebooks have always been a tool for the incremental development of software ideas. Moreover, JupyterLab is moving towards becoming a full-fledged IDE. However, once every blue moon, we may want to edit a .py file, and the integrated text editor is just a text editor. This story examines how to transform ViM into a Python IDE and use it as our main code editor through the terminal. If you want more info on using ViM, just run vimtutor in your terminal and follow the instructions! My name is Dimitris Poulopoulos, and I’m a machine learning engineer working for Arrikto. I have designed and implemented AI and software solutions for major clients such as the European Commission, Eurostat, IMF, the European Central Bank, OECD, and IKEA. If you are interested in reading more posts about Machine Learning, Deep Learning, Data Science, and DataOps, follow me on Medium, LinkedIn, or @james2pl on Twitter. Also, visit the resources page on my website, a place for great books and top-rated courses, to start building your own Data Science curriculum!
[ { "code": null, "e": 422, "s": 172, "text": "Notebooks have always been a tool for the incremental development of software ideas. Data scientists use Jupyter to journal their work, explore and experiment with novel algorithms, quickly sketch new approaches and immediately observe the outcomes." }, { "code": null, "e": 695, "s": 422, "text": "Moreover, JupyterLab is moving towards becoming a full-fledged IDE; just not an IDE you are used to. With its great extensions and libraries like kale and nbdev, it is certainly capable of doing much more than just drafting an idea. Check the story below to find out more." }, { "code": null, "e": 718, "s": 695, "text": "towardsdatascience.com" }, { "code": null, "e": 1070, "s": 718, "text": "However, once every blue moon, we may want to edit a .py file. This file may hold some utility functions we import in the Notebook or define our models' classes. It’s a good practice to work like that, so we don’t pollute the Notebooks with many definitions. But the text editor bundled with JupyterLab is just that: a simple, featureless text editor." }, { "code": null, "e": 1498, "s": 1070, "text": "So, what can we do? There are efforts like this one, which tries to integrate the monaco editor (the code editor which powers VS Code) into JupyterLab. Still, as the contributors explicitly mention in the README file, “this extension is merely a ‘proof-of-concept’ implementation and nowhere near production status.” Also, the last commit was 3 years ago (at the time of writing), so it doesn’t seem like a very active project." }, { "code": null, "e": 1642, "s": 1498, "text": "But we do not need any extension. We have a terminal. Thus, we can have ViM. And ViM has everything we need; it just takes some time to master." }, { "code": null, "e": 1819, "s": 1642, "text": "If you love ViM, you know what I’m talking about. If you don’t, don’t shy away yet! This story shows you how to turn ViM into a Python IDE and use it side-by-side with Jupyter." }, { "code": null, "e": 2019, "s": 1819, "text": "Learning Rate is a newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news and articles. Subscribe here!" }, { "code": null, "e": 2299, "s": 2019, "text": "Let’s get to the point. The first step is actually to install ViM if it’s not already there. In this story, I assume that we are working in a hoster JupyterLab environment. If you’re working locally, there’s nothing to stop you from firing up VS Code if you prefer that over ViM." }, { "code": null, "e": 2469, "s": 2299, "text": "So, my guess is that you’re working inside a VM on the Cloud. That usually means a Linux environment. To install ViM on Debian distributions, run the following commands:" }, { "code": null, "e": 2541, "s": 2469, "text": "sudo apt-get remove vim-tinysudo apt-get updatesudo apt-get install vim" }, { "code": null, "e": 2678, "s": 2541, "text": "Note that some Linux distributions come with vim-tiny pre-installed. Thus, we need to remove it first and then install the full version." }, { "code": null, "e": 2776, "s": 2678, "text": "Then, let’s verify we have everything we need. Run vim --version and pay attention to two things:" }, { "code": null, "e": 2851, "s": 2776, "text": "You should have installed VIM > 7.3Check for a +python or +python3 feature" }, { "code": null, "e": 2887, "s": 2851, "text": "You should have installed VIM > 7.3" }, { "code": null, "e": 2927, "s": 2887, "text": "Check for a +python or +python3 feature" }, { "code": null, "e": 2978, "s": 2927, "text": "We are ready. Next, we need a good plugin manager." }, { "code": null, "e": 3201, "s": 2978, "text": "I find that Vundle is an excellent and simple to use plugin manager. Thus, we will use this for installing everything we need. To install Vundle we need two things. First, git clone the project in an appropriate directory:" }, { "code": null, "e": 3277, "s": 3201, "text": "git clone https://github.com/gmarik/Vundle.vim.git ~/.vim/bundle/Vundle.vim" }, { "code": null, "e": 3392, "s": 3277, "text": "Then, we need to create a .vimrc file in our home directory and add some lines on top. So, first, create the file:" }, { "code": null, "e": 3407, "s": 3392, "text": "touch ~/.vimrc" }, { "code": null, "e": 3438, "s": 3407, "text": "Then, add the following lines:" }, { "code": null, "e": 3890, "s": 3438, "text": "set nocompatible \" requiredfiletype off \" required\" set the runtime path to include Vundleset rtp+=~/.vim/bundle/Vundle.vimcall vundle#begin()\" let Vundle manage Vundle, requiredPlugin 'gmarik/Vundle.vim'\" add all your plugins here between the vundle#begin() and \"vundle#end() calls\" All of your Plugins must be added before the following linecall vundle#end() \" requiredfiletype plugin indent on \" required" }, { "code": null, "e": 4197, "s": 3890, "text": "See the line that calls vundle#begin()? Between this and the vundle#end() call we can add any plugin we want. As a matter of fact, we have done this already: we have added the gmarik/Vundle.vim plugin. Installing a new plugin is as easy as copying and pasting its unique GitHub path. We will see how later." }, { "code": null, "e": 4294, "s": 4197, "text": "For now, launch ViM, enter the command mode by pressing : and execute PluginInstall. Let’s move." }, { "code": null, "e": 4562, "s": 4294, "text": "The first plugin we will install enables folding. Have you ever seen the numpy source code? Usually, the docstring of a function takes up the whole space. Let’s fold it by default. Install the plugin by adding this line between the begin and end calls we saw earlier:" }, { "code": null, "e": 4592, "s": 4562, "text": "Plugin 'tmhedberg/SimpylFold'" }, { "code": null, "e": 4703, "s": 4592, "text": "A reminder: every time you add a new plugin, don’t forget to install it with the PluginInstall command we saw." }, { "code": null, "e": 4803, "s": 4703, "text": "To enable the docstring folding by default, add the following setting, outside the begin-end block." }, { "code": null, "e": 4840, "s": 4803, "text": "let g:SimpylFold_docstring_preview=1" }, { "code": null, "e": 4926, "s": 4840, "text": "Next, let’s enable auto-indentation. Install the following plugin (now you know how):" }, { "code": null, "e": 4964, "s": 4926, "text": "Plugin 'vim-scripts/indentpython.vim'" }, { "code": null, "e": 5077, "s": 4964, "text": "Moreover, you can tell ViM how you want it to treat .py files by adding the following options in the vimrc file:" }, { "code": null, "e": 5266, "s": 5077, "text": "au BufNewFile,BufRead *.py \\ set tabstop=4 | \\ set softtabstop=4 | \\ set shiftwidth=4 | \\ set textwidth=79 | \\ set expandtab | \\ set autoindent | \\ set fileformat=unix" }, { "code": null, "e": 5489, "s": 5266, "text": "The names of these settings are pretty much self-explanatory. The autoindent setting does most of the things right, but install the vim-scripts/indentpython.vim plugin, which is python specific, to keep your peace of mind." }, { "code": null, "e": 5679, "s": 5489, "text": "Last but not least, you need auto-complete. The best tool for this job is YouCompleteMe. However, its installation is a bit more involved. First, install the plugin with the following line:" }, { "code": null, "e": 5711, "s": 5679, "text": "Bundle 'Valloric/YouCompleteMe'" }, { "code": null, "e": 5824, "s": 5711, "text": "It will most probably show you an error at the end. Don’t worry. Proceed and install the necessary dependencies:" }, { "code": null, "e": 5925, "s": 5824, "text": "apt install build-essential cmake python3-devapt install mono-complete golang nodejs default-jdk npm" }, { "code": null, "e": 5954, "s": 5925, "text": "Finally, compile the plugin:" }, { "code": null, "e": 6009, "s": 5954, "text": "cd ~/.vim/bundle/YouCompleteMepython3 install.py --all" }, { "code": null, "e": 6134, "s": 6009, "text": "That’s it! You have most of the things you need to turn ViM into a Python IDE. Other plugins you might want to consider are:" }, { "code": null, "e": 6186, "s": 6134, "text": "vim-syntastic/syntastic: Python syntax highlighting" }, { "code": null, "e": 6217, "s": 6186, "text": "nvie/vim-flake8: PEP8 checking" }, { "code": null, "e": 6264, "s": 6217, "text": "scrooloose/nerdtree: folder structure explorer" }, { "code": null, "e": 6300, "s": 6264, "text": "tpope/vim-fugitive: git integration" }, { "code": null, "e": 6409, "s": 6300, "text": "Here is a complete but not exhaustive .vimrc configuration. If you have more goodies to add, please comment!" }, { "code": null, "e": 6679, "s": 6409, "text": "Notebooks have always been a tool for the incremental development of software ideas. Moreover, JupyterLab is moving towards becoming a full-fledged IDE. However, once every blue moon, we may want to edit a .py file, and the integrated text editor is just a text editor." }, { "code": null, "e": 6895, "s": 6679, "text": "This story examines how to transform ViM into a Python IDE and use it as our main code editor through the terminal. If you want more info on using ViM, just run vimtutor in your terminal and follow the instructions!" }, { "code": null, "e": 7152, "s": 6895, "text": "My name is Dimitris Poulopoulos, and I’m a machine learning engineer working for Arrikto. I have designed and implemented AI and software solutions for major clients such as the European Commission, Eurostat, IMF, the European Central Bank, OECD, and IKEA." } ]
Given an array and three numbers, maximize (x * a[i]) + (y * a[j]) + (z * a[k]) - GeeksforGeeks
12 Feb, 2022 Given an array of n integers, and three integers x, y and z. maximize the value of (x * a[i]) + (y * a[j]) + (z * a[k]) where i ≤ j ≤ k. Examples : Input : arr[] = {-1, -2, -3, -4, -5} x = 1 y = 2 z = -3 Output: 12 Explanation: The maximized values is (1 * -1) + (2 * -1) + ( -3 * -5) = 12 Input: arr[] = {1, 2, 3, 4, 5} x = 1 y = 2 z = 3 Output: 30 (1*5 + 2*5 + 3*5) = 30 A simple solution is to run three nested loops to iterate through all triplets. For every triplet, compute the required value and keep track of maximum and finally return the same. An efficient solution is to precompute values and stores them using extra space. The first key observation is i ≤ j ≤ k, so x*a[i] will always be the left maximum, and z*a[k] will always be the right maximum. Create a left array where we store the left maximums for every element. Create a right array where we store the right maximums for every element. Then for every element, calculate the maximum value of the function possible. For any index ind, the maximum at that position will always be (left[ind] + j * a[ind] + right[ind]), find the maximum of this value for every element in the array and that will be your answer. Below is the implementation of the above approach C++ Java Python3 C# PHP Javascript // CPP program to find the maximum value of// x*arr[i] + y*arr[j] + z*arr[k]#include <bits/stdc++.h>using namespace std; // function to maximize the conditionint maximizeExpr(int a[], int n, int x, int y, int z){ // Traverse the whole array and compute // left maximum for every index. int L[n]; L[0] = x * a[0]; for (int i = 1; i < n; i++) L[i] = max(L[i - 1], x * a[i]); // Compute right maximum for every index. int R[n]; R[n-1] = z * a[n-1]; for (int i = n - 2; i >= 0; i--) R[i] = max(R[i + 1], z * a[i]); // Traverse through the whole array to // maximize the required expression. int ans = INT_MIN; for (int i = 0; i < n; i++) ans = max(ans, L[i] + y * a[i] + R[i]); return ans;} // driver program to test the above functionint main(){ int a[] = {-1, -2, -3, -4, -5}; int n = sizeof(a)/sizeof(a[0]); int x = 1, y = 2 , z = -3; cout << maximizeExpr(a, n, x, y, z) << endl; return 0;} // Java program to find the maximum value// of x*arr[i] + y*arr[j] + z*arr[k]import java.io.*; class GFG { // function to maximize the condition static int maximizeExpr(int a[], int n, int x, int y, int z) { // Traverse the whole array and compute // left maximum for every index. int L[] = new int[n]; L[0] = x * a[0]; for (int i = 1; i < n; i++) L[i] = Math.max(L[i - 1], x * a[i]); // Compute right maximum for every index. int R[] = new int[n]; R[n - 1] = z * a[n - 1]; for (int i = n - 2; i >= 0; i--) R[i] = Math.max(R[i + 1], z * a[i]); // Traverse through the whole array to // maximize the required expression. int ans = Integer.MIN_VALUE; for (int i = 0; i < n; i++) ans = Math.max(ans, L[i] + y * a[i] + R[i]); return ans; } // driver program to test the above function public static void main(String[] args) { int a[] = {-1, -2, -3, -4, -5}; int n = a.length; int x = 1, y = 2 , z = -3; System.out.println(maximizeExpr(a, n, x, y, z)); }}// This code is contributed by Prerna Saini # Python3 program to find# the maximum value of# x*arr[i] + y*arr[j] + z*arr[k]import sys # function to maximize# the conditiondef maximizeExpr(a, n, x, y, z): # Traverse the whole array # and compute left maximum # for every index. L = [0] * n L[0] = x * a[0] for i in range(1, n): L[i] = max(L[i - 1], x * a[i]) # Compute right maximum # for every index. R = [0] * n R[n - 1] = z * a[n - 1] for i in range(n - 2, -1, -1): R[i] = max(R[i + 1], z * a[i]) # Traverse through the whole # array to maximize the # required expression. ans = -sys.maxsize for i in range(0, n): ans = max(ans, L[i] + y * a[i] + R[i]) return ans # Driver Codea = [-1, -2, -3, -4, -5]n = len(a)x = 1y = 2z = -3print(maximizeExpr(a, n, x, y, z)) # This code is contributed# by Smitha // C# program to find the maximum value// of x*arr[i] + y*arr[j] + z*arr[k]using System; class GFG { // function to maximize the condition static int maximizeExpr(int []a, int n, int x, int y, int z) { // Traverse the whole array and // compute left maximum for every // index. int []L = new int[n]; L[0] = x * a[0]; for (int i = 1; i < n; i++) L[i] = Math.Max(L[i - 1], x * a[i]); // Compute right maximum for // every index. int []R = new int[n]; R[n - 1] = z * a[n - 1]; for (int i = n - 2; i >= 0; i--) R[i] = Math.Max(R[i + 1], z * a[i]); // Traverse through the whole array to // maximize the required expression. int ans = int.MinValue; for (int i = 0; i < n; i++) ans = Math.Max(ans, L[i] + y * a[i] + R[i]); return ans; } // driver program to test the // above function public static void Main() { int []a = {-1, -2, -3, -4, -5}; int n = a.Length; int x = 1, y = 2 , z = -3; Console.WriteLine( maximizeExpr(a, n, x, y, z)); }} // This code is contributed by vt_m. <?php// PHP program to find the// maximum value of// x*arr[i]+ y*arr[j] + z*arr[k] // function to maximize// the conditionfunction maximizeExpr($a, $n, $x, $y, $z){ // Traverse the whole array // and compute left maximum // for every index. $L = array(); $L[0] = $x * $a[0]; for ($i = 1; $i < $n; $i++) $L[$i] = max($L[$i - 1], $x * $a[$i]); // Compute right maximum // for every index. $R = array(); $R[$n - 1] = $z * $a[$n - 1]; for ($i = $n - 2; $i >= 0; $i--) $R[$i] = max($R[$i + 1], $z * $a[$i]); // Traverse through the whole // array to maximize the // required expression. $ans = PHP_INT_MIN; for ($i = 0; $i < $n; $i++) $ans = max($ans, $L[$i] + $y * $a[$i] + $R[$i]); return $ans;} // Driver Code$a = array(-1, -2, -3, -4, -5);$n = count($a);$x = 1; $y = 2 ; $z = -3;echo maximizeExpr($a, $n, $x, $y, $z); // This code is contributed by anuj_67.?> <script>// javascript program to find the maximum value// of x*arr[i] + y*arr[j] + z*arr[k] // function to maximize the condition function maximizeExpr(a , n , x , y , z) { // Traverse the whole array and compute // left maximum for every index. var L = Array(n).fill(0); L[0] = x * a[0]; for (i = 1; i < n; i++) L[i] = Math.max(L[i - 1], x * a[i]); // Compute right maximum for every index. var R = Array(n).fill(0); R[n - 1] = z * a[n - 1]; for (i = n - 2; i >= 0; i--) R[i] = Math.max(R[i + 1], z * a[i]); // Traverse through the whole array to // maximize the required expression. var ans = Number.MIN_VALUE; for (i = 0; i < n; i++) ans = Math.max(ans, L[i] + y * a[i] + R[i]); return ans; } // Driver program to test the above function var a = [ -1, -2, -3, -4, -5 ]; var n = a.length; var x = 1, y = 2, z = -3; document.write(maximizeExpr(a, n, x, y, z)); // This code is contributed by Rajput-Ji</script> Output : 12 Time complexity: O(n) Auxiliary Space: O(n) This article is contributed by Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m Smitha Dinesh Semwal Rajput-Ji simmytarika5 kk9826225 prefix Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Program to find sum of elements in a given array Reversal algorithm for array rotation Find duplicates in O(n) time and O(1) extra space | Set 1 Trapping Rain Water Next Greater Element Building Heap from Array Move all negative numbers to beginning and positive to end with constant extra space Count pairs with given sum Sliding Window Maximum (Maximum of all subarrays of size k)
[ { "code": null, "e": 24740, "s": 24712, "text": "\n12 Feb, 2022" }, { "code": null, "e": 24877, "s": 24740, "text": "Given an array of n integers, and three integers x, y and z. maximize the value of (x * a[i]) + (y * a[j]) + (z * a[k]) where i ≤ j ≤ k." }, { "code": null, "e": 24889, "s": 24877, "text": "Examples : " }, { "code": null, "e": 25175, "s": 24889, "text": "Input : arr[] = {-1, -2, -3, -4, -5} \n x = 1 \n y = 2 \n z = -3 \nOutput: 12\nExplanation: The maximized values is \n(1 * -1) + (2 * -1) + ( -3 * -5) = 12 \n\nInput: arr[] = {1, 2, 3, 4, 5} \n x = 1 \n y = 2 \n z = 3 \nOutput: 30 \n(1*5 + 2*5 + 3*5) = 30" }, { "code": null, "e": 25356, "s": 25175, "text": "A simple solution is to run three nested loops to iterate through all triplets. For every triplet, compute the required value and keep track of maximum and finally return the same." }, { "code": null, "e": 25983, "s": 25356, "text": "An efficient solution is to precompute values and stores them using extra space. The first key observation is i ≤ j ≤ k, so x*a[i] will always be the left maximum, and z*a[k] will always be the right maximum. Create a left array where we store the left maximums for every element. Create a right array where we store the right maximums for every element. Then for every element, calculate the maximum value of the function possible. For any index ind, the maximum at that position will always be (left[ind] + j * a[ind] + right[ind]), find the maximum of this value for every element in the array and that will be your answer." }, { "code": null, "e": 26035, "s": 25983, "text": "Below is the implementation of the above approach " }, { "code": null, "e": 26039, "s": 26035, "text": "C++" }, { "code": null, "e": 26044, "s": 26039, "text": "Java" }, { "code": null, "e": 26052, "s": 26044, "text": "Python3" }, { "code": null, "e": 26055, "s": 26052, "text": "C#" }, { "code": null, "e": 26059, "s": 26055, "text": "PHP" }, { "code": null, "e": 26070, "s": 26059, "text": "Javascript" }, { "code": "// CPP program to find the maximum value of// x*arr[i] + y*arr[j] + z*arr[k]#include <bits/stdc++.h>using namespace std; // function to maximize the conditionint maximizeExpr(int a[], int n, int x, int y, int z){ // Traverse the whole array and compute // left maximum for every index. int L[n]; L[0] = x * a[0]; for (int i = 1; i < n; i++) L[i] = max(L[i - 1], x * a[i]); // Compute right maximum for every index. int R[n]; R[n-1] = z * a[n-1]; for (int i = n - 2; i >= 0; i--) R[i] = max(R[i + 1], z * a[i]); // Traverse through the whole array to // maximize the required expression. int ans = INT_MIN; for (int i = 0; i < n; i++) ans = max(ans, L[i] + y * a[i] + R[i]); return ans;} // driver program to test the above functionint main(){ int a[] = {-1, -2, -3, -4, -5}; int n = sizeof(a)/sizeof(a[0]); int x = 1, y = 2 , z = -3; cout << maximizeExpr(a, n, x, y, z) << endl; return 0;}", "e": 27081, "s": 26070, "text": null }, { "code": "// Java program to find the maximum value// of x*arr[i] + y*arr[j] + z*arr[k]import java.io.*; class GFG { // function to maximize the condition static int maximizeExpr(int a[], int n, int x, int y, int z) { // Traverse the whole array and compute // left maximum for every index. int L[] = new int[n]; L[0] = x * a[0]; for (int i = 1; i < n; i++) L[i] = Math.max(L[i - 1], x * a[i]); // Compute right maximum for every index. int R[] = new int[n]; R[n - 1] = z * a[n - 1]; for (int i = n - 2; i >= 0; i--) R[i] = Math.max(R[i + 1], z * a[i]); // Traverse through the whole array to // maximize the required expression. int ans = Integer.MIN_VALUE; for (int i = 0; i < n; i++) ans = Math.max(ans, L[i] + y * a[i] + R[i]); return ans; } // driver program to test the above function public static void main(String[] args) { int a[] = {-1, -2, -3, -4, -5}; int n = a.length; int x = 1, y = 2 , z = -3; System.out.println(maximizeExpr(a, n, x, y, z)); }}// This code is contributed by Prerna Saini", "e": 28319, "s": 27081, "text": null }, { "code": "# Python3 program to find# the maximum value of# x*arr[i] + y*arr[j] + z*arr[k]import sys # function to maximize# the conditiondef maximizeExpr(a, n, x, y, z): # Traverse the whole array # and compute left maximum # for every index. L = [0] * n L[0] = x * a[0] for i in range(1, n): L[i] = max(L[i - 1], x * a[i]) # Compute right maximum # for every index. R = [0] * n R[n - 1] = z * a[n - 1] for i in range(n - 2, -1, -1): R[i] = max(R[i + 1], z * a[i]) # Traverse through the whole # array to maximize the # required expression. ans = -sys.maxsize for i in range(0, n): ans = max(ans, L[i] + y * a[i] + R[i]) return ans # Driver Codea = [-1, -2, -3, -4, -5]n = len(a)x = 1y = 2z = -3print(maximizeExpr(a, n, x, y, z)) # This code is contributed# by Smitha", "e": 29175, "s": 28319, "text": null }, { "code": "// C# program to find the maximum value// of x*arr[i] + y*arr[j] + z*arr[k]using System; class GFG { // function to maximize the condition static int maximizeExpr(int []a, int n, int x, int y, int z) { // Traverse the whole array and // compute left maximum for every // index. int []L = new int[n]; L[0] = x * a[0]; for (int i = 1; i < n; i++) L[i] = Math.Max(L[i - 1], x * a[i]); // Compute right maximum for // every index. int []R = new int[n]; R[n - 1] = z * a[n - 1]; for (int i = n - 2; i >= 0; i--) R[i] = Math.Max(R[i + 1], z * a[i]); // Traverse through the whole array to // maximize the required expression. int ans = int.MinValue; for (int i = 0; i < n; i++) ans = Math.Max(ans, L[i] + y * a[i] + R[i]); return ans; } // driver program to test the // above function public static void Main() { int []a = {-1, -2, -3, -4, -5}; int n = a.Length; int x = 1, y = 2 , z = -3; Console.WriteLine( maximizeExpr(a, n, x, y, z)); }} // This code is contributed by vt_m.", "e": 30438, "s": 29175, "text": null }, { "code": "<?php// PHP program to find the// maximum value of// x*arr[i]+ y*arr[j] + z*arr[k] // function to maximize// the conditionfunction maximizeExpr($a, $n, $x, $y, $z){ // Traverse the whole array // and compute left maximum // for every index. $L = array(); $L[0] = $x * $a[0]; for ($i = 1; $i < $n; $i++) $L[$i] = max($L[$i - 1], $x * $a[$i]); // Compute right maximum // for every index. $R = array(); $R[$n - 1] = $z * $a[$n - 1]; for ($i = $n - 2; $i >= 0; $i--) $R[$i] = max($R[$i + 1], $z * $a[$i]); // Traverse through the whole // array to maximize the // required expression. $ans = PHP_INT_MIN; for ($i = 0; $i < $n; $i++) $ans = max($ans, $L[$i] + $y * $a[$i] + $R[$i]); return $ans;} // Driver Code$a = array(-1, -2, -3, -4, -5);$n = count($a);$x = 1; $y = 2 ; $z = -3;echo maximizeExpr($a, $n, $x, $y, $z); // This code is contributed by anuj_67.?>", "e": 31455, "s": 30438, "text": null }, { "code": "<script>// javascript program to find the maximum value// of x*arr[i] + y*arr[j] + z*arr[k] // function to maximize the condition function maximizeExpr(a , n , x , y , z) { // Traverse the whole array and compute // left maximum for every index. var L = Array(n).fill(0); L[0] = x * a[0]; for (i = 1; i < n; i++) L[i] = Math.max(L[i - 1], x * a[i]); // Compute right maximum for every index. var R = Array(n).fill(0); R[n - 1] = z * a[n - 1]; for (i = n - 2; i >= 0; i--) R[i] = Math.max(R[i + 1], z * a[i]); // Traverse through the whole array to // maximize the required expression. var ans = Number.MIN_VALUE; for (i = 0; i < n; i++) ans = Math.max(ans, L[i] + y * a[i] + R[i]); return ans; } // Driver program to test the above function var a = [ -1, -2, -3, -4, -5 ]; var n = a.length; var x = 1, y = 2, z = -3; document.write(maximizeExpr(a, n, x, y, z)); // This code is contributed by Rajput-Ji</script>", "e": 32551, "s": 31455, "text": null }, { "code": null, "e": 32561, "s": 32551, "text": "Output : " }, { "code": null, "e": 32564, "s": 32561, "text": "12" }, { "code": null, "e": 32608, "s": 32564, "text": "Time complexity: O(n) Auxiliary Space: O(n)" }, { "code": null, "e": 33020, "s": 32608, "text": "This article is contributed by Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33025, "s": 33020, "text": "vt_m" }, { "code": null, "e": 33046, "s": 33025, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 33056, "s": 33046, "text": "Rajput-Ji" }, { "code": null, "e": 33069, "s": 33056, "text": "simmytarika5" }, { "code": null, "e": 33079, "s": 33069, "text": "kk9826225" }, { "code": null, "e": 33086, "s": 33079, "text": "prefix" }, { "code": null, "e": 33093, "s": 33086, "text": "Arrays" }, { "code": null, "e": 33100, "s": 33093, "text": "Arrays" }, { "code": null, "e": 33198, "s": 33100, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33207, "s": 33198, "text": "Comments" }, { "code": null, "e": 33220, "s": 33207, "text": "Old Comments" }, { "code": null, "e": 33245, "s": 33220, "text": "Window Sliding Technique" }, { "code": null, "e": 33294, "s": 33245, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 33332, "s": 33294, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 33390, "s": 33332, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 33410, "s": 33390, "text": "Trapping Rain Water" }, { "code": null, "e": 33431, "s": 33410, "text": "Next Greater Element" }, { "code": null, "e": 33456, "s": 33431, "text": "Building Heap from Array" }, { "code": null, "e": 33541, "s": 33456, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 33568, "s": 33541, "text": "Count pairs with given sum" } ]
Lollipop & Dumbbell Charts with Plotly | by Darío Weitz | Towards Data Science
A lollipop chart (LC) is a handy variation of a bar chart where the bar is replaced with a line and a dot at the end. They are two-dimensional with two axes: one axis shows categories or a time series, the other axis shows numerical values. Those numerical values are indicated by the position of the dot at the end of the line. A vertically oriented LC displays the categorical variable on the y-axis whilst a horizontally oriented LC displays it on the x-axis. Just like bar graphs, lollipop plots are used to make comparisons between different items or categories. They are also used for ranking or for showing trends over time. We compare only one numerical variable per item or category. They are not suitable for relationships, distribution, or composition analysis. LCs are preferred to bar charts when you have to display a large number of similar high values. In that case with a standard bar plot, you may get a cluttered chart and experience an optical effect called a Moiré pattern. Although they are equivalent to bar charts, this equivalence is only valid for standard bar charts; do not try to extend it to Stacked, Clustered, or Overlapping Bar Graphs. On the other hand, Dumbbell charts (DC) are an alternative to clustered bar charts and slope charts. Also known as DNA graphs, they indicate the change between two data points. Each point corresponds to a numerical value that is compared in the same dimension in a very direct way. They are very efficient when comparing differences, ranges, spread, or distance between points. They are used to make comparisons between categories or to observe a trend between two-time intervals. Figure 0 shows a schematic vertically oriented Dumbbell chart. Professional data scientists should be familiar with different statistical measures used to describe the observations of their studies or projects. Common measures of central tendency with which they should be quite familiar are the mean, median, and mode. The mean of a dataset is found by adding all numbers in the dataset and then dividing by the number of values in it. The median is the middle value when the dataset is sorted from least to greatest. Mode is a measure of central tendency representing the value that occurs most frequently in the dataset. As there are a lot of external factors that limit the use of mean, the median is widely used, particularly in skewed distributions. The median is considered robust against outliers, while the mean is considered sensitive to outliers. Remember that an outlier (anomalous value) is a piece of data that is very different from all the others in the dataset and does not seem to fit the same pattern. The median generally gives a more appropriate idea of the data distribution. Plotly Express, an object-oriented interface to figure creation, was released in 2019. It is a high-level wrapper for Plotly.py that includes functions to plot standard 2D & 3D charts and choropleth maps. Fully compatible with the rest of the Plotly ecosystem, is an excellent tool for the rapid development of exploratory charts. Plotly provides a group of classes called graph objects that may be used to construct figures. The plotly.graph_objects module contains a hierarchy of Python classes. Figure is a primary class. Figure has a data attribute and a layout attribute. The data attribute has more than 40 objects, each one refers to a specific type of chart (trace) with its corresponding parameters. The layout attribute specifies the properties of the figure as a whole (axes, title, shapes, legends, etc.). We worked with a public dataset downloaded from the community GitHub [1]. The dataset contains records related to world wealth and income. We want to know which measurement of central tendency is the most appropriate for analyzing the dataset. First, we imported Plotly Express as px, the module plotly.graph_objects as go, the Pandas library as pd and converted our csv file into a dataframe: import pandas as pdimport plotly.express as pximport plotly.graph_objects as godf_Ww = pd.read_csv(path + 'WorldWealth.csv', index_col = False, header = 0, sep = ';', engine='python') The way the data is stored in the file is not the way we need for the drawing. As every column is stored as an object type, we need to convert the columns Median_Wealth and Mean_Wealth to integer: df_Ww['Mean_Wealth'] = df_Ww['Mean_Wealth'].str.replace( ',', '').astype(str).astype(int)df_Ww['Median_Wealth'] = df_Ww['Median_Wealth'].str.replace( ',', '').astype(str).astype(int)types = df_Ww.dtypes The screenshot below shows the first ten records of the transformed dataframe: After these three lines of code, we are ready to draw lollipop charts. We used .add_trace(go.Scatter( to draw the points and .add_shape(type=’line’ to draw the corresponding lines. We selected to draw a horizontally oriented LC by displaying the categorical variable [“Country”] on the y-axis. We used mode = ‘markers’ to choose a dot marker. Standalone lines are added to the figure using fig1.add_shape(type='line'. Note that we used the counter variable of the for loop to set y0 and y1 values. We updated the chart with update.layout: set the title and the size of the font. We set the template= ‘seaborn+ygridoff’: in this case, the resulting template is computed by merging the collection of two registered templates (seaborn & ygridoff). We defined the figure dimensions with width and height. Then we updated the x-axis (title and range). We saved the chart as a static png file and, finally, we drew the chart. First we drew a ranking of the top 15 countries according to their median wealth: df_WwT = df_Ww.sort_values(by = ['Median_Wealth'], ascending = False).iloc[0:15].reset_index()fig1 = go.Figure()# Draw pointsfig1.add_trace(go.Scatter(x = df_WwT["Median_Wealth"], y = df_WwT["Country"], mode = 'markers', marker_color ='darkblue', marker_size = 10))# Draw linesfor i in range(0, len(df_WwT)): fig1.add_shape(type='line', x0 = 0, y0 = i, x1 = df_WwT["Median_Wealth"][i], y1 = i, line=dict(color='crimson', width = 3))# Set titlefig1.update_layout(title_text = "Median Wealth (U$S) Top 15 Countries", title_font_size = 30)# Set x-axes rangefig1.update_xaxes(title = 'Median Wealth' , range=[0, 250000])fig1.write_image(path + "figlollipop1.png")fig1.show() Then we drew a ranking of the bottom 15 countries according to their mean wealth: df_WwB = df_Ww.sort_values(by = ['Mean_Wealth']).iloc[0:15].reset_index()fig2 = go.Figure()# Draw Pointsfig2.add_trace(go.Scatter(x = df_WwB["Mean_Wealth"], y = df_WwB["Country"], mode = 'markers', marker_color ='darkorange', marker_size = 10)# Draw Linesfor i in range(0, len(df_WwB)): fig2.add_shape(type='line', x0 = 0, y0 = i, x1 = df_WwB["Mean_Wealth"][i], y1 = i, line=dict(color='crimson', width = 3))# Set titlefig2.update_layout(title_text = "Mean Wealth (U$S) Bottom 15 Countries", title_font_size = 30)# Set x-axes rangefig2.update_xaxes(title = 'Mean Wealth', range=[0, 2000])fig2.write_image(path + "figlollipop2.png")fig2.show() Then we designed two horizontally oriented Dumbbell Charts to compare Mean Wealth against Median Wealth for the 15 Top countries and the 15 Bottom countries. Now we need two .add_trace(go.Scatter(: one for Mean Wealth dots and another for Median Wealth dots. Regarding to .add_shape(type=’line’ we used: df_WwT[“Median_Wealth”][i] for x0 and df_WwT[“Mean_Wealth”][i] for x1. fig3= go.Figure()fig3.add_trace(go.Scatter(x = df_WwT["Median_Wealth"], y = df_WwT["Country"], mode = 'markers', marker_color = 'darkblue', marker_size = 10, name = 'Median'))fig3.add_trace(go.Scatter(x = df_WwT["Mean_Wealth"], y = df_WwT["Country"], mode = 'markers', marker_color = 'darkorange', marker_size = 10, name = 'Mean'))for i in range(0, len(df_WwT)): fig3.add_shape(type='line', x0 = df_WwT["Median_Wealth"][i], y0 = i, x1 = df_WwT["Mean_Wealth"][i], y1 = i, line=dict(color='crimson', width = 3))fig3.update_layout(title_text = "Mean vs Median (U$S) Top 15 Countries", title_font_size = 30)fig3.update_xaxes(range=[0, 600000])fig3.write_image(path + "figdumbbell1.png")fig3.show() The code for Fig.4 is the same that for Fig.3 except that we used df_WwB instead of df_WwT. When you have a normally distributed sample you can use the mean or the median as your measure of central tendency. In any symmetrical distribution the mean, median, and mode are equal. This is not the case with our data (both, top 15 countries and bottom 15 countries): the mean is always greater than the median. It is a clear indication of right-skewed data. In these situations, the median is generally considered to be the best measure of central tendency. The median is not as strongly influenced by the skewed values of very wealthy people and provides the best central location for our data. The differences shown in our Dumbbell charts confirm this assumption. Used exactly in the same situation as a standard bar chart, lollipop charts encode numerical values in the same way: the length of the lines and the location of the dots at the end of the lines are equivalent to the length or height of horizontal or vertical rectangular bars. Lollipop Charts are preferred to bar charts when you are dealing with a large number of similar numerical values. Dumbbell charts are simple graphs that quickly and directly show differences, changes, ranges, and similarities. They allow a significant amount of information to be coded into an easy-to-understand diagram. If you find this article of interest, please read my previous (https://medium.com/@dar.wtz): Diverging Bars, Why & How, Storytelling with Divergences towardsdatascience.com Slope Charts, Why & How, Storytelling with Slopes
[ { "code": null, "e": 634, "s": 171, "text": "A lollipop chart (LC) is a handy variation of a bar chart where the bar is replaced with a line and a dot at the end. They are two-dimensional with two axes: one axis shows categories or a time series, the other axis shows numerical values. Those numerical values are indicated by the position of the dot at the end of the line. A vertically oriented LC displays the categorical variable on the y-axis whilst a horizontally oriented LC displays it on the x-axis." }, { "code": null, "e": 944, "s": 634, "text": "Just like bar graphs, lollipop plots are used to make comparisons between different items or categories. They are also used for ranking or for showing trends over time. We compare only one numerical variable per item or category. They are not suitable for relationships, distribution, or composition analysis." }, { "code": null, "e": 1341, "s": 944, "text": "LCs are preferred to bar charts when you have to display a large number of similar high values. In that case with a standard bar plot, you may get a cluttered chart and experience an optical effect called a Moiré pattern. Although they are equivalent to bar charts, this equivalence is only valid for standard bar charts; do not try to extend it to Stacked, Clustered, or Overlapping Bar Graphs." }, { "code": null, "e": 1623, "s": 1341, "text": "On the other hand, Dumbbell charts (DC) are an alternative to clustered bar charts and slope charts. Also known as DNA graphs, they indicate the change between two data points. Each point corresponds to a numerical value that is compared in the same dimension in a very direct way." }, { "code": null, "e": 1822, "s": 1623, "text": "They are very efficient when comparing differences, ranges, spread, or distance between points. They are used to make comparisons between categories or to observe a trend between two-time intervals." }, { "code": null, "e": 1885, "s": 1822, "text": "Figure 0 shows a schematic vertically oriented Dumbbell chart." }, { "code": null, "e": 2142, "s": 1885, "text": "Professional data scientists should be familiar with different statistical measures used to describe the observations of their studies or projects. Common measures of central tendency with which they should be quite familiar are the mean, median, and mode." }, { "code": null, "e": 2446, "s": 2142, "text": "The mean of a dataset is found by adding all numbers in the dataset and then dividing by the number of values in it. The median is the middle value when the dataset is sorted from least to greatest. Mode is a measure of central tendency representing the value that occurs most frequently in the dataset." }, { "code": null, "e": 2920, "s": 2446, "text": "As there are a lot of external factors that limit the use of mean, the median is widely used, particularly in skewed distributions. The median is considered robust against outliers, while the mean is considered sensitive to outliers. Remember that an outlier (anomalous value) is a piece of data that is very different from all the others in the dataset and does not seem to fit the same pattern. The median generally gives a more appropriate idea of the data distribution." }, { "code": null, "e": 3251, "s": 2920, "text": "Plotly Express, an object-oriented interface to figure creation, was released in 2019. It is a high-level wrapper for Plotly.py that includes functions to plot standard 2D & 3D charts and choropleth maps. Fully compatible with the rest of the Plotly ecosystem, is an excellent tool for the rapid development of exploratory charts." }, { "code": null, "e": 3738, "s": 3251, "text": "Plotly provides a group of classes called graph objects that may be used to construct figures. The plotly.graph_objects module contains a hierarchy of Python classes. Figure is a primary class. Figure has a data attribute and a layout attribute. The data attribute has more than 40 objects, each one refers to a specific type of chart (trace) with its corresponding parameters. The layout attribute specifies the properties of the figure as a whole (axes, title, shapes, legends, etc.)." }, { "code": null, "e": 3982, "s": 3738, "text": "We worked with a public dataset downloaded from the community GitHub [1]. The dataset contains records related to world wealth and income. We want to know which measurement of central tendency is the most appropriate for analyzing the dataset." }, { "code": null, "e": 4132, "s": 3982, "text": "First, we imported Plotly Express as px, the module plotly.graph_objects as go, the Pandas library as pd and converted our csv file into a dataframe:" }, { "code": null, "e": 4355, "s": 4132, "text": "import pandas as pdimport plotly.express as pximport plotly.graph_objects as godf_Ww = pd.read_csv(path + 'WorldWealth.csv', index_col = False, header = 0, sep = ';', engine='python')" }, { "code": null, "e": 4552, "s": 4355, "text": "The way the data is stored in the file is not the way we need for the drawing. As every column is stored as an object type, we need to convert the columns Median_Wealth and Mean_Wealth to integer:" }, { "code": null, "e": 4817, "s": 4552, "text": "df_Ww['Mean_Wealth'] = df_Ww['Mean_Wealth'].str.replace( ',', '').astype(str).astype(int)df_Ww['Median_Wealth'] = df_Ww['Median_Wealth'].str.replace( ',', '').astype(str).astype(int)types = df_Ww.dtypes" }, { "code": null, "e": 4896, "s": 4817, "text": "The screenshot below shows the first ten records of the transformed dataframe:" }, { "code": null, "e": 4967, "s": 4896, "text": "After these three lines of code, we are ready to draw lollipop charts." }, { "code": null, "e": 5239, "s": 4967, "text": "We used .add_trace(go.Scatter( to draw the points and .add_shape(type=’line’ to draw the corresponding lines. We selected to draw a horizontally oriented LC by displaying the categorical variable [“Country”] on the y-axis. We used mode = ‘markers’ to choose a dot marker." }, { "code": null, "e": 5394, "s": 5239, "text": "Standalone lines are added to the figure using fig1.add_shape(type='line'. Note that we used the counter variable of the for loop to set y0 and y1 values." }, { "code": null, "e": 5816, "s": 5394, "text": "We updated the chart with update.layout: set the title and the size of the font. We set the template= ‘seaborn+ygridoff’: in this case, the resulting template is computed by merging the collection of two registered templates (seaborn & ygridoff). We defined the figure dimensions with width and height. Then we updated the x-axis (title and range). We saved the chart as a static png file and, finally, we drew the chart." }, { "code": null, "e": 5898, "s": 5816, "text": "First we drew a ranking of the top 15 countries according to their median wealth:" }, { "code": null, "e": 6857, "s": 5898, "text": "df_WwT = df_Ww.sort_values(by = ['Median_Wealth'], ascending = False).iloc[0:15].reset_index()fig1 = go.Figure()# Draw pointsfig1.add_trace(go.Scatter(x = df_WwT[\"Median_Wealth\"], y = df_WwT[\"Country\"], mode = 'markers', marker_color ='darkblue', marker_size = 10))# Draw linesfor i in range(0, len(df_WwT)): fig1.add_shape(type='line', x0 = 0, y0 = i, x1 = df_WwT[\"Median_Wealth\"][i], y1 = i, line=dict(color='crimson', width = 3))# Set titlefig1.update_layout(title_text = \"Median Wealth (U$S) Top 15 Countries\", title_font_size = 30)# Set x-axes rangefig1.update_xaxes(title = 'Median Wealth' , range=[0, 250000])fig1.write_image(path + \"figlollipop1.png\")fig1.show()" }, { "code": null, "e": 6939, "s": 6857, "text": "Then we drew a ranking of the bottom 15 countries according to their mean wealth:" }, { "code": null, "e": 7870, "s": 6939, "text": "df_WwB = df_Ww.sort_values(by = ['Mean_Wealth']).iloc[0:15].reset_index()fig2 = go.Figure()# Draw Pointsfig2.add_trace(go.Scatter(x = df_WwB[\"Mean_Wealth\"], y = df_WwB[\"Country\"], mode = 'markers', marker_color ='darkorange', marker_size = 10)# Draw Linesfor i in range(0, len(df_WwB)): fig2.add_shape(type='line', x0 = 0, y0 = i, x1 = df_WwB[\"Mean_Wealth\"][i], y1 = i, line=dict(color='crimson', width = 3))# Set titlefig2.update_layout(title_text = \"Mean Wealth (U$S) Bottom 15 Countries\", title_font_size = 30)# Set x-axes rangefig2.update_xaxes(title = 'Mean Wealth', range=[0, 2000])fig2.write_image(path + \"figlollipop2.png\")fig2.show()" }, { "code": null, "e": 8245, "s": 7870, "text": "Then we designed two horizontally oriented Dumbbell Charts to compare Mean Wealth against Median Wealth for the 15 Top countries and the 15 Bottom countries. Now we need two .add_trace(go.Scatter(: one for Mean Wealth dots and another for Median Wealth dots. Regarding to .add_shape(type=’line’ we used: df_WwT[“Median_Wealth”][i] for x0 and df_WwT[“Mean_Wealth”][i] for x1." }, { "code": null, "e": 9389, "s": 8245, "text": "fig3= go.Figure()fig3.add_trace(go.Scatter(x = df_WwT[\"Median_Wealth\"], y = df_WwT[\"Country\"], mode = 'markers', marker_color = 'darkblue', marker_size = 10, name = 'Median'))fig3.add_trace(go.Scatter(x = df_WwT[\"Mean_Wealth\"], y = df_WwT[\"Country\"], mode = 'markers', marker_color = 'darkorange', marker_size = 10, name = 'Mean'))for i in range(0, len(df_WwT)): fig3.add_shape(type='line', x0 = df_WwT[\"Median_Wealth\"][i], y0 = i, x1 = df_WwT[\"Mean_Wealth\"][i], y1 = i, line=dict(color='crimson', width = 3))fig3.update_layout(title_text = \"Mean vs Median (U$S) Top 15 Countries\", title_font_size = 30)fig3.update_xaxes(range=[0, 600000])fig3.write_image(path + \"figdumbbell1.png\")fig3.show()" }, { "code": null, "e": 9481, "s": 9389, "text": "The code for Fig.4 is the same that for Fig.3 except that we used df_WwB instead of df_WwT." }, { "code": null, "e": 10151, "s": 9481, "text": "When you have a normally distributed sample you can use the mean or the median as your measure of central tendency. In any symmetrical distribution the mean, median, and mode are equal. This is not the case with our data (both, top 15 countries and bottom 15 countries): the mean is always greater than the median. It is a clear indication of right-skewed data. In these situations, the median is generally considered to be the best measure of central tendency. The median is not as strongly influenced by the skewed values of very wealthy people and provides the best central location for our data. The differences shown in our Dumbbell charts confirm this assumption." }, { "code": null, "e": 10750, "s": 10151, "text": "Used exactly in the same situation as a standard bar chart, lollipop charts encode numerical values in the same way: the length of the lines and the location of the dots at the end of the lines are equivalent to the length or height of horizontal or vertical rectangular bars. Lollipop Charts are preferred to bar charts when you are dealing with a large number of similar numerical values. Dumbbell charts are simple graphs that quickly and directly show differences, changes, ranges, and similarities. They allow a significant amount of information to be coded into an easy-to-understand diagram." }, { "code": null, "e": 10843, "s": 10750, "text": "If you find this article of interest, please read my previous (https://medium.com/@dar.wtz):" }, { "code": null, "e": 10900, "s": 10843, "text": "Diverging Bars, Why & How, Storytelling with Divergences" }, { "code": null, "e": 10923, "s": 10900, "text": "towardsdatascience.com" } ]
How to analyse 100 GB of data on your laptop with Python | by Jovan Veljanoski | Towards Data Science
Many organizations are trying to gather and utilise as much data as possible to improve on how they run their business, increase revenue, or how they impact the world around them. Therefore it is becoming increasingly common for data scientists to face 50GB or even 500GB sized datasets. Now, these kind of datasets are a bit... uncomfortable to use. They are small enough to fit into the hard-drive of your everyday laptop, but way to big to fit in RAM. Thus, they are already tricky to open and inspect, let alone to explore or analyse. There are 3 strategies commonly employed when working with such datasets. The first one is to sub-sample the data. The drawback here is obvious: one may miss key insights by not looking at the relevant portions, or even worse, misinterpret the story the data it telling by not looking at all of it. The next strategy is to use distributed computing. While this is a valid approach for some cases, it comes with the significant overhead of managing and maintaining a cluster. Imagine having to set up a cluster for a dataset that is just out of RAM reach, like in the 30–50 GB range. It seems like an overkill to me. Alternatively, one can rent a single strong cloud instance with as much memory as required to work with the data in question. For example, AWS offers instances with Terabytes of RAM. In this case you still have to manage cloud data buckets, wait for data transfer from bucket to instance every time the instance starts, handle compliance issues that come with putting data on the cloud, and deal with all the inconvenience that come with working on a remote machine. Not to mention the costs, which although start low, tend to pile up as time goes on. In this article I will show you a new approach: a faster, more secure, and just overall more convenient way to do data science using data of almost arbitrary size, as long as it can fit on the hard-drive of your laptop, desktop or server. Vaex is an open-source DataFrame library which enables the visualisation, exploration, analysis and even machine learning on tabular datasets that are as large as your hard-drive. To do this, Vaex employs concepts such as memory mapping, efficient out-of-core algorithms and lazy evaluations. All of this is wrapped in a familiar Pandas-like API, so anyone can get started right away. To illustrate this concepts, let us do a simple exploratory data analysis on a dataset that is far to large to fit into RAM of a typical laptop. In this article we will use the New York City (NYC) Taxi dataset, which contains information on over 1 billion taxi trips conducted between 2009 and 2015 by the iconic Yellow Taxis. The data can be downloaded from this website, and comes in CSV format. The complete analysis can be viewed separately in this Jupyter notebook. The first step is to convert the data into a memory mappable file format, such as Apache Arrow, Apache Parquet, or HDF5. An example of how to do convert CSV data to HDF5 can be found in here. Once the data is in a memory mappable format, opening it with Vaex is instant (0.052 seconds!), despite its size of over 100GB on disk: Why is it so fast? When you open a memory mapped file with Vaex, there is actually no data reading going on. Vaex only reads the file metadata, such as the location of the data on disk, the data structure (number of rows, number of columns, column names and types), the file description and so on. So what if we want to inspect or interact with the data? Opening a dataset results in a standard DataFrame and inspecting it is as fast as it is trivial: Once again, notice that the cell execution time is crazy short. This is because displaying a Vaex DataFrame or column requires only the first and last 5 rows to be read from disk. This leads us to another important point: Vaex will only go over the entire dataset when it has to, and it will try to do it with as few passes over the data as possible. Anyway, let’s begin by cleaning this dataset from extreme outliers, or erroneous data inputs. A good way to start is to get a high level overview of the data using the describe method, which shows the number of samples, the number of missing values and the data type for each column. If the data type of a column is numerical, the mean, standard deviation, as well as the minimum and maximum values will also be shown. All of these stats are computed with a single pass over the data. The describe method nicely illustrates the power and efficiency of Vaex: all of these statistics were computed in under 3 minutes on my MacBook Pro (15", 2018, 2.6GHz Intel Core i7, 32GB RAM). Other libraries or methods would require either distributed computing or a cloud instance with over 100GB to preform the same computations. With Vaex, all you need is the data, and your laptop with only a few GB of RAM to spare. Looking at the output of describe, it is easy to notice that the data contains some serious outliers. First, let’s start by examining the pick-up locations. Easiest way to remove outliers is to simply plot the pick-up and drop-off locations, and visually define the area of NYC on which we want to focus our analysis. Since we are working with such a large dataset, histograms are the most effective visualisations. Creating and displaying histograms and heatmaps with Vaex is so fast, such plots can be made interactive! df.plot_widget(df.pickup_longitude, df.pickup_latitude, shape=512, limits='minmax', f='log1p', colormap='plasma') Once we interactively decide on which area of NYC we want to focus, we can simply create a filtered DataFrame: The cool thing about the code block above is that it requires negligible amount of memory to execute! When filtering a Vaex DataFrame no copies of the data are made. Instead only a reference to the original object is created, on which a binary mask is applied. The mask selects which rows are displayed and used for future calculations. This saves us 100GB of RAM that would be needed if the data were to be copied, as done by many of the standard data science tools today. Now, let’s examine the passenger_count column. The maximum number of passengers recorded in a single taxi trip is 255, which seems a little extreme. Let’s count the number of trips per number of passengers. This is easily done with the value_counts method: From the above figure we can see that trips with more than 6 passengers are likely to be either rare outliers or just erroneous data inputs. There is also a large number of trips with 0 passengers. Since at this time we do not understand whether these are legitimate trips, let us filter them out as well. Let’s do a similar exercise with the trip distance. As this is a continuous variable, we can plot the distribution of trip distances. Looking at the minimum (negative!) and maximum (further than Mars!) distance, let’s plot a histogram with a more sensible range. From the plot above we can see that number of trips decreases with increasing distance. At a distance of ~100 miles, there is a large drop in the distribution. For now, we will use this as the cut-off point to eliminate extreme outliers based on the trip distance: The presence of extreme outliers in the trip distance columns serves as motivation to investigate the trip durations and average speed of the taxis. These features are not readily available in the dataset, but are trivial to compute: The code block above requires zero memory and takes no time to execute! This is because the code results in the creation of virtual columns. These columns just house the mathematical expressions, and are evaluated only when required. Otherwise, virtual columns behave just as any other regular column. Note that other standard libraries would require 10s of GB of RAM for the same operations. Alright, so let’s plot the distribution of trip durations: From the above plot we see that 95% of all taxi trips take less than 30 minutes to reach their destination, although some trips can take more then 4–5 hours. Can you imagine being stuck in a taxi for over 3 hours in New York City? Anyway, let’s be open minded and consider all trips that last less than 3 hours in total: Now let’s investigate the mean speed of the taxis, while also choosing a sensible range for the data limits: Based on where the distribution flattens out, we can deduce that a sensible average taxi speed is in the range between 1 and 60 miles per hour, and thus we can update our filtered DataFrame: Lets shift the focus to the cost of the taxi trips. From the output of the describe method, we can see that there are some crazy outliers in the fare_amount, total_amount, and tip_amount columns. For starters, no value in any of these columns should be negative. On the opposite side of the spectrum, the numbers suggest that some lucky driver almost became a millionaire with a single taxi ride. Let’s look at the distributions of these quantities, but in a relatively sensible range: We see that all three of the above distributions have rather long tails. It is possible that some values in the tails are legit, while others are perhaps erroneous data inputs. In any case, let’s be conservative for now and consider only rides that had fare_amount, total_amount, and tip_amount less than $200. We also require that the fare_amount, total_amount values be larger than $0. Finally, after all initial cleaning of the data, let’s see how many taxi trips are left for our analysis: We are left with over 1.1 billion trips! That is plenty of data to get some valuable insights into the world of taxi travel. Assume we are a prospective taxi driver, or a manager of a taxi company, and are interested in using this dataset to learn how to maximize our profits, minimize our costs, or simply just improve our work life. Let’s start by finding out the locations for picking up passengers that, on average, would lead to the best earnings. Naively, we can just plot a heatmap of the pick-up locations colour-coded by the average fare amount, and look at the hotspots. Taxi drivers have costs on their own, however. For example, they have to pay for fuel. Hence, taking a passenger somewhere far away might result in a larger fare amount, but it would also mean larger fuel consumption, and time lost. In addition, it may not be that easy to find a passenger from that remote location to fare somewhere to the city centre, and thus driving back without a passenger might be costly. One way to account for this is to colour-code a heatmap by the mean of the ratio between the fare amount and trip distance. Let’s consider these two approaches: In the naive case, when we just care about getting a maximum fare for the service provided, the best regions to pick up passengers from are the NYC airports, and along the main avenues such as the Van Wyck Expressway, and the Long Island Expressway. When we take the distance travelled into account, we get a slightly different picture. The Van Wyck Expressway, and the Long Island Expressway avenues, as well as the airports are still a good place for picking up passengers, but they are a lot less prominent on the map. However, some bright new hotspots appear on the west side of the Hudson river that seem quite profitable. Being a taxi driver can be quite a flexible job. To better leverage that flexibility it would be useful to know when driving is most profitable, in addition to where one should be lurking. To answer this question, let’s produce a plot showing the mean ratio of fare over trip distance for every day and hour of the day: The figure above makes sense: the best earnings happen during rush-hour, especially around noon, during the working days of the week. As a taxi driver, a fraction of our earnings go to the taxi company, so we might be interested in which day and at which times customers tip the most. So let’s produce a similar plot, this time displaying the mean tip percentage: The above plot is interesting. It tells us that passengers tip their taxi drivers the most between 7–10 o’clock in the morning, and in the evening in the early part of the week. Do not expect large tips if you pick up passengers at 3 or 4am. Combining the insights from the last two plots, a nice time to work is 8–10 o’clock in the morning: one would get both a good fare per mile, and a good tip. In the earlier part of this article we briefly focused on the trip_distance column, and while cleaning it from outliers we kept all trips with a value lower than 100 miles. That is still a rather large cut-off value, especially given that the Yellow Taxi company operates primarily over Manhattan. The trip_distance column describes the distance the taxi travelled between the pick-up and the drop-off location. However, one can often take different routes with different distances between two exact pick-up and drop-off locations, for example to avoid traffic jams or roadworks. Thus as a counterpart to the trip_distance column, let’s calculate the shortest possible distance between a pick-up and drop-off locations, which we call arc_distance: The formula for the arc_distance calculation is quite involved, it contains much trigonometry and arithmetic, and can be computationally expensive especially when we are working with large datasets. If the expression or function is written only using Python operations and methods from the Numpy package, Vaex will compute it in parallel using all the cores of your machine. In addition to this, Vaex supports Just-In-Time compilation via Numba (using LLVM) or Pythran (acceleration via C++), giving better performance. If you happen to have a NVIDIA graphics card, you can use CUDA via the jit_cuda method to get even faster performance. Anyway, let’s plot the distributions of trip_distance and arc_distance: It is interesting to see that the arc_distance never exceeds 21 miles, but the distance the taxi actually travelled can be 5 times as large. In fact, there are millions of taxi trips for which the drop-off location was within 100 meters (0.06 miles) from the pickup-location! The dataset that we are using today spans across 7 years. It can be interesting to see how some quantities of interest evolved over that time. With Vaex, we can do fast out-of-core group-by and aggregation operations. Let’s explore how the fares, and trip distances evolved through the 7 years: In the above cell block we do a group-by operation followed by 8 aggregations, 2 of which are on virtual columns. The above cell block took less than 2 minutes to execute on my laptop. This is rather impressive, given that the data we are using contains over 1 billion samples. Anyway, let’s check out the results. Here is how the cost of riding a cab evolved over the years: We see that the taxi fares, as well as the tips increase as the years go by. Now let’s look at the mean trip_distance and arc_distance the taxis travelled as a function of year: The figure above shows that there is a small increase of both the trip_distance and arc_distance meaning that, on average, people tend to travel a little bit further each year. Before the end of our trip, let’s make one more stop and investigate how passengers pay for their rides. The dataset contains the payment_type column, so let’s see the values it contains: From the dataset documentation, we can see that there are only 6 valid entries for this column: 1 = credit card payment 2 = cash payment 3 = no charge 4 = dispute 5 = Unknown 6 =Voided trip Thus, we can simply map the entries in the payment_type column to integers: Now we can group-by the data per year, and see how the habits of the New Yorkers changed when it comes to taxi ride payments: We see that as time goes on, the card payments slowly became more frequent than cash payments. We truly live in a digital age! Note that in the above code block, once we aggregated the data, the small Vaex DataFrame can easily be converted to a Pandas DataFrame, which we conveniently pass to Seaborn. Not trying to reinvent the wheel here. Finally, let’s see whether the payment method depends on the time of day or the day of week by plotting the ratio between the number of cash to card payments. To do this, we will first create a filter which selects only the rides paid for by either cash or card. The next step is one of my favourite Vaex features: aggregations with selections. Other libraries require aggregations to be done on separately filtered DataFrames for each payment method that are later merged into one. With Vaex on the other hand we can do this in one step by providing the selections within the aggregation function. This is quite convenient, and requires just one pass over the data, giving us a better performance. After that, we can just plot the resulting DataFrame in a standard manner: Looking at the plot above we can notice a similar pattern to the one showing the tip percentage as a function of day of week and time of day. From these two plots, the data would suggest that passengers that pay by card tend to tip more than those that pay by cash. To find out whether this is indeed true, I would like to invite you to try and figure it out, since now you have the knowledge, the tools and the data! You can also look at this Jupyter notebook for some extra hints. I hope this article was a useful introduction to Vaex, and it will help you alleviate some of the “uncomfortable data” issues that you may be facing, at least when it comes to tabular datasets. If you are interested in exploring the dataset used in this article, it can be used straight from S3 with Vaex. See the full Jupyter notebook to find out how to do this. With Vaex, one can go over a billion rows and calculate all sort of statistics, aggregations and produce informative plots in mere seconds, right from the comfort of your own laptop. It is free and open-source, and I hope you will give it a shot! Happy data sciencing! The exploratory data analysis presented in this article is based on an early Vaex demo created by Maarten Breddels. Please check out our live demo from PyData London 2019 below:
[ { "code": null, "e": 459, "s": 171, "text": "Many organizations are trying to gather and utilise as much data as possible to improve on how they run their business, increase revenue, or how they impact the world around them. Therefore it is becoming increasingly common for data scientists to face 50GB or even 500GB sized datasets." }, { "code": null, "e": 710, "s": 459, "text": "Now, these kind of datasets are a bit... uncomfortable to use. They are small enough to fit into the hard-drive of your everyday laptop, but way to big to fit in RAM. Thus, they are already tricky to open and inspect, let alone to explore or analyse." }, { "code": null, "e": 1878, "s": 710, "text": "There are 3 strategies commonly employed when working with such datasets. The first one is to sub-sample the data. The drawback here is obvious: one may miss key insights by not looking at the relevant portions, or even worse, misinterpret the story the data it telling by not looking at all of it. The next strategy is to use distributed computing. While this is a valid approach for some cases, it comes with the significant overhead of managing and maintaining a cluster. Imagine having to set up a cluster for a dataset that is just out of RAM reach, like in the 30–50 GB range. It seems like an overkill to me. Alternatively, one can rent a single strong cloud instance with as much memory as required to work with the data in question. For example, AWS offers instances with Terabytes of RAM. In this case you still have to manage cloud data buckets, wait for data transfer from bucket to instance every time the instance starts, handle compliance issues that come with putting data on the cloud, and deal with all the inconvenience that come with working on a remote machine. Not to mention the costs, which although start low, tend to pile up as time goes on." }, { "code": null, "e": 2117, "s": 1878, "text": "In this article I will show you a new approach: a faster, more secure, and just overall more convenient way to do data science using data of almost arbitrary size, as long as it can fit on the hard-drive of your laptop, desktop or server." }, { "code": null, "e": 2502, "s": 2117, "text": "Vaex is an open-source DataFrame library which enables the visualisation, exploration, analysis and even machine learning on tabular datasets that are as large as your hard-drive. To do this, Vaex employs concepts such as memory mapping, efficient out-of-core algorithms and lazy evaluations. All of this is wrapped in a familiar Pandas-like API, so anyone can get started right away." }, { "code": null, "e": 2973, "s": 2502, "text": "To illustrate this concepts, let us do a simple exploratory data analysis on a dataset that is far to large to fit into RAM of a typical laptop. In this article we will use the New York City (NYC) Taxi dataset, which contains information on over 1 billion taxi trips conducted between 2009 and 2015 by the iconic Yellow Taxis. The data can be downloaded from this website, and comes in CSV format. The complete analysis can be viewed separately in this Jupyter notebook." }, { "code": null, "e": 3301, "s": 2973, "text": "The first step is to convert the data into a memory mappable file format, such as Apache Arrow, Apache Parquet, or HDF5. An example of how to do convert CSV data to HDF5 can be found in here. Once the data is in a memory mappable format, opening it with Vaex is instant (0.052 seconds!), despite its size of over 100GB on disk:" }, { "code": null, "e": 3753, "s": 3301, "text": "Why is it so fast? When you open a memory mapped file with Vaex, there is actually no data reading going on. Vaex only reads the file metadata, such as the location of the data on disk, the data structure (number of rows, number of columns, column names and types), the file description and so on. So what if we want to inspect or interact with the data? Opening a dataset results in a standard DataFrame and inspecting it is as fast as it is trivial:" }, { "code": null, "e": 4104, "s": 3753, "text": "Once again, notice that the cell execution time is crazy short. This is because displaying a Vaex DataFrame or column requires only the first and last 5 rows to be read from disk. This leads us to another important point: Vaex will only go over the entire dataset when it has to, and it will try to do it with as few passes over the data as possible." }, { "code": null, "e": 4589, "s": 4104, "text": "Anyway, let’s begin by cleaning this dataset from extreme outliers, or erroneous data inputs. A good way to start is to get a high level overview of the data using the describe method, which shows the number of samples, the number of missing values and the data type for each column. If the data type of a column is numerical, the mean, standard deviation, as well as the minimum and maximum values will also be shown. All of these stats are computed with a single pass over the data." }, { "code": null, "e": 5011, "s": 4589, "text": "The describe method nicely illustrates the power and efficiency of Vaex: all of these statistics were computed in under 3 minutes on my MacBook Pro (15\", 2018, 2.6GHz Intel Core i7, 32GB RAM). Other libraries or methods would require either distributed computing or a cloud instance with over 100GB to preform the same computations. With Vaex, all you need is the data, and your laptop with only a few GB of RAM to spare." }, { "code": null, "e": 5533, "s": 5011, "text": "Looking at the output of describe, it is easy to notice that the data contains some serious outliers. First, let’s start by examining the pick-up locations. Easiest way to remove outliers is to simply plot the pick-up and drop-off locations, and visually define the area of NYC on which we want to focus our analysis. Since we are working with such a large dataset, histograms are the most effective visualisations. Creating and displaying histograms and heatmaps with Vaex is so fast, such plots can be made interactive!" }, { "code": null, "e": 5721, "s": 5533, "text": "df.plot_widget(df.pickup_longitude, df.pickup_latitude, shape=512, limits='minmax', f='log1p', colormap='plasma')" }, { "code": null, "e": 5832, "s": 5721, "text": "Once we interactively decide on which area of NYC we want to focus, we can simply create a filtered DataFrame:" }, { "code": null, "e": 6306, "s": 5832, "text": "The cool thing about the code block above is that it requires negligible amount of memory to execute! When filtering a Vaex DataFrame no copies of the data are made. Instead only a reference to the original object is created, on which a binary mask is applied. The mask selects which rows are displayed and used for future calculations. This saves us 100GB of RAM that would be needed if the data were to be copied, as done by many of the standard data science tools today." }, { "code": null, "e": 6563, "s": 6306, "text": "Now, let’s examine the passenger_count column. The maximum number of passengers recorded in a single taxi trip is 255, which seems a little extreme. Let’s count the number of trips per number of passengers. This is easily done with the value_counts method:" }, { "code": null, "e": 6869, "s": 6563, "text": "From the above figure we can see that trips with more than 6 passengers are likely to be either rare outliers or just erroneous data inputs. There is also a large number of trips with 0 passengers. Since at this time we do not understand whether these are legitimate trips, let us filter them out as well." }, { "code": null, "e": 7132, "s": 6869, "text": "Let’s do a similar exercise with the trip distance. As this is a continuous variable, we can plot the distribution of trip distances. Looking at the minimum (negative!) and maximum (further than Mars!) distance, let’s plot a histogram with a more sensible range." }, { "code": null, "e": 7397, "s": 7132, "text": "From the plot above we can see that number of trips decreases with increasing distance. At a distance of ~100 miles, there is a large drop in the distribution. For now, we will use this as the cut-off point to eliminate extreme outliers based on the trip distance:" }, { "code": null, "e": 7631, "s": 7397, "text": "The presence of extreme outliers in the trip distance columns serves as motivation to investigate the trip durations and average speed of the taxis. These features are not readily available in the dataset, but are trivial to compute:" }, { "code": null, "e": 8024, "s": 7631, "text": "The code block above requires zero memory and takes no time to execute! This is because the code results in the creation of virtual columns. These columns just house the mathematical expressions, and are evaluated only when required. Otherwise, virtual columns behave just as any other regular column. Note that other standard libraries would require 10s of GB of RAM for the same operations." }, { "code": null, "e": 8083, "s": 8024, "text": "Alright, so let’s plot the distribution of trip durations:" }, { "code": null, "e": 8404, "s": 8083, "text": "From the above plot we see that 95% of all taxi trips take less than 30 minutes to reach their destination, although some trips can take more then 4–5 hours. Can you imagine being stuck in a taxi for over 3 hours in New York City? Anyway, let’s be open minded and consider all trips that last less than 3 hours in total:" }, { "code": null, "e": 8513, "s": 8404, "text": "Now let’s investigate the mean speed of the taxis, while also choosing a sensible range for the data limits:" }, { "code": null, "e": 8704, "s": 8513, "text": "Based on where the distribution flattens out, we can deduce that a sensible average taxi speed is in the range between 1 and 60 miles per hour, and thus we can update our filtered DataFrame:" }, { "code": null, "e": 9190, "s": 8704, "text": "Lets shift the focus to the cost of the taxi trips. From the output of the describe method, we can see that there are some crazy outliers in the fare_amount, total_amount, and tip_amount columns. For starters, no value in any of these columns should be negative. On the opposite side of the spectrum, the numbers suggest that some lucky driver almost became a millionaire with a single taxi ride. Let’s look at the distributions of these quantities, but in a relatively sensible range:" }, { "code": null, "e": 9578, "s": 9190, "text": "We see that all three of the above distributions have rather long tails. It is possible that some values in the tails are legit, while others are perhaps erroneous data inputs. In any case, let’s be conservative for now and consider only rides that had fare_amount, total_amount, and tip_amount less than $200. We also require that the fare_amount, total_amount values be larger than $0." }, { "code": null, "e": 9684, "s": 9578, "text": "Finally, after all initial cleaning of the data, let’s see how many taxi trips are left for our analysis:" }, { "code": null, "e": 9809, "s": 9684, "text": "We are left with over 1.1 billion trips! That is plenty of data to get some valuable insights into the world of taxi travel." }, { "code": null, "e": 10019, "s": 9809, "text": "Assume we are a prospective taxi driver, or a manager of a taxi company, and are interested in using this dataset to learn how to maximize our profits, minimize our costs, or simply just improve our work life." }, { "code": null, "e": 10839, "s": 10019, "text": "Let’s start by finding out the locations for picking up passengers that, on average, would lead to the best earnings. Naively, we can just plot a heatmap of the pick-up locations colour-coded by the average fare amount, and look at the hotspots. Taxi drivers have costs on their own, however. For example, they have to pay for fuel. Hence, taking a passenger somewhere far away might result in a larger fare amount, but it would also mean larger fuel consumption, and time lost. In addition, it may not be that easy to find a passenger from that remote location to fare somewhere to the city centre, and thus driving back without a passenger might be costly. One way to account for this is to colour-code a heatmap by the mean of the ratio between the fare amount and trip distance. Let’s consider these two approaches:" }, { "code": null, "e": 11467, "s": 10839, "text": "In the naive case, when we just care about getting a maximum fare for the service provided, the best regions to pick up passengers from are the NYC airports, and along the main avenues such as the Van Wyck Expressway, and the Long Island Expressway. When we take the distance travelled into account, we get a slightly different picture. The Van Wyck Expressway, and the Long Island Expressway avenues, as well as the airports are still a good place for picking up passengers, but they are a lot less prominent on the map. However, some bright new hotspots appear on the west side of the Hudson river that seem quite profitable." }, { "code": null, "e": 11787, "s": 11467, "text": "Being a taxi driver can be quite a flexible job. To better leverage that flexibility it would be useful to know when driving is most profitable, in addition to where one should be lurking. To answer this question, let’s produce a plot showing the mean ratio of fare over trip distance for every day and hour of the day:" }, { "code": null, "e": 12151, "s": 11787, "text": "The figure above makes sense: the best earnings happen during rush-hour, especially around noon, during the working days of the week. As a taxi driver, a fraction of our earnings go to the taxi company, so we might be interested in which day and at which times customers tip the most. So let’s produce a similar plot, this time displaying the mean tip percentage:" }, { "code": null, "e": 12550, "s": 12151, "text": "The above plot is interesting. It tells us that passengers tip their taxi drivers the most between 7–10 o’clock in the morning, and in the evening in the early part of the week. Do not expect large tips if you pick up passengers at 3 or 4am. Combining the insights from the last two plots, a nice time to work is 8–10 o’clock in the morning: one would get both a good fare per mile, and a good tip." }, { "code": null, "e": 13298, "s": 12550, "text": "In the earlier part of this article we briefly focused on the trip_distance column, and while cleaning it from outliers we kept all trips with a value lower than 100 miles. That is still a rather large cut-off value, especially given that the Yellow Taxi company operates primarily over Manhattan. The trip_distance column describes the distance the taxi travelled between the pick-up and the drop-off location. However, one can often take different routes with different distances between two exact pick-up and drop-off locations, for example to avoid traffic jams or roadworks. Thus as a counterpart to the trip_distance column, let’s calculate the shortest possible distance between a pick-up and drop-off locations, which we call arc_distance:" }, { "code": null, "e": 13937, "s": 13298, "text": "The formula for the arc_distance calculation is quite involved, it contains much trigonometry and arithmetic, and can be computationally expensive especially when we are working with large datasets. If the expression or function is written only using Python operations and methods from the Numpy package, Vaex will compute it in parallel using all the cores of your machine. In addition to this, Vaex supports Just-In-Time compilation via Numba (using LLVM) or Pythran (acceleration via C++), giving better performance. If you happen to have a NVIDIA graphics card, you can use CUDA via the jit_cuda method to get even faster performance." }, { "code": null, "e": 14009, "s": 13937, "text": "Anyway, let’s plot the distributions of trip_distance and arc_distance:" }, { "code": null, "e": 14285, "s": 14009, "text": "It is interesting to see that the arc_distance never exceeds 21 miles, but the distance the taxi actually travelled can be 5 times as large. In fact, there are millions of taxi trips for which the drop-off location was within 100 meters (0.06 miles) from the pickup-location!" }, { "code": null, "e": 14580, "s": 14285, "text": "The dataset that we are using today spans across 7 years. It can be interesting to see how some quantities of interest evolved over that time. With Vaex, we can do fast out-of-core group-by and aggregation operations. Let’s explore how the fares, and trip distances evolved through the 7 years:" }, { "code": null, "e": 14956, "s": 14580, "text": "In the above cell block we do a group-by operation followed by 8 aggregations, 2 of which are on virtual columns. The above cell block took less than 2 minutes to execute on my laptop. This is rather impressive, given that the data we are using contains over 1 billion samples. Anyway, let’s check out the results. Here is how the cost of riding a cab evolved over the years:" }, { "code": null, "e": 15134, "s": 14956, "text": "We see that the taxi fares, as well as the tips increase as the years go by. Now let’s look at the mean trip_distance and arc_distance the taxis travelled as a function of year:" }, { "code": null, "e": 15311, "s": 15134, "text": "The figure above shows that there is a small increase of both the trip_distance and arc_distance meaning that, on average, people tend to travel a little bit further each year." }, { "code": null, "e": 15499, "s": 15311, "text": "Before the end of our trip, let’s make one more stop and investigate how passengers pay for their rides. The dataset contains the payment_type column, so let’s see the values it contains:" }, { "code": null, "e": 15595, "s": 15499, "text": "From the dataset documentation, we can see that there are only 6 valid entries for this column:" }, { "code": null, "e": 15619, "s": 15595, "text": "1 = credit card payment" }, { "code": null, "e": 15636, "s": 15619, "text": "2 = cash payment" }, { "code": null, "e": 15650, "s": 15636, "text": "3 = no charge" }, { "code": null, "e": 15662, "s": 15650, "text": "4 = dispute" }, { "code": null, "e": 15674, "s": 15662, "text": "5 = Unknown" }, { "code": null, "e": 15689, "s": 15674, "text": "6 =Voided trip" }, { "code": null, "e": 15765, "s": 15689, "text": "Thus, we can simply map the entries in the payment_type column to integers:" }, { "code": null, "e": 15891, "s": 15765, "text": "Now we can group-by the data per year, and see how the habits of the New Yorkers changed when it comes to taxi ride payments:" }, { "code": null, "e": 16232, "s": 15891, "text": "We see that as time goes on, the card payments slowly became more frequent than cash payments. We truly live in a digital age! Note that in the above code block, once we aggregated the data, the small Vaex DataFrame can easily be converted to a Pandas DataFrame, which we conveniently pass to Seaborn. Not trying to reinvent the wheel here." }, { "code": null, "e": 17006, "s": 16232, "text": "Finally, let’s see whether the payment method depends on the time of day or the day of week by plotting the ratio between the number of cash to card payments. To do this, we will first create a filter which selects only the rides paid for by either cash or card. The next step is one of my favourite Vaex features: aggregations with selections. Other libraries require aggregations to be done on separately filtered DataFrames for each payment method that are later merged into one. With Vaex on the other hand we can do this in one step by providing the selections within the aggregation function. This is quite convenient, and requires just one pass over the data, giving us a better performance. After that, we can just plot the resulting DataFrame in a standard manner:" }, { "code": null, "e": 17489, "s": 17006, "text": "Looking at the plot above we can notice a similar pattern to the one showing the tip percentage as a function of day of week and time of day. From these two plots, the data would suggest that passengers that pay by card tend to tip more than those that pay by cash. To find out whether this is indeed true, I would like to invite you to try and figure it out, since now you have the knowledge, the tools and the data! You can also look at this Jupyter notebook for some extra hints." }, { "code": null, "e": 17853, "s": 17489, "text": "I hope this article was a useful introduction to Vaex, and it will help you alleviate some of the “uncomfortable data” issues that you may be facing, at least when it comes to tabular datasets. If you are interested in exploring the dataset used in this article, it can be used straight from S3 with Vaex. See the full Jupyter notebook to find out how to do this." }, { "code": null, "e": 18100, "s": 17853, "text": "With Vaex, one can go over a billion rows and calculate all sort of statistics, aggregations and produce informative plots in mere seconds, right from the comfort of your own laptop. It is free and open-source, and I hope you will give it a shot!" }, { "code": null, "e": 18122, "s": 18100, "text": "Happy data sciencing!" }, { "code": null, "e": 18238, "s": 18122, "text": "The exploratory data analysis presented in this article is based on an early Vaex demo created by Maarten Breddels." } ]
HCatalog - Installation
All Hadoop sub-projects such as Hive, Pig, and HBase support Linux operating system. Therefore, you need to install a Linux flavor on your system. HCatalog is merged with Hive Installation on March 26, 2013. From the version Hive-0.11.0 onwards, HCatalog comes with Hive installation. Therefore, follow the steps given below to install Hive which in turn will automatically install HCatalog on your system. Java must be installed on your system before installing Hive. You can use the following command to check whether you have Java already installed on your system − $ java –version If Java is already installed on your system, you get to see the following response − java version "1.7.0_71" Java(TM) SE Runtime Environment (build 1.7.0_71-b13) Java HotSpot(TM) Client VM (build 25.0-b02, mixed mode) If you don’t have Java installed on your system, then you need to follow the steps given below. Download Java (JDK <latest version> - X64.tar.gz) by visiting the following link http://www.oracle.com/ Then jdk-7u71-linux-x64.tar.gz will be downloaded onto your system. Generally you will find the downloaded Java file in the Downloads folder. Verify it and extract the jdk-7u71-linux-x64.gz file using the following commands. $ cd Downloads/ $ ls jdk-7u71-linux-x64.gz $ tar zxf jdk-7u71-linux-x64.gz $ ls jdk1.7.0_71 jdk-7u71-linux-x64.gz To make Java available to all the users, you have to move it to the location “/usr/local/”. Open root, and type the following commands. $ su password: # mv jdk1.7.0_71 /usr/local/ # exit For setting up PATH and JAVA_HOME variables, add the following commands to ~/.bashrc file. export JAVA_HOME=/usr/local/jdk1.7.0_71 export PATH=PATH:$JAVA_HOME/bin Now verify the installation using the command java -version from the terminal as explained above. Hadoop must be installed on your system before installing Hive. Let us verify the Hadoop installation using the following command − $ hadoop version If Hadoop is already installed on your system, then you will get the following response − Hadoop 2.4.1 Subversion https://svn.apache.org/repos/asf/hadoop/common -r 1529768 Compiled by hortonmu on 2013-10-07T06:28Z Compiled with protoc 2.5.0 From source with checksum 79e53ce7994d1628b240f09af91e1af4 If Hadoop is not installed on your system, then proceed with the following steps − Download and extract Hadoop 2.4.1 from Apache Software Foundation using the following commands. $ su password: # cd /usr/local # wget http://apache.claz.org/hadoop/common/hadoop-2.4.1/ hadoop-2.4.1.tar.gz # tar xzf hadoop-2.4.1.tar.gz # mv hadoop-2.4.1/* to hadoop/ # exit The following steps are used to install Hadoop 2.4.1 in pseudo distributed mode. You can set Hadoop environment variables by appending the following commands to ~/.bashrc file. export HADOOP_HOME=/usr/local/hadoop export HADOOP_MAPRED_HOME=$HADOOP_HOME export HADOOP_COMMON_HOME=$HADOOP_HOME export HADOOP_HDFS_HOME=$HADOOP_HOME export YARN_HOME=$HADOOP_HOME export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native export PATH=$PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin Now apply all the changes into the current running system. $ source ~/.bashrc You can find all the Hadoop configuration files in the location “$HADOOP_HOME/etc/hadoop”. You need to make suitable changes in those configuration files according to your Hadoop infrastructure. $ cd $HADOOP_HOME/etc/hadoop In order to develop Hadoop programs using Java, you have to reset the Java environment variables in hadoop-env.sh file by replacing JAVA_HOME value with the location of Java in your system. export JAVA_HOME=/usr/local/jdk1.7.0_71 Given below are the list of files that you have to edit to configure Hadoop. The core-site.xml file contains information such as the port number used for Hadoop instance, memory allocated for the file system, memory limit for storing the data, and the size of Read/Write buffers. Open the core-site.xml and add the following properties in between the <configuration> and </configuration> tags. <configuration> <property> <name>fs.default.name</name> <value>hdfs://localhost:9000</value> </property> </configuration> The hdfs-site.xml file contains information such as the value of replication data, the namenode path, and the datanode path of your local file systems. It means the place where you want to store the Hadoop infrastructure. Let us assume the following data. dfs.replication (data replication value) = 1 (In the following path /hadoop/ is the user name. hadoopinfra/hdfs/namenode is the directory created by hdfs file system.) namenode path = //home/hadoop/hadoopinfra/hdfs/namenode (hadoopinfra/hdfs/datanode is the directory created by hdfs file system.) datanode path = //home/hadoop/hadoopinfra/hdfs/datanode Open this file and add the following properties in between the <configuration>, </configuration> tags in this file. <configuration> <property> <name>dfs.replication</name> <value>1</value> </property> <property> <name>dfs.name.dir</name> <value>file:///home/hadoop/hadoopinfra/hdfs/namenode</value> </property> <property> <name>dfs.data.dir</name> <value>file:///home/hadoop/hadoopinfra/hdfs/datanode</value> </property> </configuration> Note − In the above file, all the property values are user-defined and you can make changes according to your Hadoop infrastructure. This file is used to configure yarn into Hadoop. Open the yarn-site.xml file and add the following properties in between the <configuration>, </configuration> tags in this file. <configuration> <property> <name>yarn.nodemanager.aux-services</name> <value>mapreduce_shuffle</value> </property> </configuration> This file is used to specify which MapReduce framework we are using. By default, Hadoop contains a template of yarn-site.xml. First of all, you need to copy the file from mapred-site,xml.template to mapred-site.xml file using the following command. $ cp mapred-site.xml.template mapred-site.xml Open mapred-site.xml file and add the following properties in between the <configuration>, </configuration> tags in this file. <configuration> <property> <name>mapreduce.framework.name</name> <value>yarn</value> </property> </configuration> The following steps are used to verify the Hadoop installation. Set up the namenode using the command “hdfs namenode -format” as follows − $ cd ~ $ hdfs namenode -format The expected result is as follows − 10/24/14 21:30:55 INFO namenode.NameNode: STARTUP_MSG: /************************************************************ STARTUP_MSG: Starting NameNode STARTUP_MSG: host = localhost/192.168.1.11 STARTUP_MSG: args = [-format] STARTUP_MSG: version = 2.4.1 ... ... 10/24/14 21:30:56 INFO common.Storage: Storage directory /home/hadoop/hadoopinfra/hdfs/namenode has been successfully formatted. 10/24/14 21:30:56 INFO namenode.NNStorageRetentionManager: Going to retain 1 images with txid >= 0 10/24/14 21:30:56 INFO util.ExitUtil: Exiting with status 0 10/24/14 21:30:56 INFO namenode.NameNode: SHUTDOWN_MSG: /************************************************************ SHUTDOWN_MSG: Shutting down NameNode at localhost/192.168.1.11 ************************************************************/ The following command is used to start the DFS. Executing this command will start your Hadoop file system. $ start-dfs.sh The expected output is as follows − 10/24/14 21:37:56 Starting namenodes on [localhost] localhost: starting namenode, logging to /home/hadoop/hadoop-2.4.1/logs/hadoop-hadoop-namenode-localhost.out localhost: starting datanode, logging to /home/hadoop/hadoop-2.4.1/logs/hadoop-hadoop-datanode-localhost.out Starting secondary namenodes [0.0.0.0] The following command is used to start the Yarn script. Executing this command will start your Yarn daemons. $ start-yarn.sh The expected output is as follows − starting yarn daemons starting resourcemanager, logging to /home/hadoop/hadoop-2.4.1/logs/ yarn-hadoop-resourcemanager-localhost.out localhost: starting nodemanager, logging to /home/hadoop/hadoop-2.4.1/logs/yarn-hadoop-nodemanager-localhost.out The default port number to access Hadoop is 50070. Use the following URL to get Hadoop services on your browser. http://localhost:50070/ The default port number to access all applications of cluster is 8088. Use the following url to visit this service. http://localhost:8088/ Once you are done with the installation of Hadoop, proceed to the next step and install Hive on your system. We use hive-0.14.0 in this tutorial. You can download it by visiting the following link http://apache.petsads.us/hive/hive-0.14.0/. Let us assume it gets downloaded onto the /Downloads directory. Here, we download Hive archive named “apache-hive-0.14.0-bin.tar.gz” for this tutorial. The following command is used to verify the download − $ cd Downloads $ ls On successful download, you get to see the following response − apache-hive-0.14.0-bin.tar.gz The following steps are required for installing Hive on your system. Let us assume the Hive archive is downloaded onto the /Downloads directory. The following command is used to verify the download and extract the Hive archive − $ tar zxvf apache-hive-0.14.0-bin.tar.gz $ ls On successful download, you get to see the following response − apache-hive-0.14.0-bin apache-hive-0.14.0-bin.tar.gz We need to copy the files from the superuser “su -”. The following commands are used to copy the files from the extracted directory to the /usr/local/hive” directory. $ su - passwd: # cd /home/user/Download # mv apache-hive-0.14.0-bin /usr/local/hive # exit You can set up the Hive environment by appending the following lines to ~/.bashrc file − export HIVE_HOME=/usr/local/hive export PATH=$PATH:$HIVE_HOME/bin export CLASSPATH=$CLASSPATH:/usr/local/Hadoop/lib/*:. export CLASSPATH=$CLASSPATH:/usr/local/hive/lib/*:. The following command is used to execute ~/.bashrc file. $ source ~/.bashrc To configure Hive with Hadoop, you need to edit the hive-env.sh file, which is placed in the $HIVE_HOME/conf directory. The following commands redirect to Hive config folder and copy the template file − $ cd $HIVE_HOME/conf $ cp hive-env.sh.template hive-env.sh Edit the hive-env.sh file by appending the following line − export HADOOP_HOME=/usr/local/hadoop With this, the Hive installation is complete. Now you require an external database server to configure Metastore. We use Apache Derby database. Follow the steps given below to download and install Apache Derby − The following command is used to download Apache Derby. It takes some time to download. $ cd ~ $ wget http://archive.apache.org/dist/db/derby/db-derby-10.4.2.0/db-derby-10.4.2.0-bin.tar.gz The following command is used to verify the download − $ ls On successful download, you get to see the following response − db-derby-10.4.2.0-bin.tar.gz The following commands are used for extracting and verifying the Derby archive − $ tar zxvf db-derby-10.4.2.0-bin.tar.gz $ ls On successful download, you get to see the following response − db-derby-10.4.2.0-bin db-derby-10.4.2.0-bin.tar.gz We need to copy from the superuser “su -”. The following commands are used to copy the files from the extracted directory to the /usr/local/derby directory − $ su - passwd: # cd /home/user # mv db-derby-10.4.2.0-bin /usr/local/derby # exit You can set up the Derby environment by appending the following lines to ~/.bashrc file − export DERBY_HOME=/usr/local/derby export PATH=$PATH:$DERBY_HOME/bin export CLASSPATH=$CLASSPATH:$DERBY_HOME/lib/derby.jar:$DERBY_HOME/lib/derbytools.jar The following command is used to execute ~/.bashrc file − $ source ~/.bashrc Create a directory named data in $DERBY_HOME directory to store Metastore data. $ mkdir $DERBY_HOME/data Derby installation and environmental setup is now complete. Configuring Metastore means specifying to Hive where the database is stored. You can do this by editing the hive-site.xml file, which is in the $HIVE_HOME/conf directory. First of all, copy the template file using the following command − $ cd $HIVE_HOME/conf $ cp hive-default.xml.template hive-site.xml Edit hive-site.xml and append the following lines between the <configuration> and </configuration> tags − <property> <name>javax.jdo.option.ConnectionURL</name> <value>jdbc:derby://localhost:1527/metastore_db;create = true</value> <description>JDBC connect string for a JDBC metastore</description> </property> Create a file named jpox.properties and add the following lines into it − javax.jdo.PersistenceManagerFactoryClass = org.jpox.PersistenceManagerFactoryImpl org.jpox.autoCreateSchema = false org.jpox.validateTables = false org.jpox.validateColumns = false org.jpox.validateConstraints = false org.jpox.storeManagerType = rdbms org.jpox.autoCreateSchema = true org.jpox.autoStartMechanismMode = checked org.jpox.transactionIsolation = read_committed javax.jdo.option.DetachAllOnCommit = true javax.jdo.option.NontransactionalRead = true javax.jdo.option.ConnectionDriverName = org.apache.derby.jdbc.ClientDriver javax.jdo.option.ConnectionURL = jdbc:derby://hadoop1:1527/metastore_db;create = true javax.jdo.option.ConnectionUserName = APP javax.jdo.option.ConnectionPassword = mine Before running Hive, you need to create the /tmp folder and a separate Hive folder in HDFS. Here, we use the /user/hive/warehouse folder. You need to set write permission for these newly created folders as shown below − chmod g+w Now set them in HDFS before verifying Hive. Use the following commands − $ $HADOOP_HOME/bin/hadoop fs -mkdir /tmp $ $HADOOP_HOME/bin/hadoop fs -mkdir /user/hive/warehouse $ $HADOOP_HOME/bin/hadoop fs -chmod g+w /tmp $ $HADOOP_HOME/bin/hadoop fs -chmod g+w /user/hive/warehouse The following commands are used to verify Hive installation − $ cd $HIVE_HOME $ bin/hive On successful installation of Hive, you get to see the following response − Logging initialized using configuration in jar:file:/home/hadoop/hive-0.9.0/lib/hive-common-0.9.0.jar!/ hive-log4j.properties Hive history =/tmp/hadoop/hive_job_log_hadoop_201312121621_1494929084.txt ...................... hive> You can execute the following sample command to display all the tables − hive> show tables; OK Time taken: 2.798 seconds hive> Use the following command to set a system variable HCAT_HOME for HCatalog Home. export HCAT_HOME = $HiVE_HOME/HCatalog Use the following command to verify the HCatalog installation. cd $HCAT_HOME/bin ./hcat If the installation is successful, you will get to see the following output − SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory] usage: hcat { -e "<query>" | -f "<filepath>" } [ -g "<group>" ] [ -p "<perms>" ] [ -D"<name> = <value>" ] -D <property = value> use hadoop value for given property -e <exec> hcat command given from command line -f <file> hcat commands in file -g <group> group for the db/table specified in CREATE statement -h,--help Print help information -p <perms> permissions for the db/table specified in CREATE statement Print Add Notes Bookmark this page
[ { "code": null, "e": 2310, "s": 1903, "text": "All Hadoop sub-projects such as Hive, Pig, and HBase support Linux operating system. Therefore, you need to install a Linux flavor on your system. HCatalog is merged with Hive Installation on March 26, 2013. From the version Hive-0.11.0 onwards, HCatalog comes with Hive installation. Therefore, follow the steps given below to install Hive which in turn will automatically install HCatalog on your system." }, { "code": null, "e": 2472, "s": 2310, "text": "Java must be installed on your system before installing Hive. You can use the following command to check whether you have Java already installed on your system −" }, { "code": null, "e": 2489, "s": 2472, "text": "$ java –version\n" }, { "code": null, "e": 2574, "s": 2489, "text": "If Java is already installed on your system, you get to see the following response −" }, { "code": null, "e": 2708, "s": 2574, "text": "java version \"1.7.0_71\"\nJava(TM) SE Runtime Environment (build 1.7.0_71-b13)\nJava HotSpot(TM) Client VM (build 25.0-b02, mixed mode)\n" }, { "code": null, "e": 2804, "s": 2708, "text": "If you don’t have Java installed on your system, then you need to follow the steps given below." }, { "code": null, "e": 2908, "s": 2804, "text": "Download Java (JDK <latest version> - X64.tar.gz) by visiting the following link http://www.oracle.com/" }, { "code": null, "e": 2976, "s": 2908, "text": "Then jdk-7u71-linux-x64.tar.gz will be downloaded onto your system." }, { "code": null, "e": 3133, "s": 2976, "text": "Generally you will find the downloaded Java file in the Downloads folder. Verify it and extract the jdk-7u71-linux-x64.gz file using the following commands." }, { "code": null, "e": 3249, "s": 3133, "text": "$ cd Downloads/\n$ ls\njdk-7u71-linux-x64.gz\n\n$ tar zxf jdk-7u71-linux-x64.gz\n$ ls\njdk1.7.0_71 jdk-7u71-linux-x64.gz\n" }, { "code": null, "e": 3385, "s": 3249, "text": "To make Java available to all the users, you have to move it to the location “/usr/local/”. Open root, and type the following commands." }, { "code": null, "e": 3437, "s": 3385, "text": "$ su\npassword:\n# mv jdk1.7.0_71 /usr/local/\n# exit\n" }, { "code": null, "e": 3528, "s": 3437, "text": "For setting up PATH and JAVA_HOME variables, add the following commands to ~/.bashrc file." }, { "code": null, "e": 3600, "s": 3528, "text": "export JAVA_HOME=/usr/local/jdk1.7.0_71\nexport PATH=PATH:$JAVA_HOME/bin" }, { "code": null, "e": 3698, "s": 3600, "text": "Now verify the installation using the command java -version from the terminal as explained above." }, { "code": null, "e": 3830, "s": 3698, "text": "Hadoop must be installed on your system before installing Hive. Let us verify the Hadoop installation using the following command −" }, { "code": null, "e": 3848, "s": 3830, "text": "$ hadoop version\n" }, { "code": null, "e": 3938, "s": 3848, "text": "If Hadoop is already installed on your system, then you will get the following response −" }, { "code": null, "e": 4149, "s": 3938, "text": "Hadoop 2.4.1\nSubversion https://svn.apache.org/repos/asf/hadoop/common -r 1529768\nCompiled by hortonmu on 2013-10-07T06:28Z\nCompiled with protoc 2.5.0\nFrom source with checksum 79e53ce7994d1628b240f09af91e1af4\n" }, { "code": null, "e": 4232, "s": 4149, "text": "If Hadoop is not installed on your system, then proceed with the following steps −" }, { "code": null, "e": 4328, "s": 4232, "text": "Download and extract Hadoop 2.4.1 from Apache Software Foundation using the following commands." }, { "code": null, "e": 4506, "s": 4328, "text": "$ su\npassword:\n# cd /usr/local\n# wget http://apache.claz.org/hadoop/common/hadoop-2.4.1/\nhadoop-2.4.1.tar.gz\n# tar xzf hadoop-2.4.1.tar.gz\n# mv hadoop-2.4.1/* to hadoop/\n# exit\n" }, { "code": null, "e": 4587, "s": 4506, "text": "The following steps are used to install Hadoop 2.4.1 in pseudo distributed mode." }, { "code": null, "e": 4683, "s": 4587, "text": "You can set Hadoop environment variables by appending the following commands to ~/.bashrc file." }, { "code": null, "e": 4980, "s": 4683, "text": "export HADOOP_HOME=/usr/local/hadoop\nexport HADOOP_MAPRED_HOME=$HADOOP_HOME\nexport HADOOP_COMMON_HOME=$HADOOP_HOME\nexport HADOOP_HDFS_HOME=$HADOOP_HOME\nexport YARN_HOME=$HADOOP_HOME \nexport HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native\nexport PATH=$PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin\n" }, { "code": null, "e": 5039, "s": 4980, "text": "Now apply all the changes into the current running system." }, { "code": null, "e": 5059, "s": 5039, "text": "$ source ~/.bashrc\n" }, { "code": null, "e": 5254, "s": 5059, "text": "You can find all the Hadoop configuration files in the location “$HADOOP_HOME/etc/hadoop”. You need to make suitable changes in those configuration files according to your Hadoop infrastructure." }, { "code": null, "e": 5284, "s": 5254, "text": "$ cd $HADOOP_HOME/etc/hadoop\n" }, { "code": null, "e": 5474, "s": 5284, "text": "In order to develop Hadoop programs using Java, you have to reset the Java environment variables in hadoop-env.sh file by replacing JAVA_HOME value with the location of Java in your system." }, { "code": null, "e": 5515, "s": 5474, "text": "export JAVA_HOME=/usr/local/jdk1.7.0_71\n" }, { "code": null, "e": 5592, "s": 5515, "text": "Given below are the list of files that you have to edit to configure Hadoop." }, { "code": null, "e": 5795, "s": 5592, "text": "The core-site.xml file contains information such as the port number used for Hadoop instance, memory allocated for the file system, memory limit for storing the data, and the size of Read/Write buffers." }, { "code": null, "e": 5909, "s": 5795, "text": "Open the core-site.xml and add the following properties in between the <configuration> and </configuration> tags." }, { "code": null, "e": 6049, "s": 5909, "text": "<configuration>\n <property>\n <name>fs.default.name</name>\n <value>hdfs://localhost:9000</value>\n </property>\n</configuration>" }, { "code": null, "e": 6271, "s": 6049, "text": "The hdfs-site.xml file contains information such as the value of replication data, the namenode path, and the datanode path of your local file systems. It means the place where you want to store the Hadoop infrastructure." }, { "code": null, "e": 6305, "s": 6271, "text": "Let us assume the following data." }, { "code": null, "e": 6662, "s": 6305, "text": "dfs.replication (data replication value) = 1\n\n(In the following path /hadoop/ is the user name.\nhadoopinfra/hdfs/namenode is the directory created by hdfs file system.)\n\nnamenode path = //home/hadoop/hadoopinfra/hdfs/namenode\n\n(hadoopinfra/hdfs/datanode is the directory created by hdfs file system.)\ndatanode path = //home/hadoop/hadoopinfra/hdfs/datanode" }, { "code": null, "e": 6778, "s": 6662, "text": "Open this file and add the following properties in between the <configuration>, </configuration> tags in this file." }, { "code": null, "e": 7163, "s": 6778, "text": "<configuration>\n <property>\n <name>dfs.replication</name>\n <value>1</value>\n </property> \n \n <property>\n <name>dfs.name.dir</name>\n <value>file:///home/hadoop/hadoopinfra/hdfs/namenode</value> \n </property> \n\n <property>\n <name>dfs.data.dir</name>\n <value>file:///home/hadoop/hadoopinfra/hdfs/datanode</value> \n </property>\n</configuration>" }, { "code": null, "e": 7296, "s": 7163, "text": "Note − In the above file, all the property values are user-defined and you can make changes according to your Hadoop infrastructure." }, { "code": null, "e": 7474, "s": 7296, "text": "This file is used to configure yarn into Hadoop. Open the yarn-site.xml file and add the following properties in between the <configuration>, </configuration> tags in this file." }, { "code": null, "e": 7624, "s": 7474, "text": "<configuration>\n <property>\n <name>yarn.nodemanager.aux-services</name>\n <value>mapreduce_shuffle</value>\n </property>\n</configuration>" }, { "code": null, "e": 7873, "s": 7624, "text": "This file is used to specify which MapReduce framework we are using. By default, Hadoop contains a template of yarn-site.xml. First of all, you need to copy the file from mapred-site,xml.template to mapred-site.xml file using the following command." }, { "code": null, "e": 7920, "s": 7873, "text": "$ cp mapred-site.xml.template mapred-site.xml\n" }, { "code": null, "e": 8047, "s": 7920, "text": "Open mapred-site.xml file and add the following properties in between the <configuration>, </configuration> tags in this file." }, { "code": null, "e": 8179, "s": 8047, "text": "<configuration>\n <property>\n <name>mapreduce.framework.name</name>\n <value>yarn</value>\n </property>\n</configuration>" }, { "code": null, "e": 8243, "s": 8179, "text": "The following steps are used to verify the Hadoop installation." }, { "code": null, "e": 8318, "s": 8243, "text": "Set up the namenode using the command “hdfs namenode -format” as follows −" }, { "code": null, "e": 8349, "s": 8318, "text": "$ cd ~\n$ hdfs namenode -format" }, { "code": null, "e": 8385, "s": 8349, "text": "The expected result is as follows −" }, { "code": null, "e": 9175, "s": 8385, "text": "10/24/14 21:30:55 INFO namenode.NameNode: STARTUP_MSG:\n/************************************************************\nSTARTUP_MSG: Starting NameNode\nSTARTUP_MSG: host = localhost/192.168.1.11\nSTARTUP_MSG: args = [-format]\nSTARTUP_MSG: version = 2.4.1\n...\n...\n10/24/14 21:30:56 INFO common.Storage: Storage directory\n/home/hadoop/hadoopinfra/hdfs/namenode has been successfully formatted.\n10/24/14 21:30:56 INFO namenode.NNStorageRetentionManager: Going to retain 1\nimages with txid >= 0 10/24/14 21:30:56 INFO util.ExitUtil: Exiting with status 0\n10/24/14 21:30:56 INFO namenode.NameNode: SHUTDOWN_MSG:\n/************************************************************\nSHUTDOWN_MSG: Shutting down NameNode at localhost/192.168.1.11\n************************************************************/\n" }, { "code": null, "e": 9282, "s": 9175, "text": "The following command is used to start the DFS. Executing this command will start your Hadoop file system." }, { "code": null, "e": 9297, "s": 9282, "text": "$ start-dfs.sh" }, { "code": null, "e": 9333, "s": 9297, "text": "The expected output is as follows −" }, { "code": null, "e": 9646, "s": 9333, "text": "10/24/14 21:37:56 Starting namenodes on [localhost]\nlocalhost: starting namenode, logging to\n/home/hadoop/hadoop-2.4.1/logs/hadoop-hadoop-namenode-localhost.out localhost:\nstarting datanode, logging to\n /home/hadoop/hadoop-2.4.1/logs/hadoop-hadoop-datanode-localhost.out\nStarting secondary namenodes [0.0.0.0]\n" }, { "code": null, "e": 9755, "s": 9646, "text": "The following command is used to start the Yarn script. Executing this command will start your Yarn daemons." }, { "code": null, "e": 9771, "s": 9755, "text": "$ start-yarn.sh" }, { "code": null, "e": 9807, "s": 9771, "text": "The expected output is as follows −" }, { "code": null, "e": 10057, "s": 9807, "text": "starting yarn daemons\nstarting resourcemanager, logging to /home/hadoop/hadoop-2.4.1/logs/\nyarn-hadoop-resourcemanager-localhost.out\nlocalhost: starting nodemanager, logging to\n /home/hadoop/hadoop-2.4.1/logs/yarn-hadoop-nodemanager-localhost.out\n" }, { "code": null, "e": 10170, "s": 10057, "text": "The default port number to access Hadoop is 50070. Use the following URL to get Hadoop services on your browser." }, { "code": null, "e": 10195, "s": 10170, "text": "http://localhost:50070/\n" }, { "code": null, "e": 10311, "s": 10195, "text": "The default port number to access all applications of cluster is 8088. Use the following url to visit this service." }, { "code": null, "e": 10335, "s": 10311, "text": "http://localhost:8088/\n" }, { "code": null, "e": 10444, "s": 10335, "text": "Once you are done with the installation of Hadoop, proceed to the next step and install Hive on your system." }, { "code": null, "e": 10783, "s": 10444, "text": "We use hive-0.14.0 in this tutorial. You can download it by visiting the following link http://apache.petsads.us/hive/hive-0.14.0/. Let us assume it gets downloaded onto the /Downloads directory. Here, we download Hive archive named “apache-hive-0.14.0-bin.tar.gz” for this tutorial. The following command is used to verify the download −" }, { "code": null, "e": 10804, "s": 10783, "text": "$ cd Downloads\n$ ls\n" }, { "code": null, "e": 10868, "s": 10804, "text": "On successful download, you get to see the following response −" }, { "code": null, "e": 10899, "s": 10868, "text": "apache-hive-0.14.0-bin.tar.gz\n" }, { "code": null, "e": 11044, "s": 10899, "text": "The following steps are required for installing Hive on your system. Let us assume the Hive archive is downloaded onto the /Downloads directory." }, { "code": null, "e": 11128, "s": 11044, "text": "The following command is used to verify the download and extract the Hive archive −" }, { "code": null, "e": 11175, "s": 11128, "text": "$ tar zxvf apache-hive-0.14.0-bin.tar.gz\n$ ls\n" }, { "code": null, "e": 11239, "s": 11175, "text": "On successful download, you get to see the following response −" }, { "code": null, "e": 11293, "s": 11239, "text": "apache-hive-0.14.0-bin apache-hive-0.14.0-bin.tar.gz\n" }, { "code": null, "e": 11460, "s": 11293, "text": "We need to copy the files from the superuser “su -”. The following commands are used to copy the files from the extracted directory to the /usr/local/hive” directory." }, { "code": null, "e": 11552, "s": 11460, "text": "$ su -\npasswd:\n# cd /home/user/Download\n# mv apache-hive-0.14.0-bin /usr/local/hive\n# exit\n" }, { "code": null, "e": 11641, "s": 11552, "text": "You can set up the Hive environment by appending the following lines to ~/.bashrc file −" }, { "code": null, "e": 11814, "s": 11641, "text": "export HIVE_HOME=/usr/local/hive\nexport PATH=$PATH:$HIVE_HOME/bin\nexport CLASSPATH=$CLASSPATH:/usr/local/Hadoop/lib/*:.\nexport CLASSPATH=$CLASSPATH:/usr/local/hive/lib/*:.\n" }, { "code": null, "e": 11871, "s": 11814, "text": "The following command is used to execute ~/.bashrc file." }, { "code": null, "e": 11891, "s": 11871, "text": "$ source ~/.bashrc\n" }, { "code": null, "e": 12094, "s": 11891, "text": "To configure Hive with Hadoop, you need to edit the hive-env.sh file, which is placed in the $HIVE_HOME/conf directory. The following commands redirect to Hive config folder and copy the template file −" }, { "code": null, "e": 12154, "s": 12094, "text": "$ cd $HIVE_HOME/conf\n$ cp hive-env.sh.template hive-env.sh\n" }, { "code": null, "e": 12214, "s": 12154, "text": "Edit the hive-env.sh file by appending the following line −" }, { "code": null, "e": 12252, "s": 12214, "text": "export HADOOP_HOME=/usr/local/hadoop\n" }, { "code": null, "e": 12396, "s": 12252, "text": "With this, the Hive installation is complete. Now you require an external database server to configure Metastore. We use Apache Derby database." }, { "code": null, "e": 12464, "s": 12396, "text": "Follow the steps given below to download and install Apache Derby −" }, { "code": null, "e": 12552, "s": 12464, "text": "The following command is used to download Apache Derby. It takes some time to download." }, { "code": null, "e": 12653, "s": 12552, "text": "$ cd ~\n$ wget http://archive.apache.org/dist/db/derby/db-derby-10.4.2.0/db-derby-10.4.2.0-bin.tar.gz" }, { "code": null, "e": 12708, "s": 12653, "text": "The following command is used to verify the download −" }, { "code": null, "e": 12714, "s": 12708, "text": "$ ls\n" }, { "code": null, "e": 12778, "s": 12714, "text": "On successful download, you get to see the following response −" }, { "code": null, "e": 12808, "s": 12778, "text": "db-derby-10.4.2.0-bin.tar.gz\n" }, { "code": null, "e": 12889, "s": 12808, "text": "The following commands are used for extracting and verifying the Derby archive −" }, { "code": null, "e": 12935, "s": 12889, "text": "$ tar zxvf db-derby-10.4.2.0-bin.tar.gz\n$ ls\n" }, { "code": null, "e": 12999, "s": 12935, "text": "On successful download, you get to see the following response −" }, { "code": null, "e": 13051, "s": 12999, "text": "db-derby-10.4.2.0-bin db-derby-10.4.2.0-bin.tar.gz\n" }, { "code": null, "e": 13209, "s": 13051, "text": "We need to copy from the superuser “su -”. The following commands are used to copy the files from the extracted directory to the /usr/local/derby directory −" }, { "code": null, "e": 13292, "s": 13209, "text": "$ su -\npasswd:\n# cd /home/user\n# mv db-derby-10.4.2.0-bin /usr/local/derby\n# exit\n" }, { "code": null, "e": 13382, "s": 13292, "text": "You can set up the Derby environment by appending the following lines to ~/.bashrc file −" }, { "code": null, "e": 13537, "s": 13382, "text": "export DERBY_HOME=/usr/local/derby\nexport PATH=$PATH:$DERBY_HOME/bin\nexport CLASSPATH=$CLASSPATH:$DERBY_HOME/lib/derby.jar:$DERBY_HOME/lib/derbytools.jar\n" }, { "code": null, "e": 13595, "s": 13537, "text": "The following command is used to execute ~/.bashrc file −" }, { "code": null, "e": 13615, "s": 13595, "text": "$ source ~/.bashrc\n" }, { "code": null, "e": 13695, "s": 13615, "text": "Create a directory named data in $DERBY_HOME directory to store Metastore data." }, { "code": null, "e": 13721, "s": 13695, "text": "$ mkdir $DERBY_HOME/data\n" }, { "code": null, "e": 13781, "s": 13721, "text": "Derby installation and environmental setup is now complete." }, { "code": null, "e": 14019, "s": 13781, "text": "Configuring Metastore means specifying to Hive where the database is stored. You can do this by editing the hive-site.xml file, which is in the $HIVE_HOME/conf directory. First of all, copy the template file using the following command −" }, { "code": null, "e": 14086, "s": 14019, "text": "$ cd $HIVE_HOME/conf\n$ cp hive-default.xml.template hive-site.xml\n" }, { "code": null, "e": 14192, "s": 14086, "text": "Edit hive-site.xml and append the following lines between the <configuration> and </configuration> tags −" }, { "code": null, "e": 14406, "s": 14192, "text": "<property>\n <name>javax.jdo.option.ConnectionURL</name>\n <value>jdbc:derby://localhost:1527/metastore_db;create = true</value>\n <description>JDBC connect string for a JDBC metastore</description>\n</property>" }, { "code": null, "e": 14480, "s": 14406, "text": "Create a file named jpox.properties and add the following lines into it −" }, { "code": null, "e": 15190, "s": 14480, "text": "javax.jdo.PersistenceManagerFactoryClass = org.jpox.PersistenceManagerFactoryImpl\n\norg.jpox.autoCreateSchema = false\norg.jpox.validateTables = false\norg.jpox.validateColumns = false\norg.jpox.validateConstraints = false\n\norg.jpox.storeManagerType = rdbms\norg.jpox.autoCreateSchema = true\norg.jpox.autoStartMechanismMode = checked\norg.jpox.transactionIsolation = read_committed\n\njavax.jdo.option.DetachAllOnCommit = true\njavax.jdo.option.NontransactionalRead = true\njavax.jdo.option.ConnectionDriverName = org.apache.derby.jdbc.ClientDriver\njavax.jdo.option.ConnectionURL = jdbc:derby://hadoop1:1527/metastore_db;create = true\njavax.jdo.option.ConnectionUserName = APP\njavax.jdo.option.ConnectionPassword = mine" }, { "code": null, "e": 15410, "s": 15190, "text": "Before running Hive, you need to create the /tmp folder and a separate Hive folder in HDFS. Here, we use the /user/hive/warehouse folder. You need to set write permission for these newly created folders as shown below −" }, { "code": null, "e": 15421, "s": 15410, "text": "chmod g+w\n" }, { "code": null, "e": 15494, "s": 15421, "text": "Now set them in HDFS before verifying Hive. Use the following commands −" }, { "code": null, "e": 15699, "s": 15494, "text": "$ $HADOOP_HOME/bin/hadoop fs -mkdir /tmp\n$ $HADOOP_HOME/bin/hadoop fs -mkdir /user/hive/warehouse\n$ $HADOOP_HOME/bin/hadoop fs -chmod g+w /tmp\n$ $HADOOP_HOME/bin/hadoop fs -chmod g+w /user/hive/warehouse\n" }, { "code": null, "e": 15761, "s": 15699, "text": "The following commands are used to verify Hive installation −" }, { "code": null, "e": 15789, "s": 15761, "text": "$ cd $HIVE_HOME\n$ bin/hive\n" }, { "code": null, "e": 15865, "s": 15789, "text": "On successful installation of Hive, you get to see the following response −" }, { "code": null, "e": 16102, "s": 15865, "text": "Logging initialized using configuration in \n jar:file:/home/hadoop/hive-0.9.0/lib/hive-common-0.9.0.jar!/\nhive-log4j.properties Hive history\n =/tmp/hadoop/hive_job_log_hadoop_201312121621_1494929084.txt\n......................\nhive>\n" }, { "code": null, "e": 16175, "s": 16102, "text": "You can execute the following sample command to display all the tables −" }, { "code": null, "e": 16230, "s": 16175, "text": "hive> show tables;\nOK Time taken: 2.798 seconds\nhive>\n" }, { "code": null, "e": 16310, "s": 16230, "text": "Use the following command to set a system variable HCAT_HOME for HCatalog Home." }, { "code": null, "e": 16350, "s": 16310, "text": "export HCAT_HOME = $HiVE_HOME/HCatalog\n" }, { "code": null, "e": 16413, "s": 16350, "text": "Use the following command to verify the HCatalog installation." }, { "code": null, "e": 16439, "s": 16413, "text": "cd $HCAT_HOME/bin\n./hcat\n" }, { "code": null, "e": 16517, "s": 16439, "text": "If the installation is successful, you will get to see the following output −" }, { "code": null, "e": 17083, "s": 16517, "text": "SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]\nusage: hcat { -e \"<query>\" | -f \"<filepath>\" } \n [ -g \"<group>\" ] [ -p \"<perms>\" ] \n [ -D\"<name> = <value>\" ]\n\t\n-D <property = value> use hadoop value for given property\n-e <exec> hcat command given from command line\n-f <file> hcat commands in file\n-g <group> group for the db/table specified in CREATE statement\n-h,--help Print help information\n-p <perms> permissions for the db/table specified in CREATE statement\n" }, { "code": null, "e": 17090, "s": 17083, "text": " Print" }, { "code": null, "e": 17101, "s": 17090, "text": " Add Notes" } ]
How to convert JavaScript datetime to MySQL datetime ? - GeeksforGeeks
28 Jun, 2019 Given a date in JavaScript DateTime format and the task is to convert this time into MySQL DateTime format using JavaScript. Approach: Use date.toISOString() function to convert the date object into string ISO format i.e. YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ format. Use slice() method to extract the part of a string. Use replace() method to replace the ‘T’ character with space ‘ ‘. Example 1: In this example, the JavaScript datetime object is converted into MySQL datetime (UTC format) by using slice() and replace() method. <!DOCTYPE HTML> <html> <head> <title> How to convert JavaScript datetime to MySQL datetime ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to convert " + "the JS datetime to MySQL datetime."; function GFG_Fun() { var date = new Date(); el_down.innerHTML = "MySQL datetime - " + date.toISOString().slice(0, 19).replace('T', ' '); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This is same as previous example but with a different approach and time is in IST, the JS datetime is converted to MySQL datetime by using slice() and replace() method. <!DOCTYPE HTML> <html> <head> <title> How to convert JavaScript datetime to MySQL datetime ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to convert " + "the JS datetime to MySQL datetime."; function GFG_Fun() { var date = new Date(); el_down.innerHTML = "MySQL datetime - " + date.toISOString().split('T')[0] + ' ' + date.toTimeString().split(' ')[0]; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? Remove elements from a JavaScript Array How to get selected value in dropdown list using JavaScript ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24909, "s": 24881, "text": "\n28 Jun, 2019" }, { "code": null, "e": 25034, "s": 24909, "text": "Given a date in JavaScript DateTime format and the task is to convert this time into MySQL DateTime format using JavaScript." }, { "code": null, "e": 25044, "s": 25034, "text": "Approach:" }, { "code": null, "e": 25195, "s": 25044, "text": "Use date.toISOString() function to convert the date object into string ISO format i.e. YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ format." }, { "code": null, "e": 25247, "s": 25195, "text": "Use slice() method to extract the part of a string." }, { "code": null, "e": 25313, "s": 25247, "text": "Use replace() method to replace the ‘T’ character with space ‘ ‘." }, { "code": null, "e": 25457, "s": 25313, "text": "Example 1: In this example, the JavaScript datetime object is converted into MySQL datetime (UTC format) by using slice() and replace() method." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to convert JavaScript datetime to MySQL datetime ? </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 19px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to convert \" + \"the JS datetime to MySQL datetime.\"; function GFG_Fun() { var date = new Date(); el_down.innerHTML = \"MySQL datetime - \" + date.toISOString().slice(0, 19).replace('T', ' '); } </script> </body> </html>", "e": 26600, "s": 25457, "text": null }, { "code": null, "e": 26608, "s": 26600, "text": "Output:" }, { "code": null, "e": 26639, "s": 26608, "text": "Before clicking on the button:" }, { "code": null, "e": 26669, "s": 26639, "text": "After clicking on the button:" }, { "code": null, "e": 26849, "s": 26669, "text": "Example 2: This is same as previous example but with a different approach and time is in IST, the JS datetime is converted to MySQL datetime by using slice() and replace() method." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to convert JavaScript datetime to MySQL datetime ? </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 19px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to convert \" + \"the JS datetime to MySQL datetime.\"; function GFG_Fun() { var date = new Date(); el_down.innerHTML = \"MySQL datetime - \" + date.toISOString().split('T')[0] + ' ' + date.toTimeString().split(' ')[0]; } </script> </body> </html>", "e": 28049, "s": 26849, "text": null }, { "code": null, "e": 28057, "s": 28049, "text": "Output:" }, { "code": null, "e": 28088, "s": 28057, "text": "Before clicking on the button:" }, { "code": null, "e": 28118, "s": 28088, "text": "After clicking on the button:" }, { "code": null, "e": 28134, "s": 28118, "text": "JavaScript-Misc" }, { "code": null, "e": 28145, "s": 28134, "text": "JavaScript" }, { "code": null, "e": 28162, "s": 28145, "text": "Web Technologies" }, { "code": null, "e": 28189, "s": 28162, "text": "Web technologies Questions" }, { "code": null, "e": 28287, "s": 28189, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28296, "s": 28287, "text": "Comments" }, { "code": null, "e": 28309, "s": 28296, "text": "Old Comments" }, { "code": null, "e": 28370, "s": 28309, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28411, "s": 28370, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28465, "s": 28411, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28505, "s": 28465, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28567, "s": 28505, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 28623, "s": 28567, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28656, "s": 28623, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28718, "s": 28656, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28761, "s": 28718, "text": "How to fetch data from an API in ReactJS ?" } ]
Creating Symbolic Links on Windows - GeeksforGeeks
08 Sep, 2020 A symbolic link is used to describe a file, that doesn’t store any data. Symbolic Links on Windows contains a reference to another file or directory in the respective of an absolute or you can say to the relative path. The type of path (relative/absolute) is defined during the creation of the link. Most operating systems offer support for Symbolic Links in one way or another. Linux and Windows both provide support for generic Symbolic Links with some OS exclusive features, i.e. Windows allows for the creation of Junction points which are folder soft links with a little different working. In this article, we will take a look at the creation of symbolic links on Windows using mklink command found in the command processor (cmd) of the OS. Note – The command requires administrator privileges to execute. Types of symlinks : Hard Links Soft Links Description of the command : MKLINK [[/D] | [/H] | [/J]] Link Target /D Creates a directory symbolic link. Default is a file symbolic link. /H Creates a hard link instead of a symbolic link. /J Creates a Directory Junction. Link Specifies the new symbolic link name. Target Specifies the path (relative or absolute) that the new link refers to. Note – The above text could be obtained by executing the mklink command without any arguments. Creating a soft link to a file : In order to create a soft link, the syntax of the command is: mklink Link_path Target_path Where Link_path is the name (or path) to the symbolic link which is to be created. Target_path is the path which the new link will refer to. Example – There exists the a file with the path C:\suga\settings In order to create a soft link of the file on the same path with a different name (ex. apple), the command would look as follows. mklink "C:\suga\apple" "C:\suga\settings" Note – In the above command, both paths are absolute. After the execution of the above command, a soft link to the file will be created appears as follows. The same method could be used for creating a soft link to a directory as well, the only difference being that the /D switch needs to be added to the command. making the syntax : mklink /D Link_path Target_path Creating a hard link to a file : In order to create a soft link, the syntax of the command is as follows. mklink /H Link_path Target_path Example – In this example, we would use the same file as the one used in the last example, located at C:\suga\settings. In order to create a hard link of the file at the same path with a different name (ex. moba) the command would look as follows: mklink /H "C:\suga\moba" "C:\suga\settings" After the execution of the above command, a hard link to the file will be created appearing as follows : Hard links could not be created for directories, therefore unlike the previous example, both paths (Link & Target) should point to a file only. Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Memory Management in Operating System File Allocation Methods Segmentation in Operating System Difference between Internal and External fragmentation Introduction of Process Management Mutex lock for Linux Thread Synchronization States of a Process in Operating Systems Program for Least Recently Used (LRU) Page Replacement algorithm Logical and Physical Address in Operating System Dining Philosopher Problem Using Semaphores
[ { "code": null, "e": 24101, "s": 24073, "text": "\n08 Sep, 2020" }, { "code": null, "e": 24402, "s": 24101, "text": "A symbolic link is used to describe a file, that doesn’t store any data. Symbolic Links on Windows contains a reference to another file or directory in the respective of an absolute or you can say to the relative path. The type of path (relative/absolute) is defined during the creation of the link. " }, { "code": null, "e": 24849, "s": 24402, "text": "Most operating systems offer support for Symbolic Links in one way or another. Linux and Windows both provide support for generic Symbolic Links with some OS exclusive features, i.e. Windows allows for the creation of Junction points which are folder soft links with a little different working. In this article, we will take a look at the creation of symbolic links on Windows using mklink command found in the command processor (cmd) of the OS. " }, { "code": null, "e": 24856, "s": 24849, "text": "Note –" }, { "code": null, "e": 24914, "s": 24856, "text": "The command requires administrator privileges to execute." }, { "code": null, "e": 24935, "s": 24914, "text": "Types of symlinks : " }, { "code": null, "e": 24947, "s": 24935, "text": "Hard Links " }, { "code": null, "e": 24958, "s": 24947, "text": "Soft Links" }, { "code": null, "e": 24988, "s": 24958, "text": "Description of the command : " }, { "code": null, "e": 25391, "s": 24988, "text": "MKLINK [[/D] | [/H] | [/J]] Link Target\n\n /D Creates a directory symbolic link. Default is a file\n symbolic link.\n /H Creates a hard link instead of a symbolic link.\n /J Creates a Directory Junction.\n Link Specifies the new symbolic link name.\n Target Specifies the path (relative or absolute) that the new link\n refers to.\n" }, { "code": null, "e": 25398, "s": 25391, "text": "Note –" }, { "code": null, "e": 25486, "s": 25398, "text": "The above text could be obtained by executing the mklink command without any arguments." }, { "code": null, "e": 25519, "s": 25486, "text": "Creating a soft link to a file :" }, { "code": null, "e": 25581, "s": 25519, "text": "In order to create a soft link, the syntax of the command is:" }, { "code": null, "e": 25611, "s": 25581, "text": "mklink Link_path Target_path\n" }, { "code": null, "e": 25695, "s": 25611, "text": "Where Link_path is the name (or path) to the symbolic link which is to be created. " }, { "code": null, "e": 25753, "s": 25695, "text": "Target_path is the path which the new link will refer to." }, { "code": null, "e": 25763, "s": 25753, "text": "Example –" }, { "code": null, "e": 25818, "s": 25763, "text": "There exists the a file with the path C:\\suga\\settings" }, { "code": null, "e": 25948, "s": 25818, "text": "In order to create a soft link of the file on the same path with a different name (ex. apple), the command would look as follows." }, { "code": null, "e": 25993, "s": 25948, "text": "mklink \"C:\\suga\\apple\" \"C:\\suga\\settings\" \n" }, { "code": null, "e": 26000, "s": 25993, "text": "Note –" }, { "code": null, "e": 26047, "s": 26000, "text": "In the above command, both paths are absolute." }, { "code": null, "e": 26149, "s": 26047, "text": "After the execution of the above command, a soft link to the file will be created appears as follows." }, { "code": null, "e": 26307, "s": 26149, "text": "The same method could be used for creating a soft link to a directory as well, the only difference being that the /D switch needs to be added to the command." }, { "code": null, "e": 26327, "s": 26307, "text": "making the syntax :" }, { "code": null, "e": 26360, "s": 26327, "text": "mklink /D Link_path Target_path\n" }, { "code": null, "e": 26393, "s": 26360, "text": "Creating a hard link to a file :" }, { "code": null, "e": 26466, "s": 26393, "text": "In order to create a soft link, the syntax of the command is as follows." }, { "code": null, "e": 26499, "s": 26466, "text": "mklink /H Link_path Target_path\n" }, { "code": null, "e": 26509, "s": 26499, "text": "Example –" }, { "code": null, "e": 26748, "s": 26509, "text": "In this example, we would use the same file as the one used in the last example, located at C:\\suga\\settings. In order to create a hard link of the file at the same path with a different name (ex. moba) the command would look as follows:" }, { "code": null, "e": 26794, "s": 26748, "text": "mklink /H \"C:\\suga\\moba\" \"C:\\suga\\settings\" \n" }, { "code": null, "e": 26899, "s": 26794, "text": "After the execution of the above command, a hard link to the file will be created appearing as follows :" }, { "code": null, "e": 27043, "s": 26899, "text": "Hard links could not be created for directories, therefore unlike the previous example, both paths (Link & Target) should point to a file only." }, { "code": null, "e": 27061, "s": 27043, "text": "Operating Systems" }, { "code": null, "e": 27079, "s": 27061, "text": "Operating Systems" }, { "code": null, "e": 27177, "s": 27079, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27186, "s": 27177, "text": "Comments" }, { "code": null, "e": 27199, "s": 27186, "text": "Old Comments" }, { "code": null, "e": 27237, "s": 27199, "text": "Memory Management in Operating System" }, { "code": null, "e": 27261, "s": 27237, "text": "File Allocation Methods" }, { "code": null, "e": 27294, "s": 27261, "text": "Segmentation in Operating System" }, { "code": null, "e": 27349, "s": 27294, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 27384, "s": 27349, "text": "Introduction of Process Management" }, { "code": null, "e": 27428, "s": 27384, "text": "Mutex lock for Linux Thread Synchronization" }, { "code": null, "e": 27469, "s": 27428, "text": "States of a Process in Operating Systems" }, { "code": null, "e": 27534, "s": 27469, "text": "Program for Least Recently Used (LRU) Page Replacement algorithm" }, { "code": null, "e": 27583, "s": 27534, "text": "Logical and Physical Address in Operating System" } ]
Java program to convert a list to an array
The List object provides a method known as toArray(). This method accepts an empty array as argument, converts the current list to an array and places in the given array. To convert a List object to an array − Create a List object. Add elements to it. Create an empty array with size of the created ArrayList. Convert the list to an array using the toArray() method, bypassing the above-created array as an argument to it. Print the contents of the array. Live Demo import java.util.ArrayList; public class ListToArray { public static void main(String args[]){ ArrayList<String> list = new ArrayList<String>(); list.add("Apple"); list.add("Orange"); list.add("Banana"); System.out.println("Contents of list ::"+list); String[] myArray = new String[list.size()]; list.toArray(myArray); for(int i=0; i<myArray.length; i++){ System.out.println("Element at the index "+i+" is ::"+myArray[i]); } } } Contents of list ::[Apple, Orange, Banana] Element at the index 0 is ::Apple Element at the index 1 is ::Orange Element at the index 2 is ::Banana
[ { "code": null, "e": 1272, "s": 1062, "text": "The List object provides a method known as toArray(). This method accepts an empty array as argument, converts the current list to an array and places in the given array. To convert a List object to an array −" }, { "code": null, "e": 1295, "s": 1272, "text": " Create a List object." }, { "code": null, "e": 1316, "s": 1295, "text": " Add elements to it." }, { "code": null, "e": 1375, "s": 1316, "text": " Create an empty array with size of the created ArrayList." }, { "code": null, "e": 1489, "s": 1375, "text": " Convert the list to an array using the toArray() method, bypassing the above-created array as an argument to it." }, { "code": null, "e": 1523, "s": 1489, "text": " Print the contents of the array." }, { "code": null, "e": 1533, "s": 1523, "text": "Live Demo" }, { "code": null, "e": 2033, "s": 1533, "text": "import java.util.ArrayList;\npublic class ListToArray {\n public static void main(String args[]){\n ArrayList<String> list = new ArrayList<String>();\n list.add(\"Apple\");\n list.add(\"Orange\");\n list.add(\"Banana\");\n\n System.out.println(\"Contents of list ::\"+list);\n String[] myArray = new String[list.size()];\n list.toArray(myArray);\n\n for(int i=0; i<myArray.length; i++){\n System.out.println(\"Element at the index \"+i+\" is ::\"+myArray[i]);\n }\n }\n}" }, { "code": null, "e": 2180, "s": 2033, "text": "Contents of list ::[Apple, Orange, Banana]\nElement at the index 0 is ::Apple\nElement at the index 1 is ::Orange\nElement at the index 2 is ::Banana" } ]
Exception handling and object destruction in C++
Destructors in C++ basically called when objects will get destroyed and release memory from the system. When an exception is thrown in the class, the destructor is called automatically before the catch block gets executed. Begin Declare a class sample1. Declare a constructor of sample1. Print “Construct an Object of sample1” Declare a destructor of sample1. Print “Destruct an Object of sample1” Declare a class sample. Declare a constructor of sample2. Declare variable i of the integer datatype. Initialize i = 7. Print “Construct an Object of sample1”. Throw i. Declare a destructor of sample2. Print “Destruct an Object of sample2” Try: Declare an object s1 of class sample1. Declare an object s2 of class sample2. Ctach(int i) Print “Caught”. Print the value of variable i. End. Live Demo #include <iostream> using namespace std; class Sample1 { public: Sample1() { cout << "Construct an Object of sample1" << endl; } ~Sample1() { cout << "Destruct an Object of sample1" << endl; } }; class Sample2 { public: Sample2() { int i =7; cout << "Construct an Object of sample2" << endl; throw i; } ~Sample2() { cout << "Destruct an Object of sample2" << endl; } }; int main() { try { Sample1 s1; Sample2 s2; } catch(int i) { cout << "Caught " << i << endl; } } Construct an Object of sample1 Construct an Object of sample2 Destruct an Object of sample1 Caught 7
[ { "code": null, "e": 1285, "s": 1062, "text": "Destructors in C++ basically called when objects will get destroyed and release memory from the system. When an exception is thrown in the class, the destructor is called automatically before the catch block gets executed." }, { "code": null, "e": 1971, "s": 1285, "text": "Begin\n Declare a class sample1.\n Declare a constructor of sample1.\n Print “Construct an Object of sample1”\n Declare a destructor of sample1.\n Print “Destruct an Object of sample1”\n Declare a class sample.\n Declare a constructor of sample2.\n Declare variable i of the integer datatype.\n Initialize i = 7.\n Print “Construct an Object of sample1”.\n Throw i.\n Declare a destructor of sample2.\n Print “Destruct an Object of sample2”\n Try:\n Declare an object s1 of class sample1.\n Declare an object s2 of class sample2.\n Ctach(int i)\n Print “Caught”.\n Print the value of variable i.\nEnd." }, { "code": null, "e": 1982, "s": 1971, "text": " Live Demo" }, { "code": null, "e": 2583, "s": 1982, "text": "#include <iostream>\nusing namespace std;\nclass Sample1 {\n public:\n Sample1() {\n cout << \"Construct an Object of sample1\" << endl;\n }\n ~Sample1() {\n cout << \"Destruct an Object of sample1\" << endl;\n }\n};\nclass Sample2 {\n public:\n Sample2() {\n int i =7;\n cout << \"Construct an Object of sample2\" << endl;\n throw i;\n }\n ~Sample2() {\n cout << \"Destruct an Object of sample2\" << endl;\n }\n};\nint main() {\n try {\n Sample1 s1;\n Sample2 s2;\n } catch(int i) {\n cout << \"Caught \" << i << endl;\n }\n}" }, { "code": null, "e": 2684, "s": 2583, "text": "Construct an Object of sample1\nConstruct an Object of sample2\nDestruct an Object of sample1\nCaught 7" } ]
Implementing multi-class text classification with Doc2Vec | by Dipika Baad | Towards Data Science
In this post, you will learn how to classify text documents into different categories while using Doc2Vec to represent the documents. We will learn this with an easy to understand example of classifying the movie plots by genre using Doc2vec for feature representation and using logistic regression as a classification algorithm. The movie dataset contains short movie plot descriptions and the labels for them represents the genre. There are six genres present in the dataset: Sci-fiActionComedyFantasyAnimationRomance Sci-fi Action Comedy Fantasy Animation Romance Well, why should we choose doc2vec representation method rather than using widely known bag-of-words(BOW) method. For complex text classification algorithms, BOW would not be suitable as it lacks the capability to capture the semantics and syntactic order of words in the text. Thus using them as feature input to machine learning algorithm will not yield significant performance. Doc2Vec on the other hand is able to detect relationships among words and understands the semantics of the text. Doc2Vec is an unsupervised algorithm that learns fixed-length feature vectors for paragraphs/documents/texts. For understanding the basic working of doc2vec , how the word2vec works needs to be understood as it uses the same logic except the document specific vector is the added feature vector. For more details on this, you can read this blog. Now that we know why we are using it and how doc2vec will be used in this program, we can go on to the next stage of actually implementing the classifier. Let’s get started on building a movie plot classifier!! Three main parts involved for this are as follows: Loading and preparing the text dataGetting the feature vector using doc2vec modelTraining the Classifier Loading and preparing the text data Getting the feature vector using doc2vec model Training the Classifier Here are the first three rows of the input csv file: ,movieId,plot,tag0,1,"A little boy named Andy loves to be in his room, playing with his toys, especially his doll named ""Woody"". But, what do the toys do when Andy is not with them, they come to life. Woody believes that he has life (as a toy) good. However, he must worry about Andy's family moving, and what Woody does not know is about Andy's birthday party. Woody does not realize that Andy's mother gave him an action figure known as Buzz Lightyear, who does not believe that he is a toy, and quickly becomes Andy's new favorite toy. Woody, who is now consumed with jealousy, tries to get rid of Buzz. Then, both Woody and Buzz are now lost. They must find a way to get back to Andy before he moves without them, but they will have to pass through a ruthless toy killer, Sid Phillips.",animation1,2,"When two kids find and play a magical board game, they release a man trapped for decades in it and a host of dangers that can only be stopped by finishing the game.",fantasy Importing the required libraries: We use multiprocessing for utilizing all the cores for faster training with Doc2Vec. Package tqdm is used for showing the progress bar while training. We use gensim package for Doc2Vec. For classification purpose Logistic regression from scikit-learn is used. NLTK package is used for tokenizing task. from gensim.test.utils import common_textsfrom gensim.models.doc2vec import Doc2Vec, TaggedDocumentfrom sklearn.metrics import accuracy_score, f1_scorefrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionfrom sklearn import utilsimport csvfrom tqdm import tqdmimport multiprocessingimport nltkfrom nltk.corpus import stopwords The following code is for reading the data from the csv and function for tokenizing which will be used while creating training and testing documents as input to the doc2vec model. The data has 2448 rows, we have chosen first 2000 rows for training and the rest for testing. tqdm.pandas(desc="progress-bar")# Function for tokenizingdef tokenize_text(text): tokens = [] for sent in nltk.sent_tokenize(text): for word in nltk.word_tokenize(sent): if len(word) < 2: continue tokens.append(word.lower()) return tokens# Initializing the variablestrain_documents = []test_documents = []i = 0# Associating the tags(labels) with numberstags_index = {'sci-fi': 1 , 'action': 2, 'comedy': 3, 'fantasy': 4, 'animation': 5, 'romance': 6}#Reading the fileFILEPATH = 'data/tagged_plots_movielens.csv'with open(FILEPATH, 'r') as csvfile:with open('data/tagged_plots_movielens.csv', 'r') as csvfile: moviereader = csv.reader(csvfile, delimiter=',', quotechar='"') for row in moviereader: if i == 0: i += 1 continue i += 1 if i <= 2000: train_documents.append( TaggedDocument(words=tokenize_text(row[2]), tags=[tags_index.get(row[3], 8)] )) else: test_documents.append( TaggedDocument(words=tokenize_text(row[2]), tags=[tags_index.get(row[3], 8)]))print(train_documents[0]) Output which is the training_document for the first row is the TaggedDocument object. This shows the tokens as the first argument which are tokens and labelID as the second argument (5: Animation) for TaggedDocument. TaggedDocument(['little', 'boy', 'named', 'andy', 'loves', 'to', 'be', 'in', 'his', 'room', 'playing', 'with', 'his', 'toys', 'especially', 'his', 'doll', 'named', '``', 'woody', "''", 'but', 'what', 'do', 'the', 'toys', 'do', 'when', 'andy', 'is', 'not', 'with', 'them', 'they', 'come', 'to', 'life', 'woody', 'believes', 'that', 'he', 'has', 'life', 'as', 'toy', 'good', 'however', 'he', 'must', 'worry', 'about', 'andy', "'s", 'family', 'moving', 'and', 'what', 'woody', 'does', 'not', 'know', 'is', 'about', 'andy', "'s", 'birthday', 'party', 'woody', 'does', 'not', 'realize', 'that', 'andy', "'s", 'mother', 'gave', 'him', 'an', 'action', 'figure', 'known', 'as', 'buzz', 'lightyear', 'who', 'does', 'not', 'believe', 'that', 'he', 'is', 'toy', 'and', 'quickly', 'becomes', 'andy', "'s", 'new', 'favorite', 'toy', 'woody', 'who', 'is', 'now', 'consumed', 'with', 'jealousy', 'tries', 'to', 'get', 'rid', 'of', 'buzz', 'then', 'both', 'woody', 'and', 'buzz', 'are', 'now', 'lost', 'they', 'must', 'find', 'way', 'to', 'get', 'back', 'to', 'andy', 'before', 'he', 'moves', 'without', 'them', 'but', 'they', 'will', 'have', 'to', 'pass', 'through', 'ruthless', 'toy', 'killer', 'sid', 'phillips'], [5]) Next, we initialize the gensim doc2vec model and train for 30 epochs. This process is pretty simple. Doc2Vec architecture also has two algorithms like word2vec and they are the corresponding algorithms for those two algorithms namely ‘Continuous Bag of Words’(CBOW) and ‘Skip-Gram’(SG). One of the algotihms in doc2vec is called Paragraph Vector - Distributed Bag of Words (PV-DBOW) which is similar to SG model in word2vec except that additional paragraph id vector is added. Here neural network is trained to predict the vector of surrounding words in the given paragraph and paragraph id vector based on a given word in the paragraph. The second algorithm is Paragraph Vector (PV-DM) which is similar to CBOW in word vector. A few important parameters for the doc2vec model consists of: dm ({0,1}, optional) 1: PV-DM, 0: PV-DBOW vector_size Dimensionality of the feature vector (we chose 300) workers this is number of threads which we assigned number of cores The rest of the parameter details could be found here. After initializing, we build the vocabulary using the train_documents cores = multiprocessing.cpu_count()model_dbow = Doc2Vec(dm=1, vector_size=300, negative=5, hs=0, min_count=2, sample = 0, workers=cores, alpha=0.025, min_alpha=0.001)model_dbow.build_vocab([x for x in tqdm(train_documents)])train_documents = utils.shuffle(train_documents)model_dbow.train(train_documents,total_examples=len(train_documents), epochs=30)def vector_for_learning(model, input_docs): sents = input_docs targets, feature_vectors = zip(*[(doc.tags[0], model.infer_vector(doc.words, steps=20)) for doc in sents]) return targets, feature_vectorsmodel_dbow.save('./movieModel.d2v') Finally, using the feature vector building function above we train the Logistic Regression Classifier. Here we used the feature vector generated for the train_documents while training and used the feature vectors of test_documents in the prediction phase. y_train, X_train = vector_for_learning(model_dbow, train_documents)y_test, X_test = vector_for_learning(model_dbow, test_documents)logreg = LogisticRegression(n_jobs=1, C=1e5)logreg.fit(X_train, y_train)y_pred = logreg.predict(X_test)print('Testing accuracy for movie plots%s' % accuracy_score(y_test, y_pred))print('Testing F1 score for movie plots: {}'.format(f1_score(y_test, y_pred, average='weighted'))) The output when dm=1 is as follows: Testing accuracy 0.42316258351893093Testing F1 score: 0.41259684559985876 This accuracy is obtained only with just few records with very short text and hence, this can be improved with adding better features like n-grams, using stopwords to remove noise. Building on this, you can experiment more easily using with other datasets and changing the algorithms for doc2vec is as easy as changing the dm paramter. Hope this helps you get started on your first project on text classification with Doc2Vec! Author: Dipika Baad
[ { "code": null, "e": 649, "s": 171, "text": "In this post, you will learn how to classify text documents into different categories while using Doc2Vec to represent the documents. We will learn this with an easy to understand example of classifying the movie plots by genre using Doc2vec for feature representation and using logistic regression as a classification algorithm. The movie dataset contains short movie plot descriptions and the labels for them represents the genre. There are six genres present in the dataset:" }, { "code": null, "e": 691, "s": 649, "text": "Sci-fiActionComedyFantasyAnimationRomance" }, { "code": null, "e": 698, "s": 691, "text": "Sci-fi" }, { "code": null, "e": 705, "s": 698, "text": "Action" }, { "code": null, "e": 712, "s": 705, "text": "Comedy" }, { "code": null, "e": 720, "s": 712, "text": "Fantasy" }, { "code": null, "e": 730, "s": 720, "text": "Animation" }, { "code": null, "e": 738, "s": 730, "text": "Romance" }, { "code": null, "e": 1733, "s": 738, "text": "Well, why should we choose doc2vec representation method rather than using widely known bag-of-words(BOW) method. For complex text classification algorithms, BOW would not be suitable as it lacks the capability to capture the semantics and syntactic order of words in the text. Thus using them as feature input to machine learning algorithm will not yield significant performance. Doc2Vec on the other hand is able to detect relationships among words and understands the semantics of the text. Doc2Vec is an unsupervised algorithm that learns fixed-length feature vectors for paragraphs/documents/texts. For understanding the basic working of doc2vec , how the word2vec works needs to be understood as it uses the same logic except the document specific vector is the added feature vector. For more details on this, you can read this blog. Now that we know why we are using it and how doc2vec will be used in this program, we can go on to the next stage of actually implementing the classifier." }, { "code": null, "e": 1789, "s": 1733, "text": "Let’s get started on building a movie plot classifier!!" }, { "code": null, "e": 1840, "s": 1789, "text": "Three main parts involved for this are as follows:" }, { "code": null, "e": 1945, "s": 1840, "text": "Loading and preparing the text dataGetting the feature vector using doc2vec modelTraining the Classifier" }, { "code": null, "e": 1981, "s": 1945, "text": "Loading and preparing the text data" }, { "code": null, "e": 2028, "s": 1981, "text": "Getting the feature vector using doc2vec model" }, { "code": null, "e": 2052, "s": 2028, "text": "Training the Classifier" }, { "code": null, "e": 2105, "s": 2052, "text": "Here are the first three rows of the input csv file:" }, { "code": null, "e": 3086, "s": 2105, "text": ",movieId,plot,tag0,1,\"A little boy named Andy loves to be in his room, playing with his toys, especially his doll named \"\"Woody\"\". But, what do the toys do when Andy is not with them, they come to life. Woody believes that he has life (as a toy) good. However, he must worry about Andy's family moving, and what Woody does not know is about Andy's birthday party. Woody does not realize that Andy's mother gave him an action figure known as Buzz Lightyear, who does not believe that he is a toy, and quickly becomes Andy's new favorite toy. Woody, who is now consumed with jealousy, tries to get rid of Buzz. Then, both Woody and Buzz are now lost. They must find a way to get back to Andy before he moves without them, but they will have to pass through a ruthless toy killer, Sid Phillips.\",animation1,2,\"When two kids find and play a magical board game, they release a man trapped for decades in it and a host of dangers that can only be stopped by finishing the game.\",fantasy" }, { "code": null, "e": 3120, "s": 3086, "text": "Importing the required libraries:" }, { "code": null, "e": 3422, "s": 3120, "text": "We use multiprocessing for utilizing all the cores for faster training with Doc2Vec. Package tqdm is used for showing the progress bar while training. We use gensim package for Doc2Vec. For classification purpose Logistic regression from scikit-learn is used. NLTK package is used for tokenizing task." }, { "code": null, "e": 3799, "s": 3422, "text": "from gensim.test.utils import common_textsfrom gensim.models.doc2vec import Doc2Vec, TaggedDocumentfrom sklearn.metrics import accuracy_score, f1_scorefrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionfrom sklearn import utilsimport csvfrom tqdm import tqdmimport multiprocessingimport nltkfrom nltk.corpus import stopwords" }, { "code": null, "e": 4073, "s": 3799, "text": "The following code is for reading the data from the csv and function for tokenizing which will be used while creating training and testing documents as input to the doc2vec model. The data has 2448 rows, we have chosen first 2000 rows for training and the rest for testing." }, { "code": null, "e": 5195, "s": 4073, "text": "tqdm.pandas(desc=\"progress-bar\")# Function for tokenizingdef tokenize_text(text): tokens = [] for sent in nltk.sent_tokenize(text): for word in nltk.word_tokenize(sent): if len(word) < 2: continue tokens.append(word.lower()) return tokens# Initializing the variablestrain_documents = []test_documents = []i = 0# Associating the tags(labels) with numberstags_index = {'sci-fi': 1 , 'action': 2, 'comedy': 3, 'fantasy': 4, 'animation': 5, 'romance': 6}#Reading the fileFILEPATH = 'data/tagged_plots_movielens.csv'with open(FILEPATH, 'r') as csvfile:with open('data/tagged_plots_movielens.csv', 'r') as csvfile: moviereader = csv.reader(csvfile, delimiter=',', quotechar='\"') for row in moviereader: if i == 0: i += 1 continue i += 1 if i <= 2000: train_documents.append( TaggedDocument(words=tokenize_text(row[2]), tags=[tags_index.get(row[3], 8)] )) else: test_documents.append( TaggedDocument(words=tokenize_text(row[2]), tags=[tags_index.get(row[3], 8)]))print(train_documents[0])" }, { "code": null, "e": 5412, "s": 5195, "text": "Output which is the training_document for the first row is the TaggedDocument object. This shows the tokens as the first argument which are tokens and labelID as the second argument (5: Animation) for TaggedDocument." }, { "code": null, "e": 6618, "s": 5412, "text": "TaggedDocument(['little', 'boy', 'named', 'andy', 'loves', 'to', 'be', 'in', 'his', 'room', 'playing', 'with', 'his', 'toys', 'especially', 'his', 'doll', 'named', '``', 'woody', \"''\", 'but', 'what', 'do', 'the', 'toys', 'do', 'when', 'andy', 'is', 'not', 'with', 'them', 'they', 'come', 'to', 'life', 'woody', 'believes', 'that', 'he', 'has', 'life', 'as', 'toy', 'good', 'however', 'he', 'must', 'worry', 'about', 'andy', \"'s\", 'family', 'moving', 'and', 'what', 'woody', 'does', 'not', 'know', 'is', 'about', 'andy', \"'s\", 'birthday', 'party', 'woody', 'does', 'not', 'realize', 'that', 'andy', \"'s\", 'mother', 'gave', 'him', 'an', 'action', 'figure', 'known', 'as', 'buzz', 'lightyear', 'who', 'does', 'not', 'believe', 'that', 'he', 'is', 'toy', 'and', 'quickly', 'becomes', 'andy', \"'s\", 'new', 'favorite', 'toy', 'woody', 'who', 'is', 'now', 'consumed', 'with', 'jealousy', 'tries', 'to', 'get', 'rid', 'of', 'buzz', 'then', 'both', 'woody', 'and', 'buzz', 'are', 'now', 'lost', 'they', 'must', 'find', 'way', 'to', 'get', 'back', 'to', 'andy', 'before', 'he', 'moves', 'without', 'them', 'but', 'they', 'will', 'have', 'to', 'pass', 'through', 'ruthless', 'toy', 'killer', 'sid', 'phillips'], [5])" }, { "code": null, "e": 7346, "s": 6618, "text": "Next, we initialize the gensim doc2vec model and train for 30 epochs. This process is pretty simple. Doc2Vec architecture also has two algorithms like word2vec and they are the corresponding algorithms for those two algorithms namely ‘Continuous Bag of Words’(CBOW) and ‘Skip-Gram’(SG). One of the algotihms in doc2vec is called Paragraph Vector - Distributed Bag of Words (PV-DBOW) which is similar to SG model in word2vec except that additional paragraph id vector is added. Here neural network is trained to predict the vector of surrounding words in the given paragraph and paragraph id vector based on a given word in the paragraph. The second algorithm is Paragraph Vector (PV-DM) which is similar to CBOW in word vector." }, { "code": null, "e": 7408, "s": 7346, "text": "A few important parameters for the doc2vec model consists of:" }, { "code": null, "e": 7450, "s": 7408, "text": "dm ({0,1}, optional) 1: PV-DM, 0: PV-DBOW" }, { "code": null, "e": 7514, "s": 7450, "text": "vector_size Dimensionality of the feature vector (we chose 300)" }, { "code": null, "e": 7582, "s": 7514, "text": "workers this is number of threads which we assigned number of cores" }, { "code": null, "e": 7707, "s": 7582, "text": "The rest of the parameter details could be found here. After initializing, we build the vocabulary using the train_documents" }, { "code": null, "e": 8306, "s": 7707, "text": "cores = multiprocessing.cpu_count()model_dbow = Doc2Vec(dm=1, vector_size=300, negative=5, hs=0, min_count=2, sample = 0, workers=cores, alpha=0.025, min_alpha=0.001)model_dbow.build_vocab([x for x in tqdm(train_documents)])train_documents = utils.shuffle(train_documents)model_dbow.train(train_documents,total_examples=len(train_documents), epochs=30)def vector_for_learning(model, input_docs): sents = input_docs targets, feature_vectors = zip(*[(doc.tags[0], model.infer_vector(doc.words, steps=20)) for doc in sents]) return targets, feature_vectorsmodel_dbow.save('./movieModel.d2v')" }, { "code": null, "e": 8562, "s": 8306, "text": "Finally, using the feature vector building function above we train the Logistic Regression Classifier. Here we used the feature vector generated for the train_documents while training and used the feature vectors of test_documents in the prediction phase." }, { "code": null, "e": 8971, "s": 8562, "text": "y_train, X_train = vector_for_learning(model_dbow, train_documents)y_test, X_test = vector_for_learning(model_dbow, test_documents)logreg = LogisticRegression(n_jobs=1, C=1e5)logreg.fit(X_train, y_train)y_pred = logreg.predict(X_test)print('Testing accuracy for movie plots%s' % accuracy_score(y_test, y_pred))print('Testing F1 score for movie plots: {}'.format(f1_score(y_test, y_pred, average='weighted')))" }, { "code": null, "e": 9007, "s": 8971, "text": "The output when dm=1 is as follows:" }, { "code": null, "e": 9081, "s": 9007, "text": "Testing accuracy 0.42316258351893093Testing F1 score: 0.41259684559985876" }, { "code": null, "e": 9262, "s": 9081, "text": "This accuracy is obtained only with just few records with very short text and hence, this can be improved with adding better features like n-grams, using stopwords to remove noise." }, { "code": null, "e": 9508, "s": 9262, "text": "Building on this, you can experiment more easily using with other datasets and changing the algorithms for doc2vec is as easy as changing the dm paramter. Hope this helps you get started on your first project on text classification with Doc2Vec!" } ]
What is onclick event in JavaScript?
The onClick event is the most frequently used event type, which occurs when a user clicks the left button of the mouse. You can put your validation, warning etc., against this event type. Live Demo <html> <head> <script> <!-- function sayHello() { alert("Hello World") } //--> </script> </head> <body> <p>Click the following button and see result</p> <form> <input type="button" onclick="sayHello()" value="Say Hello" /> </form> </body> </html>
[ { "code": null, "e": 1182, "s": 1062, "text": "The onClick event is the most frequently used event type, which occurs when a user clicks the left button of the mouse." }, { "code": null, "e": 1250, "s": 1182, "text": "You can put your validation, warning etc., against this event type." }, { "code": null, "e": 1260, "s": 1250, "text": "Live Demo" }, { "code": null, "e": 1615, "s": 1260, "text": "<html>\n <head>\n <script>\n <!--\n function sayHello() {\n alert(\"Hello World\")\n }\n //-->\n </script>\n </head>\n <body>\n <p>Click the following button and see result</p>\n <form>\n <input type=\"button\" onclick=\"sayHello()\" value=\"Say Hello\" />\n </form>\n </body>\n</html>" } ]
Linked List Length Even or Odd? | Practice | GeeksforGeeks
Given a linked list of size N, your task is to complete the function isLengthEvenOrOdd() which contains head of the linked list and check whether the length of linked list is even or odd. Input: The input line contains T, denoting the number of testcases. Each testcase contains two lines. the first line contains N(size of the linked list). the second line contains N elements of the linked list separated by space. Output: For each testcase in new line, print "even"(without quotes) if the length is even else "odd"(without quotes) if the length is odd. User Task: Since this is a functional problem you don't have to worry about input, you just have to complete the function isLengthEvenOrOdd() which takes head of the linked list as input parameter and returns 0 if the length of the linked list is even otherwise returns 1. Constraints: 1 <= T <= 100 1 <= N <= 103 1 <= A[i] <= 103 Example: Input: 2 3 9 4 3 6 12 52 10 47 95 0 Output: Odd Even Explanation: Testcase 1: The length of linked list is 3 which is odd. Testcase 2: The length of linked list is 6 which is even. 0 neelasatyasai93in 4 hours #PYTHON def isLengthEvenOrOdd(head): count=0 temp=head while temp!=None: count+=1 temp=temp.next return 0 if count%2==0 else 1 0 mankesh0162 weeks ago Short & Sweet... Node* fast=head; while(fast && fast->next){ fast=fast->next->next; } if(!fast) return 0; return 1; 0 priyankarajpoot2013 weeks ago Java Solution- int isLengthEvenorOdd(Node head1){ //Add your code here. int count = 0; if(head1 == null){ return 0; } Node temp = head1; while(temp != null){ temp = temp.next; count++; } if(count%2 == 0){ return 0; }else{ return 1; }} 0 bobbyprajapati963 weeks ago JAVA EASY SOLUTION int isLengthEvenorOdd(Node head1){ //Add your code here. int count=0; Node temp=head1; while(temp!=null) { count++; temp=temp.next; } if(count%2==0) return 0; else return 1;} 0 atif836141 month ago JAVA SOLUTION: int isLengthEvenorOdd(Node head1){ int count=0; Node ptr = head1; if(ptr==null){ return 0; } while(ptr!=null){ coun++; ptr = ptr.next; } if(count%2==0){ return 0; } return 1; } 0 ishitasharma14320021 month ago int isLengthEvenOrOdd(struct Node* head) { if(head==NULL) { return -1; } else { int count=1; while(head->next!=NULL) { count++; head=head->next; } if((count+1)%2==0) { return 1; } else return 0; } } +1 imohdalam1 month ago Java | O(n) class GFG { int isLengthEvenorOdd(Node head) { int count = 0; if(head == null) return 0; while(head != null){ count++; head = head.next; } return count%2 == 0 ? 0 : 1; } } 0 rklsspty7772 months ago Solution in Java: class GFG { int c = 0; int isLengthEvenorOdd(Node head1) { if(head1==null) return c&1; else { c+=1; return isLengthEvenorOdd(head1.next); } } } +1 gurucharanchouhan172 months ago Simple Solution in java :) class GFG { public int check(Node head) { int c=0; while(head!=null) { c++; head=head.next; } return c; } int isLengthEvenorOdd(Node head) { return check(head)%2==0?0:1; } } 0 mayank20212 months ago C++int isLengthEvenOrOdd(struct Node* head){ Node* temp=head; int count=0; while(temp) { count++; temp=temp->next; } return count&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": 414, "s": 226, "text": "Given a linked list of size N, your task is to complete the function isLengthEvenOrOdd() which contains head of the linked list and check whether the length of linked list is even or odd." }, { "code": null, "e": 643, "s": 414, "text": "Input:\nThe input line contains T, denoting the number of testcases. Each testcase contains two lines. the first line contains N(size of the linked list). the second line contains N elements of the linked list separated by space." }, { "code": null, "e": 782, "s": 643, "text": "Output:\nFor each testcase in new line, print \"even\"(without quotes) if the length is even else \"odd\"(without quotes) if the length is odd." }, { "code": null, "e": 1056, "s": 782, "text": "User Task:\nSince this is a functional problem you don't have to worry about input, you just have to complete the function isLengthEvenOrOdd() which takes head of the linked list as input parameter and returns 0 if the length of the linked list is even otherwise returns 1." }, { "code": null, "e": 1114, "s": 1056, "text": "Constraints:\n1 <= T <= 100\n1 <= N <= 103\n1 <= A[i] <= 103" }, { "code": null, "e": 1159, "s": 1114, "text": "Example:\nInput:\n2\n3\n9 4 3\n6\n12 52 10 47 95 0" }, { "code": null, "e": 1176, "s": 1159, "text": "Output:\nOdd\nEven" }, { "code": null, "e": 1306, "s": 1176, "text": "Explanation:\nTestcase 1: The length of linked list is 3 which is odd.\nTestcase 2: The length of linked list is 6 which is even.\n " }, { "code": null, "e": 1308, "s": 1306, "text": "0" }, { "code": null, "e": 1334, "s": 1308, "text": "neelasatyasai93in 4 hours" }, { "code": null, "e": 1342, "s": 1334, "text": "#PYTHON" }, { "code": null, "e": 1373, "s": 1342, "text": "def isLengthEvenOrOdd(head): " }, { "code": null, "e": 1481, "s": 1373, "text": "count=0 temp=head while temp!=None: count+=1 temp=temp.next return 0 if count%2==0 else 1" }, { "code": null, "e": 1483, "s": 1481, "text": "0" }, { "code": null, "e": 1505, "s": 1483, "text": "mankesh0162 weeks ago" }, { "code": null, "e": 1522, "s": 1505, "text": "Short & Sweet..." }, { "code": null, "e": 1651, "s": 1522, "text": " Node* fast=head;\n while(fast && fast->next){\n fast=fast->next->next;\n }\n if(!fast) return 0;\n return 1;" }, { "code": null, "e": 1653, "s": 1651, "text": "0" }, { "code": null, "e": 1683, "s": 1653, "text": "priyankarajpoot2013 weeks ago" }, { "code": null, "e": 1698, "s": 1683, "text": "Java Solution-" }, { "code": null, "e": 1989, "s": 1698, "text": " int isLengthEvenorOdd(Node head1){ //Add your code here. int count = 0; if(head1 == null){ return 0; } Node temp = head1; while(temp != null){ temp = temp.next; count++; } if(count%2 == 0){ return 0; }else{ return 1; }}" }, { "code": null, "e": 1991, "s": 1989, "text": "0" }, { "code": null, "e": 2019, "s": 1991, "text": "bobbyprajapati963 weeks ago" }, { "code": null, "e": 2038, "s": 2019, "text": "JAVA EASY SOLUTION" }, { "code": null, "e": 2263, "s": 2038, "text": " int isLengthEvenorOdd(Node head1){ //Add your code here. int count=0; Node temp=head1; while(temp!=null) { count++; temp=temp.next; } if(count%2==0) return 0; else return 1;} " }, { "code": null, "e": 2265, "s": 2263, "text": "0" }, { "code": null, "e": 2286, "s": 2265, "text": "atif836141 month ago" }, { "code": null, "e": 2301, "s": 2286, "text": "JAVA SOLUTION:" }, { "code": null, "e": 2479, "s": 2301, "text": "int isLengthEvenorOdd(Node head1){\nint count=0;\nNode ptr = head1;\nif(ptr==null){\nreturn 0;\n}\nwhile(ptr!=null){\ncoun++;\nptr = ptr.next;\n}\nif(count%2==0){\nreturn 0;\n}\nreturn 1;\n}\n" }, { "code": null, "e": 2481, "s": 2479, "text": "0" }, { "code": null, "e": 2512, "s": 2481, "text": "ishitasharma14320021 month ago" }, { "code": null, "e": 2858, "s": 2512, "text": "int isLengthEvenOrOdd(struct Node* head)\n{\n if(head==NULL)\n {\n return -1;\n }\n else\n {\n int count=1;\n while(head->next!=NULL)\n {\n count++;\n head=head->next;\n }\n if((count+1)%2==0)\n {\n return 1;\n }\n else\n return 0;\n }\n \n}" }, { "code": null, "e": 2861, "s": 2858, "text": "+1" }, { "code": null, "e": 2882, "s": 2861, "text": "imohdalam1 month ago" }, { "code": null, "e": 2894, "s": 2882, "text": "Java | O(n)" }, { "code": null, "e": 3139, "s": 2894, "text": "class GFG\n{\n\tint isLengthEvenorOdd(Node head)\n\t{\n\t int count = 0;\n\t \n\t if(head == null)\n\t return 0;\n\t \n\t while(head != null){\n\t count++;\n\t head = head.next;\n\t }\n\t \n\t return count%2 == 0 ? 0 : 1;\n\t}\n}" }, { "code": null, "e": 3141, "s": 3139, "text": "0" }, { "code": null, "e": 3165, "s": 3141, "text": "rklsspty7772 months ago" }, { "code": null, "e": 3183, "s": 3165, "text": "Solution in Java:" }, { "code": null, "e": 3376, "s": 3183, "text": "class GFG\n{\n int c = 0;\n\tint isLengthEvenorOdd(Node head1)\n\t{\n\t if(head1==null)\n\t return c&1;\n\t else {\n\t c+=1;\n\t return isLengthEvenorOdd(head1.next);\n\t }\n\t}\n}" }, { "code": null, "e": 3379, "s": 3376, "text": "+1" }, { "code": null, "e": 3411, "s": 3379, "text": "gurucharanchouhan172 months ago" }, { "code": null, "e": 3438, "s": 3411, "text": "Simple Solution in java :)" }, { "code": null, "e": 3698, "s": 3438, "text": "class GFG\n{\n public int check(Node head)\n {\n int c=0;\n while(head!=null)\n {\n c++;\n head=head.next;\n }\n return c;\n }\n\tint isLengthEvenorOdd(Node head)\n\t{\t \n\t return check(head)%2==0?0:1;\n\t}\n}" }, { "code": null, "e": 3700, "s": 3698, "text": "0" }, { "code": null, "e": 3723, "s": 3700, "text": "mayank20212 months ago" }, { "code": null, "e": 3901, "s": 3723, "text": "C++int isLengthEvenOrOdd(struct Node* head){ Node* temp=head; int count=0; while(temp) { count++; temp=temp->next; } return count&1; }" }, { "code": null, "e": 4047, "s": 3901, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 4083, "s": 4047, "text": " Login to access your submissions. " }, { "code": null, "e": 4093, "s": 4083, "text": "\nProblem\n" }, { "code": null, "e": 4103, "s": 4093, "text": "\nContest\n" }, { "code": null, "e": 4166, "s": 4103, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4314, "s": 4166, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 4522, "s": 4314, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 4628, "s": 4522, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How To Use Machine Learning To Possibly Become A Millionaire: Predicting The Stock Market? | by Jere Xu | Towards Data Science
Working on Wall Street is just as intense and rewarding as you would imagine. Lots of suits and lots of sullen faces and lots of cigarette smoke. Amidst all of the craziness you’d expect from the literal financial center of the world, the actual underlying goal of everyone there is pretty simple. At risk of oversimplifying things, I’ll tell you right now that finance is simply using money (either your own or some you’ve borrowed) to get more money. The financial industry doesn’t actually create any value, rather it uses other factors to get returns on investments. The stock market is one of the most well-known infrastructures through which anyone can potentially make a fortune. If anyone could crack the code to predicting what future stock prices are, they’ll practically rule the world. There’s just one problem. It’s pretty much impossible to accurately predict the future of the stock market. So many analysts, so many researchers, so many super smart people have tried to figure it all out. No one has been able to garner consistent results. No one. So what’s the point of this article? Why am I writing about using machine learning to possibly predict the stock market? Mostly just for fun, I guess. More importantly, however, it’s a great learning exercise for machine learning and finance. The Stocker ModuleMoving AveragesSimple Linear RegressionK-Nearest NeighborsMultilayer PerceptronWhat You Should Do InsteadAreas of ImprovementResources The Stocker Module Moving Averages Simple Linear Regression K-Nearest Neighbors Multilayer Perceptron What You Should Do Instead Areas of Improvement Resources If you want a more in-depth view of this project, or if you want to add to the code, check out the GitHub repository. The Stocker module is a simple Python library that contains a bunch of useful stock market prediction functions. Upon initialization, they aren’t that accurate (better to just flip a coin). But with some tuning of parameters, the results can be a lot better. First we need to clone the GitHub repository. !git clone https://github.com/WillKoehrsen/Data-Analysis.git We also need to import some libraries. Now that the repo is cloned, we can import the Stocker module as well. !pip install quandl!pip install pytrendsimport stockerfrom stocker import Stocker Let’s create a Stocker object. I chose Google as my company, but you’re not obligated to do the same. The Stocker module has a function called plot_stock() that does a lot by itself. If you pay attention, you’ll notice that the dates for the Stocker object are not up-to-date. It stops at 2018–3–27. Taking close look at the actual module code, we’ll see that the data is taken from Quandl’s WIKI exchange. Perhaps the data is not kept up to date? We can use Stocker to conduct technical stock analysis, but for now we will focus on being mediums. Stocker uses a package created by Facebook called prophet which is good for additive modeling. Now let’s test the stocker predictions. We need to create a test set and a training set. We’ll have our training set to be 2014–2016, and our test set to be 2017. Let’s see how accurate this model is. The results are quite horrendous, with the predictions being almost as bad as a coin flip. Let’s adjust some hyperparameters. Validating on the changepoints is an effective way to adjust the hyperparameters to better tweak the stock prediction algorithm. Now we can evaluate the refined model to see if there are any improvements in the prediction estimates. Now it’s time to do the ultimate test: try our luck in the stock market (simulated, of course). Even after all of that tweaking, it’s clear that simply buying and holding would produce better returns. Now let’s move on to attempting to predict stock prices with machine learning instead of depending on a module. For this example, I’ll be using Google stock data using the make_df function Stocker provides. In summary, a moving average is a commonly used indicator in technical analysis. It’s a lagging indicator, which means that it uses past prices to predict future prices. It’s effective in smoothing out any short-term fluctuations and finding the overall trend. We’ll use moving averages to see if we can do a better job of predicting stock prices. Let’s measure the accuracy of our model with RMS (Root Mean Squared Error). Now let’s see our prediction plotted next to the actual prices. In terms of figuring out the general trend of the stock data, the moving average method did okay, but it failed to see the full extent of the increase in the price, and that is not good. We definitely wouldn’t want to use this method for actual algorithmic trading. Let’s try using another method to predict future stock prices, linear regression. First let’s create a new dataset based off of the original. Now let’s add some more features to the dataset for the linear regression algorithm. We’ll be using some functions from the fastai module. Now let’s do a train-test split. Now we can implement the algorithm and get some results. Once again, the prediction algorithm somewhat figures out the general trend, yet it fails to capture what we need the most. Let’s move on to yet another machine learning algorithm, KNN. Let’s go through the same process with the same data as the linear regression stuff. The only difference is that we’ll be implementing a different algorithm to the data. Let’s see which predictions are better. What are our results? Yikes! This is the worst prediction we’ve got so far! There’s a reason k-nearest neighbors is more useful for classification problems and small-scale regression. This appears to be a classic case of overfitting. Because KNN is really just calculating distances from each point to another, it was completely unable to figure out the trend of where the prices are going. What’s next? Let’s move into some deep learning, more specifically, neural networks. A multilayer perceptron is one of the simplest types of neural networks, at least simpler than convolutional neural networks and long short-term memory. We don’t need to get into the details on how the algorithm actually works. If you’re interested, check out the resources at the end of the article. Let’s get our results. This is even worse than KNN! There are a number of factors as to why the neural network is so bad at predicting the stock prices, and one of them is definitely the lack of meaningful features and data. Obviously there are many hyperparameters that can be tweaked as well. What did we learn today? What did all of this technical analysis show us? The answer is quite simple: If you’re not someone like Ray Dalio or Warren Buffet or any of the great investors, it’s very risky and ultimately not as profitable to try to beat the stock market. According to some sources, a majority of hedge funds can’t even do better than the S&P 500! Therefore, if you want to make the best returns on your investments, do the buy and hold strategy. For the most part, simply investing in an index fund like the S&P 500 has yielded pretty good returns, even when there were several big drops in the economy. In the end, it’s up for you to decide. Thank you for taking the time to read through this article! Feel free to check out my portfolio site or my GitHub. I only used Google stock data and for a relatively small range of time. Feel free to use different data that can be pulled with Stocker or Yahoo Finance or Quandl. There are MANY machine learning algorithms out there that are very good. I only used a small subset of them and only one of them was even a deep learning algorithm. This is pretty self-explanatory. More often than not, the default settings for any algorithm are not optimal, thus it’s useful for you to try out some validation to figure out which hyperparameters are most effective. Understanding the Stock MarketTechnical AnalysisWhat is Machine Learning?Moving AveragesLinear RegressionK-Nearest NeighborsNeural NetworksTensorflowKeras Understanding the Stock Market Technical Analysis What is Machine Learning?
[ { "code": null, "e": 743, "s": 172, "text": "Working on Wall Street is just as intense and rewarding as you would imagine. Lots of suits and lots of sullen faces and lots of cigarette smoke. Amidst all of the craziness you’d expect from the literal financial center of the world, the actual underlying goal of everyone there is pretty simple. At risk of oversimplifying things, I’ll tell you right now that finance is simply using money (either your own or some you’ve borrowed) to get more money. The financial industry doesn’t actually create any value, rather it uses other factors to get returns on investments." }, { "code": null, "e": 970, "s": 743, "text": "The stock market is one of the most well-known infrastructures through which anyone can potentially make a fortune. If anyone could crack the code to predicting what future stock prices are, they’ll practically rule the world." }, { "code": null, "e": 1236, "s": 970, "text": "There’s just one problem. It’s pretty much impossible to accurately predict the future of the stock market. So many analysts, so many researchers, so many super smart people have tried to figure it all out. No one has been able to garner consistent results. No one." }, { "code": null, "e": 1479, "s": 1236, "text": "So what’s the point of this article? Why am I writing about using machine learning to possibly predict the stock market? Mostly just for fun, I guess. More importantly, however, it’s a great learning exercise for machine learning and finance." }, { "code": null, "e": 1632, "s": 1479, "text": "The Stocker ModuleMoving AveragesSimple Linear RegressionK-Nearest NeighborsMultilayer PerceptronWhat You Should Do InsteadAreas of ImprovementResources" }, { "code": null, "e": 1651, "s": 1632, "text": "The Stocker Module" }, { "code": null, "e": 1667, "s": 1651, "text": "Moving Averages" }, { "code": null, "e": 1692, "s": 1667, "text": "Simple Linear Regression" }, { "code": null, "e": 1712, "s": 1692, "text": "K-Nearest Neighbors" }, { "code": null, "e": 1734, "s": 1712, "text": "Multilayer Perceptron" }, { "code": null, "e": 1761, "s": 1734, "text": "What You Should Do Instead" }, { "code": null, "e": 1782, "s": 1761, "text": "Areas of Improvement" }, { "code": null, "e": 1792, "s": 1782, "text": "Resources" }, { "code": null, "e": 1910, "s": 1792, "text": "If you want a more in-depth view of this project, or if you want to add to the code, check out the GitHub repository." }, { "code": null, "e": 2169, "s": 1910, "text": "The Stocker module is a simple Python library that contains a bunch of useful stock market prediction functions. Upon initialization, they aren’t that accurate (better to just flip a coin). But with some tuning of parameters, the results can be a lot better." }, { "code": null, "e": 2215, "s": 2169, "text": "First we need to clone the GitHub repository." }, { "code": null, "e": 2276, "s": 2215, "text": "!git clone https://github.com/WillKoehrsen/Data-Analysis.git" }, { "code": null, "e": 2386, "s": 2276, "text": "We also need to import some libraries. Now that the repo is cloned, we can import the Stocker module as well." }, { "code": null, "e": 2468, "s": 2386, "text": "!pip install quandl!pip install pytrendsimport stockerfrom stocker import Stocker" }, { "code": null, "e": 2651, "s": 2468, "text": "Let’s create a Stocker object. I chose Google as my company, but you’re not obligated to do the same. The Stocker module has a function called plot_stock() that does a lot by itself." }, { "code": null, "e": 2916, "s": 2651, "text": "If you pay attention, you’ll notice that the dates for the Stocker object are not up-to-date. It stops at 2018–3–27. Taking close look at the actual module code, we’ll see that the data is taken from Quandl’s WIKI exchange. Perhaps the data is not kept up to date?" }, { "code": null, "e": 3111, "s": 2916, "text": "We can use Stocker to conduct technical stock analysis, but for now we will focus on being mediums. Stocker uses a package created by Facebook called prophet which is good for additive modeling." }, { "code": null, "e": 3312, "s": 3111, "text": "Now let’s test the stocker predictions. We need to create a test set and a training set. We’ll have our training set to be 2014–2016, and our test set to be 2017. Let’s see how accurate this model is." }, { "code": null, "e": 3438, "s": 3312, "text": "The results are quite horrendous, with the predictions being almost as bad as a coin flip. Let’s adjust some hyperparameters." }, { "code": null, "e": 3567, "s": 3438, "text": "Validating on the changepoints is an effective way to adjust the hyperparameters to better tweak the stock prediction algorithm." }, { "code": null, "e": 3671, "s": 3567, "text": "Now we can evaluate the refined model to see if there are any improvements in the prediction estimates." }, { "code": null, "e": 3767, "s": 3671, "text": "Now it’s time to do the ultimate test: try our luck in the stock market (simulated, of course)." }, { "code": null, "e": 3872, "s": 3767, "text": "Even after all of that tweaking, it’s clear that simply buying and holding would produce better returns." }, { "code": null, "e": 4079, "s": 3872, "text": "Now let’s move on to attempting to predict stock prices with machine learning instead of depending on a module. For this example, I’ll be using Google stock data using the make_df function Stocker provides." }, { "code": null, "e": 4427, "s": 4079, "text": "In summary, a moving average is a commonly used indicator in technical analysis. It’s a lagging indicator, which means that it uses past prices to predict future prices. It’s effective in smoothing out any short-term fluctuations and finding the overall trend. We’ll use moving averages to see if we can do a better job of predicting stock prices." }, { "code": null, "e": 4503, "s": 4427, "text": "Let’s measure the accuracy of our model with RMS (Root Mean Squared Error)." }, { "code": null, "e": 4567, "s": 4503, "text": "Now let’s see our prediction plotted next to the actual prices." }, { "code": null, "e": 4833, "s": 4567, "text": "In terms of figuring out the general trend of the stock data, the moving average method did okay, but it failed to see the full extent of the increase in the price, and that is not good. We definitely wouldn’t want to use this method for actual algorithmic trading." }, { "code": null, "e": 4915, "s": 4833, "text": "Let’s try using another method to predict future stock prices, linear regression." }, { "code": null, "e": 4975, "s": 4915, "text": "First let’s create a new dataset based off of the original." }, { "code": null, "e": 5114, "s": 4975, "text": "Now let’s add some more features to the dataset for the linear regression algorithm. We’ll be using some functions from the fastai module." }, { "code": null, "e": 5147, "s": 5114, "text": "Now let’s do a train-test split." }, { "code": null, "e": 5204, "s": 5147, "text": "Now we can implement the algorithm and get some results." }, { "code": null, "e": 5328, "s": 5204, "text": "Once again, the prediction algorithm somewhat figures out the general trend, yet it fails to capture what we need the most." }, { "code": null, "e": 5390, "s": 5328, "text": "Let’s move on to yet another machine learning algorithm, KNN." }, { "code": null, "e": 5600, "s": 5390, "text": "Let’s go through the same process with the same data as the linear regression stuff. The only difference is that we’ll be implementing a different algorithm to the data. Let’s see which predictions are better." }, { "code": null, "e": 5622, "s": 5600, "text": "What are our results?" }, { "code": null, "e": 6004, "s": 5622, "text": "Yikes! This is the worst prediction we’ve got so far! There’s a reason k-nearest neighbors is more useful for classification problems and small-scale regression. This appears to be a classic case of overfitting. Because KNN is really just calculating distances from each point to another, it was completely unable to figure out the trend of where the prices are going. What’s next?" }, { "code": null, "e": 6377, "s": 6004, "text": "Let’s move into some deep learning, more specifically, neural networks. A multilayer perceptron is one of the simplest types of neural networks, at least simpler than convolutional neural networks and long short-term memory. We don’t need to get into the details on how the algorithm actually works. If you’re interested, check out the resources at the end of the article." }, { "code": null, "e": 6400, "s": 6377, "text": "Let’s get our results." }, { "code": null, "e": 6672, "s": 6400, "text": "This is even worse than KNN! There are a number of factors as to why the neural network is so bad at predicting the stock prices, and one of them is definitely the lack of meaningful features and data. Obviously there are many hyperparameters that can be tweaked as well." }, { "code": null, "e": 7329, "s": 6672, "text": "What did we learn today? What did all of this technical analysis show us? The answer is quite simple: If you’re not someone like Ray Dalio or Warren Buffet or any of the great investors, it’s very risky and ultimately not as profitable to try to beat the stock market. According to some sources, a majority of hedge funds can’t even do better than the S&P 500! Therefore, if you want to make the best returns on your investments, do the buy and hold strategy. For the most part, simply investing in an index fund like the S&P 500 has yielded pretty good returns, even when there were several big drops in the economy. In the end, it’s up for you to decide." }, { "code": null, "e": 7444, "s": 7329, "text": "Thank you for taking the time to read through this article! Feel free to check out my portfolio site or my GitHub." }, { "code": null, "e": 7608, "s": 7444, "text": "I only used Google stock data and for a relatively small range of time. Feel free to use different data that can be pulled with Stocker or Yahoo Finance or Quandl." }, { "code": null, "e": 7773, "s": 7608, "text": "There are MANY machine learning algorithms out there that are very good. I only used a small subset of them and only one of them was even a deep learning algorithm." }, { "code": null, "e": 7991, "s": 7773, "text": "This is pretty self-explanatory. More often than not, the default settings for any algorithm are not optimal, thus it’s useful for you to try out some validation to figure out which hyperparameters are most effective." }, { "code": null, "e": 8146, "s": 7991, "text": "Understanding the Stock MarketTechnical AnalysisWhat is Machine Learning?Moving AveragesLinear RegressionK-Nearest NeighborsNeural NetworksTensorflowKeras" }, { "code": null, "e": 8177, "s": 8146, "text": "Understanding the Stock Market" }, { "code": null, "e": 8196, "s": 8177, "text": "Technical Analysis" } ]
How to get the number of rows and columns of a JTable in Java Swing
To count the number of rows of a table, use the getRowCount() method − table.getRowCount() To count the number of columns of a table, use the getColumnCount() method − table.getColumnCount() The following is an example to get the number of rows and columns of a JTable − package my; import java.awt.Font; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class SwingDemo { public static void main(String[] argv) throws Exception { DefaultTableModel tableModel = new DefaultTableModel(); JTable table = new JTable(tableModel); tableModel.addColumn("Language/ Technology"); tableModel.addColumn("Text Tutorial"); tableModel.addColumn("Video Tutorial"); tableModel.addColumn("Views"); // prevent from resizing table.getTableHeader().setResizingAllowed(false); tableModel.addRow(new Object[] { "F#", "Yes", "No", "7890"}); tableModel.addRow(new Object[] { "Blockchain", "Yes", "No", "10600"}); tableModel.addRow(new Object[] { "SharePoint", "Yes", "Yes", "4900"}); tableModel.addRow(new Object[] { "AWS", "No", "Yes", "8900"}); tableModel.addRow(new Object[] { "Python", "Yes", "No", "6789"}); tableModel.addRow(new Object[] { "Scala", "Yes", "No", "3400"}); tableModel.addRow(new Object[] { "Swift", "No", "Yes", "9676"}); tableModel.addRow(new Object[] { "C#", "Yes", "Yes", "1300"}); tableModel.addRow(new Object[] { "NodeJS", "No", "Yes", "2350"}); tableModel.addRow(new Object[] { "MVC", "Yes", "No", "1500"}); tableModel.addRow(new Object[] { "ASP.NET", "Yes", "Yes", "3400"}); tableModel.addRow(new Object[] { "Java", "Yes", "No", "9686"}); tableModel.addRow(new Object[] { "jQuery", "Yes", "Yes", "4500"}); System.out.println("Table rows = "+table.getRowCount()); System.out.println("Table columns = "+table.getColumnCount()); Font font = new Font("Verdana", Font.PLAIN, 12); table.setFont(font); JFrame frame = new JFrame(); frame.setSize(600, 400); frame.add(new JScrollPane(table)); frame.setVisible(true); } } This will produce the following output displaying the table with rows and columns − The count of rows and columns are displayed in the console as shown below −
[ { "code": null, "e": 1133, "s": 1062, "text": "To count the number of rows of a table, use the getRowCount() method −" }, { "code": null, "e": 1153, "s": 1133, "text": "table.getRowCount()" }, { "code": null, "e": 1230, "s": 1153, "text": "To count the number of columns of a table, use the getColumnCount() method −" }, { "code": null, "e": 1253, "s": 1230, "text": "table.getColumnCount()" }, { "code": null, "e": 1333, "s": 1253, "text": "The following is an example to get the number of rows and columns of a JTable −" }, { "code": null, "e": 3247, "s": 1333, "text": "package my;\nimport java.awt.Font;\nimport javax.swing.JFrame;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.table.DefaultTableModel;\npublic class SwingDemo {\n public static void main(String[] argv) throws Exception {\n DefaultTableModel tableModel = new DefaultTableModel();\n JTable table = new JTable(tableModel);\n tableModel.addColumn(\"Language/ Technology\");\n tableModel.addColumn(\"Text Tutorial\");\n tableModel.addColumn(\"Video Tutorial\");\n tableModel.addColumn(\"Views\");\n // prevent from resizing\n table.getTableHeader().setResizingAllowed(false);\n tableModel.addRow(new Object[] { \"F#\", \"Yes\", \"No\", \"7890\"});\n tableModel.addRow(new Object[] { \"Blockchain\", \"Yes\", \"No\", \"10600\"});\n tableModel.addRow(new Object[] { \"SharePoint\", \"Yes\", \"Yes\", \"4900\"});\n tableModel.addRow(new Object[] { \"AWS\", \"No\", \"Yes\", \"8900\"});\n tableModel.addRow(new Object[] { \"Python\", \"Yes\", \"No\", \"6789\"});\n tableModel.addRow(new Object[] { \"Scala\", \"Yes\", \"No\", \"3400\"});\n tableModel.addRow(new Object[] { \"Swift\", \"No\", \"Yes\", \"9676\"});\n tableModel.addRow(new Object[] { \"C#\", \"Yes\", \"Yes\", \"1300\"});\n tableModel.addRow(new Object[] { \"NodeJS\", \"No\", \"Yes\", \"2350\"});\n tableModel.addRow(new Object[] { \"MVC\", \"Yes\", \"No\", \"1500\"});\n tableModel.addRow(new Object[] { \"ASP.NET\", \"Yes\", \"Yes\", \"3400\"});\n tableModel.addRow(new Object[] { \"Java\", \"Yes\", \"No\", \"9686\"});\n tableModel.addRow(new Object[] { \"jQuery\", \"Yes\", \"Yes\", \"4500\"});\n System.out.println(\"Table rows = \"+table.getRowCount());\n System.out.println(\"Table columns = \"+table.getColumnCount());\n Font font = new Font(\"Verdana\", Font.PLAIN, 12);\n table.setFont(font);\n JFrame frame = new JFrame();\n frame.setSize(600, 400);\n frame.add(new JScrollPane(table));\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 3331, "s": 3247, "text": "This will produce the following output displaying the table with rows and columns −" }, { "code": null, "e": 3407, "s": 3331, "text": "The count of rows and columns are displayed in the console as shown below −" } ]
Java Examples - Debug a java file
How to set destination of the class file? Following example demonstrates how to debug a java file using =g option with javac command. c:> javac demo.java -g The above code sample will produce the following result. Demo.java will debug. Print Add Notes Bookmark this page
[ { "code": null, "e": 2110, "s": 2068, "text": "How to set destination of the class file?" }, { "code": null, "e": 2202, "s": 2110, "text": "Following example demonstrates how to debug a java file using =g option with javac command." }, { "code": null, "e": 2226, "s": 2202, "text": "c:> javac demo.java -g\n" }, { "code": null, "e": 2283, "s": 2226, "text": "The above code sample will produce the following result." }, { "code": null, "e": 2306, "s": 2283, "text": "Demo.java will debug.\n" }, { "code": null, "e": 2313, "s": 2306, "text": " Print" }, { "code": null, "e": 2324, "s": 2313, "text": " Add Notes" } ]
Remove trailing zeros in decimal value with changing length in MySQL?
You can remove trailing zeros using TRIM() function. The syntax is as follows. SELECT TRIM(yourColumnName)+0 FROM yourTableName; To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table removeTrailingZeroInDecimal -> ( -> Id int not null auto_increment, -> Amount decimal(5,2), -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (1.01 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into removeTrailingZeroInDecimal(Amount) values(405.50); Query OK, 1 row affected (0.22 sec) mysql> insert into removeTrailingZeroInDecimal(Amount) values(23.05); Query OK, 1 row affected (0.17 sec) mysql> insert into removeTrailingZeroInDecimal(Amount) values(12.050); Query OK, 1 row affected (0.14 sec) mysql> insert into removeTrailingZeroInDecimal(Amount) values(125.23); Query OK, 1 row affected (0.14 sec) mysql> insert into removeTrailingZeroInDecimal(Amount) values(125.00); Query OK, 1 row affected (0.15 sec) mysql> insert into removeTrailingZeroInDecimal(Amount) values(126); Query OK, 1 row affected (0.14 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from removeTrailingZeroInDecimal; The following is the output. +----+--------+ | Id | Amount | +----+--------+ | 1 | 405.50 | | 2 | 23.05 | | 3 | 12.05 | | 4 | 125.23 | | 5 | 125.00 | | 6 | 126.00 | +----+--------+ 6 rows in set (0.00 sec) Here is the query to remove trailing zeros in decimal value. The query is as follows − mysql> SELECT TRIM(Amount)+0 FROM removeTrailingZeroInDecimal; The output displays the records without the trailing zeros. +----------------+ | TRIM(Amount)+0 | +----------------+ | 405.5 | | 23.05 | | 12.05 | | 125.23 | | 125 | | 126 | +----------------+ 6 rows in set (0.00 sec)
[ { "code": null, "e": 1141, "s": 1062, "text": "You can remove trailing zeros using TRIM() function. The syntax is as follows." }, { "code": null, "e": 1191, "s": 1141, "text": "SELECT TRIM(yourColumnName)+0 FROM yourTableName;" }, { "code": null, "e": 1290, "s": 1191, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1479, "s": 1290, "text": "mysql> create table removeTrailingZeroInDecimal\n -> (\n -> Id int not null auto_increment,\n -> Amount decimal(5,2),\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (1.01 sec)" }, { "code": null, "e": 1560, "s": 1479, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2203, "s": 1560, "text": "mysql> insert into removeTrailingZeroInDecimal(Amount) values(405.50);\nQuery OK, 1 row affected (0.22 sec)\n\nmysql> insert into removeTrailingZeroInDecimal(Amount) values(23.05);\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into removeTrailingZeroInDecimal(Amount) values(12.050);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into removeTrailingZeroInDecimal(Amount) values(125.23);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into removeTrailingZeroInDecimal(Amount) values(125.00);\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into removeTrailingZeroInDecimal(Amount) values(126);\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 2288, "s": 2203, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2337, "s": 2288, "text": "mysql> select *from removeTrailingZeroInDecimal;" }, { "code": null, "e": 2366, "s": 2337, "text": "The following is the output." }, { "code": null, "e": 2551, "s": 2366, "text": "+----+--------+\n| Id | Amount |\n+----+--------+\n| 1 | 405.50 |\n| 2 | 23.05 |\n| 3 | 12.05 |\n| 4 | 125.23 |\n| 5 | 125.00 |\n| 6 | 126.00 |\n+----+--------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2638, "s": 2551, "text": "Here is the query to remove trailing zeros in decimal value. The query is as follows −" }, { "code": null, "e": 2701, "s": 2638, "text": "mysql> SELECT TRIM(Amount)+0 FROM removeTrailingZeroInDecimal;" }, { "code": null, "e": 2761, "s": 2701, "text": "The output displays the records without the trailing zeros." }, { "code": null, "e": 2976, "s": 2761, "text": "+----------------+\n| TRIM(Amount)+0 |\n+----------------+\n| 405.5 |\n| 23.05 |\n| 12.05 |\n| 125.23 |\n| 125 |\n| 126 |\n+----------------+\n6 rows in set (0.00 sec)" } ]
Machine Learning application in Petrophysics Industry: A Sonic Log Synthesis prediction story | by Aboze Brain John Jnr | Towards Data Science
Petrophysics is the study of the properties of rock and a brief description about the interactions of liquids. It is mainly used in the Oil and Gas industry to study the behavior of different kinds of reservoirs. It also explains the chemistry of pores of the subsurface and how they are connected. It helps in controlling the migration and accumulation of hydrocarbons, while explaining the chemical and physical properties, Petrophysics also explains many other related terms such as lithology, water saturation, density, permeability and porosity. Petrophysics emphasizes those properties relating to the pore system and its fluid distribution and flow characteristics. These properties and their relationships are used to identify and evaluate: Hydrocarbon reservoirs Hydrocarbon sources Seals Aquifers The petrophysicist or petrophysical engineer practices the science of petrophysics as a member of the reservoir management team. The petrophysicist provides answers on products needed and used by team members, as well as physical and chemical insights needed by other teammates. The reservoir and fluid characteristics to be determined are: Thickness (bed boundaries) Lithology (rock type) Porosity Fluid saturations and pressures Fluid identification and characterization Permeability (absolute) Fractional flow (oil, gas, water) It is easy to define these characteristics and to appreciate their part in the assessment of reserves. The difficult part comes in determining their actual value at a level of certainty needed to make economic decisions leading to development and production. The seven characteristics listed are interdependent (i.e., to properly determine porosity from a wireline log, one must know the lithology, fluid saturations, and fluid types). The science of petrophysics is then used to unscramble the hidden world of rock and fluid properties in reservoirs from just below the Earth’s surface to ones more than four miles deep. The petrophysicist then takes on many characteristics of the fictional sleuth Sherlock Holmes to extrapolate, from the most meager of clues, the true picture of the subsurface reservoir using dogged determination to wrest all possible information from the available data, all the while enjoying the thrill of the hunt. Archie’s general method is to subdivide the problem into smaller segments and iterate using all data until all data agree. One starting point is to determine rock types (petrofacies) wherein we identify: Pore type Pore size distribution Pore throat type Pore throat distribution When coupled with fluid type, one can establish a capillary pressure model that will lead to understanding in-situ fluid saturations and fluid flow. However, the tools available to the petrophysicist are: Mud logging (solids, liquids, gasses, volumes, rates, concentrations, and temperature) Measurement while drilling (MWD) and Logging while drilling (LWD) Wireline logging (open- and cased-hole) Core sampling and core analysis Fluid sampling (wireline and/or drillstem tests) Compressional traveltime (DTC) and shear traveltime (DTS) logs are not acquired in all the wells drilled in a field due to financial or operational constraints. Under such circumstances, machine-learning techniques can be used to predict DTC and DTS logs to improve subsurface characterization. The goal of this Petrophysical Data-Driven Analytics project is to develop data-driven models by processing “easy-to-acquire” conventional logs from casr study ‘Well 1’, and use the data-driven models to generate synthetic DTC and DTS logs in case study ‘Well 2’. A robust data-driven model for the desired sonic-log synthesis will result in low prediction errors, which can be quantified in terms of root mean squared error (RME) by comparing the synthesized and the original DTC and DTS logs. Well datasets (comprising of Well 1 & Well 2) are provided, and the goal is to build a generalizable data-driven models using the Well 1 dataset. Following that, you will deploy the newly developed data-driven models on the Well 2 dataset to synthesize DTS and DTC logs. The data-driven model uses feature sets derived from the following seven logs: caliper, neutron, gamma ray, deep resistivity, medium resistivity, photoelectric factor and density. The data-driven model should synthesize two target logs: DTC and DTS logs. The location of the data is a GitHub repository sourced from the Github repository maintained by the amazing team at Petrophysical Data-Driven Analytics The only way to find the best algorithm for a given problem is to try and test all algorithms It is time expensive to try out all possible machine learning algorithms for this project, so in the context for this article we will be using eXtreme Gradient Boosting (XGBoost) Algorithm. From the problem statement, we to predict two features making it a Multi-target regression problem. The XGBoost Regressor coupled with SKlearn’s MultiOutputRegressor would be applied. The name XGBoost, though, actually refers to the engineering goal to push the limit of computations resources for boosted tree algorithms. Which is the reason why many people use XGBoost. It is an implementation of gradient boosting machines created by Tianqi Chen, now with contributions from many developers. It belongs to a broader collection of tools under the umbrella of the Distributed Machine Learning Community or DMLC who are also the creators of the popular mxnet deep learning library. It is free open source software available for use under the permissive Apache-2 license that supports the following main interfaces: Command Line Interface (CLI). Python interface as well as a model in scikit-learn. C++ (the language in which the library is written). R interface as well as a model in the caret package. Julia. Java and JVM languages like Scala and platforms like Hadoop. The library is laser focused on Computational speed: Generally, XGBoost is fast. Really fast when compared to other implementations of gradient boosting.Model performance: XGBoost dominates structured or tabular datasets on classification and regression predictive modeling problems. The evidence is that it is the go-to algorithm for competition winners on the Kaggle competitive data science platform. Computational speed: Generally, XGBoost is fast. Really fast when compared to other implementations of gradient boosting. Model performance: XGBoost dominates structured or tabular datasets on classification and regression predictive modeling problems. The evidence is that it is the go-to algorithm for competition winners on the Kaggle competitive data science platform. XGBoost package can be install into the python environment by using the Python Package Index (PyPI) for a stable version. pip install xgboost Here, we start with importing all the python libraries we would be needing for this project. warning : Warning control for suppressing deprecated functions in python packages. numpy : For scientific computing. pandas : For data wrangling and analysis matplotlib: For visualizations of graphs and charts. xgboost : The machine learning algorithm used for prediction. MultiOutputRegressor : This provides the multi-target regression environment. StandardScaler : To scale the data train_test_split : To split the data RandomizedSearchCV : For random parameter tuning mean_square_error : Performance metric used to evaluate the predictions. Firstly, most times during data entry missing values are replaced with -999 , so it is ideal to identify it as a missing value indicator for the system. Here, white spaces as well as Nan and NaN were also identified as missing value indicator in the dataset. Data description of the respective features is as follows: CAL: Caliper log (unit in inch) CNC: Neuron log (unit in dec) GR: Gamma Ray log (unit in API) HRD: Deep Resistivity log (unit in Ohm per meter) HRM: Medium Resistivity log (unit in Ohm per meter) PE: Photo-electric Factor (unit in Barn) ZDEN: Density log (unit in Grams per cubit meter) DTC: Compressional Travel-time lo (unit in nanosecond per foot) DTS: Shear Travel-time log (unit in nanosecond per foot) DTC and DTS are called Sonic logs, which can be computed from the waveforms recorded at the receiver. The descriptive statistics is also computed. Checking for Missing values It can be observed that a colossal amount of missing values exists in the training data. Let’s have a view what the distribution of the data. Most of the feature’s histograms are uni-molar and others are skewed, filling the former with the previous value in the dataframe and the latter with the median will be highly logical. The filling with previous value method will be supported by pandas fillna backfill method and the median by the median.() method. The Feature engineering in the context of this publication is focused mainly gamma ray log (GR) feature. From the histogram, outliers can be observed, as GR values conventionally fall between 0–200. We will be creating two new features out of GR, while bounding it to the upper and lower limits. The two new features to be created are: gamma ray index (IGR)natural gamma radiation (NGR) gamma ray index (IGR) natural gamma radiation (NGR) The gamma ray log (GR) feature should be dropped after using it to create other features to reduce redundancy in the data. The training data is split with a 70:30 ratio Most machine models work best when various variables are put on the same scale. The XGBoost Regression is instantiated with already tuned hyperparameters. Hyperparameter tuning is a very time expensive procedure and was skipped in the article but can be referred and looked up in notebook on github. The model was fitted to the training data to aid the learning process. The final output of the model — predictions. Lower values of RMSE indicate better fit and the model is looking good! Lastly, the model is applied to data it hasn’t seen — ‘test’ data. I hope this article will broadening the horizons of the application of Machine Learning in the Petrophysics Industry. hanks for reading and stay safe.
[ { "code": null, "e": 723, "s": 172, "text": "Petrophysics is the study of the properties of rock and a brief description about the interactions of liquids. It is mainly used in the Oil and Gas industry to study the behavior of different kinds of reservoirs. It also explains the chemistry of pores of the subsurface and how they are connected. It helps in controlling the migration and accumulation of hydrocarbons, while explaining the chemical and physical properties, Petrophysics also explains many other related terms such as lithology, water saturation, density, permeability and porosity." }, { "code": null, "e": 921, "s": 723, "text": "Petrophysics emphasizes those properties relating to the pore system and its fluid distribution and flow characteristics. These properties and their relationships are used to identify and evaluate:" }, { "code": null, "e": 944, "s": 921, "text": "Hydrocarbon reservoirs" }, { "code": null, "e": 964, "s": 944, "text": "Hydrocarbon sources" }, { "code": null, "e": 970, "s": 964, "text": "Seals" }, { "code": null, "e": 979, "s": 970, "text": "Aquifers" }, { "code": null, "e": 1320, "s": 979, "text": "The petrophysicist or petrophysical engineer practices the science of petrophysics as a member of the reservoir management team. The petrophysicist provides answers on products needed and used by team members, as well as physical and chemical insights needed by other teammates. The reservoir and fluid characteristics to be determined are:" }, { "code": null, "e": 1347, "s": 1320, "text": "Thickness (bed boundaries)" }, { "code": null, "e": 1369, "s": 1347, "text": "Lithology (rock type)" }, { "code": null, "e": 1378, "s": 1369, "text": "Porosity" }, { "code": null, "e": 1410, "s": 1378, "text": "Fluid saturations and pressures" }, { "code": null, "e": 1452, "s": 1410, "text": "Fluid identification and characterization" }, { "code": null, "e": 1476, "s": 1452, "text": "Permeability (absolute)" }, { "code": null, "e": 1510, "s": 1476, "text": "Fractional flow (oil, gas, water)" }, { "code": null, "e": 2451, "s": 1510, "text": "It is easy to define these characteristics and to appreciate their part in the assessment of reserves. The difficult part comes in determining their actual value at a level of certainty needed to make economic decisions leading to development and production. The seven characteristics listed are interdependent (i.e., to properly determine porosity from a wireline log, one must know the lithology, fluid saturations, and fluid types). The science of petrophysics is then used to unscramble the hidden world of rock and fluid properties in reservoirs from just below the Earth’s surface to ones more than four miles deep. The petrophysicist then takes on many characteristics of the fictional sleuth Sherlock Holmes to extrapolate, from the most meager of clues, the true picture of the subsurface reservoir using dogged determination to wrest all possible information from the available data, all the while enjoying the thrill of the hunt." }, { "code": null, "e": 2655, "s": 2451, "text": "Archie’s general method is to subdivide the problem into smaller segments and iterate using all data until all data agree. One starting point is to determine rock types (petrofacies) wherein we identify:" }, { "code": null, "e": 2665, "s": 2655, "text": "Pore type" }, { "code": null, "e": 2688, "s": 2665, "text": "Pore size distribution" }, { "code": null, "e": 2705, "s": 2688, "text": "Pore throat type" }, { "code": null, "e": 2730, "s": 2705, "text": "Pore throat distribution" }, { "code": null, "e": 2935, "s": 2730, "text": "When coupled with fluid type, one can establish a capillary pressure model that will lead to understanding in-situ fluid saturations and fluid flow. However, the tools available to the petrophysicist are:" }, { "code": null, "e": 3022, "s": 2935, "text": "Mud logging (solids, liquids, gasses, volumes, rates, concentrations, and temperature)" }, { "code": null, "e": 3088, "s": 3022, "text": "Measurement while drilling (MWD) and Logging while drilling (LWD)" }, { "code": null, "e": 3128, "s": 3088, "text": "Wireline logging (open- and cased-hole)" }, { "code": null, "e": 3160, "s": 3128, "text": "Core sampling and core analysis" }, { "code": null, "e": 3209, "s": 3160, "text": "Fluid sampling (wireline and/or drillstem tests)" }, { "code": null, "e": 3999, "s": 3209, "text": "Compressional traveltime (DTC) and shear traveltime (DTS) logs are not acquired in all the wells drilled in a field due to financial or operational constraints. Under such circumstances, machine-learning techniques can be used to predict DTC and DTS logs to improve subsurface characterization. The goal of this Petrophysical Data-Driven Analytics project is to develop data-driven models by processing “easy-to-acquire” conventional logs from casr study ‘Well 1’, and use the data-driven models to generate synthetic DTC and DTS logs in case study ‘Well 2’. A robust data-driven model for the desired sonic-log synthesis will result in low prediction errors, which can be quantified in terms of root mean squared error (RME) by comparing the synthesized and the original DTC and DTS logs." }, { "code": null, "e": 4525, "s": 3999, "text": "Well datasets (comprising of Well 1 & Well 2) are provided, and the goal is to build a generalizable data-driven models using the Well 1 dataset. Following that, you will deploy the newly developed data-driven models on the Well 2 dataset to synthesize DTS and DTC logs. The data-driven model uses feature sets derived from the following seven logs: caliper, neutron, gamma ray, deep resistivity, medium resistivity, photoelectric factor and density. The data-driven model should synthesize two target logs: DTC and DTS logs." }, { "code": null, "e": 4678, "s": 4525, "text": "The location of the data is a GitHub repository sourced from the Github repository maintained by the amazing team at Petrophysical Data-Driven Analytics" }, { "code": null, "e": 4772, "s": 4678, "text": "The only way to find the best algorithm for a given problem is to try and test all algorithms" }, { "code": null, "e": 5146, "s": 4772, "text": "It is time expensive to try out all possible machine learning algorithms for this project, so in the context for this article we will be using eXtreme Gradient Boosting (XGBoost) Algorithm. From the problem statement, we to predict two features making it a Multi-target regression problem. The XGBoost Regressor coupled with SKlearn’s MultiOutputRegressor would be applied." }, { "code": null, "e": 5334, "s": 5146, "text": "The name XGBoost, though, actually refers to the engineering goal to push the limit of computations resources for boosted tree algorithms. Which is the reason why many people use XGBoost." }, { "code": null, "e": 5777, "s": 5334, "text": "It is an implementation of gradient boosting machines created by Tianqi Chen, now with contributions from many developers. It belongs to a broader collection of tools under the umbrella of the Distributed Machine Learning Community or DMLC who are also the creators of the popular mxnet deep learning library. It is free open source software available for use under the permissive Apache-2 license that supports the following main interfaces:" }, { "code": null, "e": 5807, "s": 5777, "text": "Command Line Interface (CLI)." }, { "code": null, "e": 5860, "s": 5807, "text": "Python interface as well as a model in scikit-learn." }, { "code": null, "e": 5912, "s": 5860, "text": "C++ (the language in which the library is written)." }, { "code": null, "e": 5965, "s": 5912, "text": "R interface as well as a model in the caret package." }, { "code": null, "e": 5972, "s": 5965, "text": "Julia." }, { "code": null, "e": 6033, "s": 5972, "text": "Java and JVM languages like Scala and platforms like Hadoop." }, { "code": null, "e": 6065, "s": 6033, "text": "The library is laser focused on" }, { "code": null, "e": 6437, "s": 6065, "text": "Computational speed: Generally, XGBoost is fast. Really fast when compared to other implementations of gradient boosting.Model performance: XGBoost dominates structured or tabular datasets on classification and regression predictive modeling problems. The evidence is that it is the go-to algorithm for competition winners on the Kaggle competitive data science platform." }, { "code": null, "e": 6559, "s": 6437, "text": "Computational speed: Generally, XGBoost is fast. Really fast when compared to other implementations of gradient boosting." }, { "code": null, "e": 6810, "s": 6559, "text": "Model performance: XGBoost dominates structured or tabular datasets on classification and regression predictive modeling problems. The evidence is that it is the go-to algorithm for competition winners on the Kaggle competitive data science platform." }, { "code": null, "e": 6932, "s": 6810, "text": "XGBoost package can be install into the python environment by using the Python Package Index (PyPI) for a stable version." }, { "code": null, "e": 6952, "s": 6932, "text": "pip install xgboost" }, { "code": null, "e": 7045, "s": 6952, "text": "Here, we start with importing all the python libraries we would be needing for this project." }, { "code": null, "e": 7128, "s": 7045, "text": "warning : Warning control for suppressing deprecated functions in python packages." }, { "code": null, "e": 7162, "s": 7128, "text": "numpy : For scientific computing." }, { "code": null, "e": 7203, "s": 7162, "text": "pandas : For data wrangling and analysis" }, { "code": null, "e": 7256, "s": 7203, "text": "matplotlib: For visualizations of graphs and charts." }, { "code": null, "e": 7318, "s": 7256, "text": "xgboost : The machine learning algorithm used for prediction." }, { "code": null, "e": 7396, "s": 7318, "text": "MultiOutputRegressor : This provides the multi-target regression environment." }, { "code": null, "e": 7431, "s": 7396, "text": "StandardScaler : To scale the data" }, { "code": null, "e": 7468, "s": 7431, "text": "train_test_split : To split the data" }, { "code": null, "e": 7517, "s": 7468, "text": "RandomizedSearchCV : For random parameter tuning" }, { "code": null, "e": 7590, "s": 7517, "text": "mean_square_error : Performance metric used to evaluate the predictions." }, { "code": null, "e": 7849, "s": 7590, "text": "Firstly, most times during data entry missing values are replaced with -999 , so it is ideal to identify it as a missing value indicator for the system. Here, white spaces as well as Nan and NaN were also identified as missing value indicator in the dataset." }, { "code": null, "e": 7908, "s": 7849, "text": "Data description of the respective features is as follows:" }, { "code": null, "e": 7940, "s": 7908, "text": "CAL: Caliper log (unit in inch)" }, { "code": null, "e": 7970, "s": 7940, "text": "CNC: Neuron log (unit in dec)" }, { "code": null, "e": 8002, "s": 7970, "text": "GR: Gamma Ray log (unit in API)" }, { "code": null, "e": 8052, "s": 8002, "text": "HRD: Deep Resistivity log (unit in Ohm per meter)" }, { "code": null, "e": 8104, "s": 8052, "text": "HRM: Medium Resistivity log (unit in Ohm per meter)" }, { "code": null, "e": 8145, "s": 8104, "text": "PE: Photo-electric Factor (unit in Barn)" }, { "code": null, "e": 8195, "s": 8145, "text": "ZDEN: Density log (unit in Grams per cubit meter)" }, { "code": null, "e": 8259, "s": 8195, "text": "DTC: Compressional Travel-time lo (unit in nanosecond per foot)" }, { "code": null, "e": 8316, "s": 8259, "text": "DTS: Shear Travel-time log (unit in nanosecond per foot)" }, { "code": null, "e": 8463, "s": 8316, "text": "DTC and DTS are called Sonic logs, which can be computed from the waveforms recorded at the receiver. The descriptive statistics is also computed." }, { "code": null, "e": 8491, "s": 8463, "text": "Checking for Missing values" }, { "code": null, "e": 8633, "s": 8491, "text": "It can be observed that a colossal amount of missing values exists in the training data. Let’s have a view what the distribution of the data." }, { "code": null, "e": 8948, "s": 8633, "text": "Most of the feature’s histograms are uni-molar and others are skewed, filling the former with the previous value in the dataframe and the latter with the median will be highly logical. The filling with previous value method will be supported by pandas fillna backfill method and the median by the median.() method." }, { "code": null, "e": 9284, "s": 8948, "text": "The Feature engineering in the context of this publication is focused mainly gamma ray log (GR) feature. From the histogram, outliers can be observed, as GR values conventionally fall between 0–200. We will be creating two new features out of GR, while bounding it to the upper and lower limits. The two new features to be created are:" }, { "code": null, "e": 9335, "s": 9284, "text": "gamma ray index (IGR)natural gamma radiation (NGR)" }, { "code": null, "e": 9357, "s": 9335, "text": "gamma ray index (IGR)" }, { "code": null, "e": 9387, "s": 9357, "text": "natural gamma radiation (NGR)" }, { "code": null, "e": 9510, "s": 9387, "text": "The gamma ray log (GR) feature should be dropped after using it to create other features to reduce redundancy in the data." }, { "code": null, "e": 9556, "s": 9510, "text": "The training data is split with a 70:30 ratio" }, { "code": null, "e": 9636, "s": 9556, "text": "Most machine models work best when various variables are put on the same scale." }, { "code": null, "e": 9927, "s": 9636, "text": "The XGBoost Regression is instantiated with already tuned hyperparameters. Hyperparameter tuning is a very time expensive procedure and was skipped in the article but can be referred and looked up in notebook on github. The model was fitted to the training data to aid the learning process." }, { "code": null, "e": 10111, "s": 9927, "text": "The final output of the model — predictions. Lower values of RMSE indicate better fit and the model is looking good! Lastly, the model is applied to data it hasn’t seen — ‘test’ data." } ]
Fixing a Broken Ubuntu GUI. Lessons learned from bad driver... | by Normaler Mensch | Towards Data Science
I switch between Windows and Flavors of Ubuntu a lot. I recently noticed that I haven’t used my Kubuntu PC in a while during which it gathered dust. I decided to bring it up to speed. Having had enough of Kubuntu, I switched to Ubuntu 20.04, which wasn’t all so much a pain to install, you know... the GUI support, and all. The trouble came afterward when the installation was slower than the economy during the pandemic. In the process of fixing these errors, I went through the all-too-familiar NVIDIA, light-dm issues that I had to go through a couple of times as a Ubuntu newbie. I decided to document it once and for all, for everybody suffering from new installations of Ubuntu like me. This is probably because Ubuntu defaults to the XOrg drivers with a new Installation. You can see that in your Software updates application under “Additional Drivers”. If Xorg is selected (Third option in the screenshot), it’s probably not the best. (Used up the majority of CPU in my case). In order to fix this, you now either have to: Install Proprietary drivers of your graphics card (Mine was NVIDIA GeForce GT)Find the latest stable version of drivers for your graphics card and install them Install Proprietary drivers of your graphics card (Mine was NVIDIA GeForce GT) Find the latest stable version of drivers for your graphics card and install them (You will know you have to do 2 when you try 1 and it fails on your face(!) So, if 1 worked for you, awesome, do a sudo reboot and you are good to go! If your GUI hung up for some reason, or the process didn’t finish successfully, you are better off switching back to Xorg and reinstalling stable drivers. If you don’t do this, your GUI gets all messed up on reboot. In my case, the reboot failed. It took me to a sad blinking cursor on a blank screen like so: In order to get out of this abyss, press ctrl + F1 (Or F2,3,4,5,6,7) until one of those works. ctrl + F1 you will enter a regular command-line interface from there. Log in with your user name and password. Then, execute these: sudo apt-get purge lightdmsudo apt-get updatesudo apt-get install lightdmdpkg-reconfigure lightdmsudo reboot This is because Ubuntu’s display is managed by lightdm package, which failed. You are purging it and reinstalling it to fix these issues. when you reconfigure lightdm, you will be asked if you want to stay with lightdm or change to GDM3. I stayed with lightdm because I was more familiar (And a lot of ppl on the internet complained about gdm as a manager with NVIDIA drivers) At this point, I was overjoyed because on rebooting, everything seemed to work and I came to my sign-in screen. While I typed my credentials with joy in my heart and spring in my step, my computer decided to just keep asking me for my credentials again and again. I WAS STUCK IN A LOGIN LOOP!! Note: If your dpkg reconfigure fails in this line, dpkg-reconfigure lightdm run this and you should be fine: sudo dpkg --configure -a If you cannot login to your account but the GUI is back, you have to fix your drivers from the command line (Ofcourse you have to! you broke them in step 1!!!) So now, Press Ctrl+F3 to get back control over your command line. (with Alt+arrow keys, you can switch between screens: Login, command line etc.). Login with your credentials. Ctrl+F3 There are 2 possible sources of failure here, Failure of configuration of .Xauthority permissons are messed upNVIDIA drivers are messed up .Xauthority permissons are messed up NVIDIA drivers are messed up In our case, we know it’s the drivers. If you want to check your Xauthority permissions, do this: ls -lA Now look for the line: -rw — — — — 1 user user 79 Sep 3 19:56 .Xauthority If instead of where your username has to be, you see: -rw — — — — 1 root root 79 Sep 3 19:56 .Xauthority You have to: chown username:username .Xauthority And you have your authority and you can log in! If that wasn’t the problem in the first place, get to reinstalling the drivers: sudo add-apt-repository ppa:graphics-drivers/ppasudo apt update Now look for what drivers are available: I used the third party free recommended driver. Install it (replace the last your-Nvidia-driver-here with the actual name of it from the above result): sudo apt install your-nvidia-driver-here If this worked, not only is your GUI back but also you have better drivers for your graphics card hardware! do a: sudo reboot This should do it! My computer now works like a good regular computer should and doesn’t take forever to startup. If you have had a similar problem, hope this helps!
[ { "code": null, "e": 495, "s": 171, "text": "I switch between Windows and Flavors of Ubuntu a lot. I recently noticed that I haven’t used my Kubuntu PC in a while during which it gathered dust. I decided to bring it up to speed. Having had enough of Kubuntu, I switched to Ubuntu 20.04, which wasn’t all so much a pain to install, you know... the GUI support, and all." }, { "code": null, "e": 864, "s": 495, "text": "The trouble came afterward when the installation was slower than the economy during the pandemic. In the process of fixing these errors, I went through the all-too-familiar NVIDIA, light-dm issues that I had to go through a couple of times as a Ubuntu newbie. I decided to document it once and for all, for everybody suffering from new installations of Ubuntu like me." }, { "code": null, "e": 1156, "s": 864, "text": "This is probably because Ubuntu defaults to the XOrg drivers with a new Installation. You can see that in your Software updates application under “Additional Drivers”. If Xorg is selected (Third option in the screenshot), it’s probably not the best. (Used up the majority of CPU in my case)." }, { "code": null, "e": 1202, "s": 1156, "text": "In order to fix this, you now either have to:" }, { "code": null, "e": 1362, "s": 1202, "text": "Install Proprietary drivers of your graphics card (Mine was NVIDIA GeForce GT)Find the latest stable version of drivers for your graphics card and install them" }, { "code": null, "e": 1441, "s": 1362, "text": "Install Proprietary drivers of your graphics card (Mine was NVIDIA GeForce GT)" }, { "code": null, "e": 1523, "s": 1441, "text": "Find the latest stable version of drivers for your graphics card and install them" }, { "code": null, "e": 1599, "s": 1523, "text": "(You will know you have to do 2 when you try 1 and it fails on your face(!)" }, { "code": null, "e": 1638, "s": 1599, "text": "So, if 1 worked for you, awesome, do a" }, { "code": null, "e": 1650, "s": 1638, "text": "sudo reboot" }, { "code": null, "e": 1674, "s": 1650, "text": "and you are good to go!" }, { "code": null, "e": 1984, "s": 1674, "text": "If your GUI hung up for some reason, or the process didn’t finish successfully, you are better off switching back to Xorg and reinstalling stable drivers. If you don’t do this, your GUI gets all messed up on reboot. In my case, the reboot failed. It took me to a sad blinking cursor on a blank screen like so:" }, { "code": null, "e": 2079, "s": 1984, "text": "In order to get out of this abyss, press ctrl + F1 (Or F2,3,4,5,6,7) until one of those works." }, { "code": null, "e": 2089, "s": 2079, "text": "ctrl + F1" }, { "code": null, "e": 2211, "s": 2089, "text": "you will enter a regular command-line interface from there. Log in with your user name and password. Then, execute these:" }, { "code": null, "e": 2320, "s": 2211, "text": "sudo apt-get purge lightdmsudo apt-get updatesudo apt-get install lightdmdpkg-reconfigure lightdmsudo reboot" }, { "code": null, "e": 2697, "s": 2320, "text": "This is because Ubuntu’s display is managed by lightdm package, which failed. You are purging it and reinstalling it to fix these issues. when you reconfigure lightdm, you will be asked if you want to stay with lightdm or change to GDM3. I stayed with lightdm because I was more familiar (And a lot of ppl on the internet complained about gdm as a manager with NVIDIA drivers)" }, { "code": null, "e": 2991, "s": 2697, "text": "At this point, I was overjoyed because on rebooting, everything seemed to work and I came to my sign-in screen. While I typed my credentials with joy in my heart and spring in my step, my computer decided to just keep asking me for my credentials again and again. I WAS STUCK IN A LOGIN LOOP!!" }, { "code": null, "e": 3042, "s": 2991, "text": "Note: If your dpkg reconfigure fails in this line," }, { "code": null, "e": 3067, "s": 3042, "text": "dpkg-reconfigure lightdm" }, { "code": null, "e": 3100, "s": 3067, "text": "run this and you should be fine:" }, { "code": null, "e": 3125, "s": 3100, "text": "sudo dpkg --configure -a" }, { "code": null, "e": 3285, "s": 3125, "text": "If you cannot login to your account but the GUI is back, you have to fix your drivers from the command line (Ofcourse you have to! you broke them in step 1!!!)" }, { "code": null, "e": 3461, "s": 3285, "text": "So now, Press Ctrl+F3 to get back control over your command line. (with Alt+arrow keys, you can switch between screens: Login, command line etc.). Login with your credentials." }, { "code": null, "e": 3469, "s": 3461, "text": "Ctrl+F3" }, { "code": null, "e": 3543, "s": 3469, "text": "There are 2 possible sources of failure here, Failure of configuration of" }, { "code": null, "e": 3608, "s": 3543, "text": ".Xauthority permissons are messed upNVIDIA drivers are messed up" }, { "code": null, "e": 3645, "s": 3608, "text": ".Xauthority permissons are messed up" }, { "code": null, "e": 3674, "s": 3645, "text": "NVIDIA drivers are messed up" }, { "code": null, "e": 3772, "s": 3674, "text": "In our case, we know it’s the drivers. If you want to check your Xauthority permissions, do this:" }, { "code": null, "e": 3779, "s": 3772, "text": "ls -lA" }, { "code": null, "e": 3802, "s": 3779, "text": "Now look for the line:" }, { "code": null, "e": 3853, "s": 3802, "text": "-rw — — — — 1 user user 79 Sep 3 19:56 .Xauthority" }, { "code": null, "e": 3907, "s": 3853, "text": "If instead of where your username has to be, you see:" }, { "code": null, "e": 3958, "s": 3907, "text": "-rw — — — — 1 root root 79 Sep 3 19:56 .Xauthority" }, { "code": null, "e": 3971, "s": 3958, "text": "You have to:" }, { "code": null, "e": 4007, "s": 3971, "text": "chown username:username .Xauthority" }, { "code": null, "e": 4055, "s": 4007, "text": "And you have your authority and you can log in!" }, { "code": null, "e": 4135, "s": 4055, "text": "If that wasn’t the problem in the first place, get to reinstalling the drivers:" }, { "code": null, "e": 4199, "s": 4135, "text": "sudo add-apt-repository ppa:graphics-drivers/ppasudo apt update" }, { "code": null, "e": 4240, "s": 4199, "text": "Now look for what drivers are available:" }, { "code": null, "e": 4392, "s": 4240, "text": "I used the third party free recommended driver. Install it (replace the last your-Nvidia-driver-here with the actual name of it from the above result):" }, { "code": null, "e": 4433, "s": 4392, "text": "sudo apt install your-nvidia-driver-here" }, { "code": null, "e": 4541, "s": 4433, "text": "If this worked, not only is your GUI back but also you have better drivers for your graphics card hardware!" }, { "code": null, "e": 4547, "s": 4541, "text": "do a:" }, { "code": null, "e": 4559, "s": 4547, "text": "sudo reboot" }, { "code": null, "e": 4578, "s": 4559, "text": "This should do it!" } ]
How to Iterate Over Rows in a Pandas DataFrame | Towards Data Science
Iterating over pandas DataFrames is definitely not a best practise and you should only consider doing so only when this is absolutely necessary and when you have exhausted every other possible option that is likely to be more elegant and efficient. Iterating through pandas objects is generally slow. In many cases, iterating manually over the rows is not needed and can be avoided — pandas documentation In today’s article, we will discuss how to avoid iterating through DataFrames in pandas. We’ll also go through a “checklist” that you may need to reference every time before choosing to go with an iterative approach. Additionally, we will explore how to do so in cases where no other option is suitable to your specific use-case. Lastly, we will discuss why you should avoid modifying pandas object while iterating over them. As highlighted in the official pandas documentation, the iteration through DataFrames is very inefficient and it can usually be avoided. Usually, pandas newcomers are not familiar with the concept of vectorisation and are unaware that most operations in pandas should (and can) be performed in a non-iterative context. Before attempting to iterate through pandas objects, you must first ensure that none of the options below suit the needs of your use-case: Vectorisation over iteration: pandas comes with rich set of built-in methods whose performance is optimised. Most of the operations could potentially be performed using one of these methods. Additionally, you can even take a look at numpy and check whether any of its functions can be used in your context. Applying a function to rows: A common requirement is definitely when it comes to apply a function to every row, which designed to work — say — over only one row at a time, and not on the full DataFrame or Series. In such cases, it’s always best to use apply() method instead of iterating through the pandas object. For more details, you can refer to this section of the pandas documentation that explains how to apply your own or another library’s functions to pandas objects. Iterative manipulations: In case you need to perform iterative manipulations and at the same time performance is a concern, then you may have to take a look into cython or numba. For more details around these concepts you can read this section of the pandas documentation. Printing a DataFrame: If you want to print out a DataFrame then simply use DataFrame.to_string() method in order to render the DataFrame to a console-friendly tabular output. In case none of the above options will work for you, then you may still want to iterate through pandas objects. You can do so using either iterrows() or itertuples() built-in methods. Before seeing both methods in action, let’s create an example DataFrame that we’ll use to iterate over. import pandas as pddf = pd.DataFrame({ 'colA': [1, 2, 3, 4, 5], 'colB': ['a', 'b', 'c', 'd', 'e'], 'colC': [True, True, False, True, False],})print(df) colA colB colC0 1 a True1 2 b True2 3 c False3 4 d True4 5 e False pandas.DataFrame.iterrows() method is used to iterate over DataFrame rows as (index, Series) pairs. Note that this method does not preserve the dtypes across rows due to the fact that this method will convert each row into a Series. If you need to preserve the dtypes of the pandas object, then you should use itertuples() method instead. for index, row in df.iterrows(): print(row['colA'], row['colB'], row['colC'])1 a True2 b True3 c False4 d True5 e False pandas.DataFrame.itertuples() method is used to iterate over DataFrame rows as namedtuples. In general, itertuples() is expected to be faster compared to iterrows(). for row in df.itertuples(): print(row.colA, row.colB, row.colC)1 a True2 b True3 c False4 d True5 e False For more details regarding Named Tuples in Python, you can read the article below. towardsdatascience.com At this point, it’s important to highlight that you should never modify a pandas DataFrame or Series you are iterating over. Depending on the data types of your pandas object, the iterator may return a copy of the object rather than a view. In this case, writing anything to a copy won’t have the desired effect. For instance, let’s suppose we want to double the values of each row in colA. An iterative approach won’t do the trick: for index, row in df.iterrows(): row['colA'] = row['colA'] * 2print(df) colA colB colC0 1 a True1 2 b True2 3 c False3 4 d True4 5 e False In similar use-cases, you should use apply() method instead. df['colA'] = df['colA'].apply(lambda x: x * 2)print(df) colA colB colC0 2 a True1 4 b True2 6 c False3 8 d True4 10 e False In today’s article, we discussed why it’s important to avoid iterative approaches while working with pandas objects and prefer vectorised or really any other approach that is suitable to your specific use-case. pandas comes with a rich set of built-in methods which are optimized to work on large pandas objects and you should always favour these over any other iterative solution. In case you still want/have to iterate over a DataFrame or Series, you can use iterrows() or itertuples() methods. Lastly, we discussed why you must always avoid modifying a pandas object that you are iterating through as this may not work as expected. Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You may also like
[ { "code": null, "e": 421, "s": 172, "text": "Iterating over pandas DataFrames is definitely not a best practise and you should only consider doing so only when this is absolutely necessary and when you have exhausted every other possible option that is likely to be more elegant and efficient." }, { "code": null, "e": 554, "s": 421, "text": "Iterating through pandas objects is generally slow. In many cases, iterating manually over the rows is not needed and can be avoided" }, { "code": null, "e": 577, "s": 554, "text": "— pandas documentation" }, { "code": null, "e": 1003, "s": 577, "text": "In today’s article, we will discuss how to avoid iterating through DataFrames in pandas. We’ll also go through a “checklist” that you may need to reference every time before choosing to go with an iterative approach. Additionally, we will explore how to do so in cases where no other option is suitable to your specific use-case. Lastly, we will discuss why you should avoid modifying pandas object while iterating over them." }, { "code": null, "e": 1322, "s": 1003, "text": "As highlighted in the official pandas documentation, the iteration through DataFrames is very inefficient and it can usually be avoided. Usually, pandas newcomers are not familiar with the concept of vectorisation and are unaware that most operations in pandas should (and can) be performed in a non-iterative context." }, { "code": null, "e": 1461, "s": 1322, "text": "Before attempting to iterate through pandas objects, you must first ensure that none of the options below suit the needs of your use-case:" }, { "code": null, "e": 1768, "s": 1461, "text": "Vectorisation over iteration: pandas comes with rich set of built-in methods whose performance is optimised. Most of the operations could potentially be performed using one of these methods. Additionally, you can even take a look at numpy and check whether any of its functions can be used in your context." }, { "code": null, "e": 2245, "s": 1768, "text": "Applying a function to rows: A common requirement is definitely when it comes to apply a function to every row, which designed to work — say — over only one row at a time, and not on the full DataFrame or Series. In such cases, it’s always best to use apply() method instead of iterating through the pandas object. For more details, you can refer to this section of the pandas documentation that explains how to apply your own or another library’s functions to pandas objects." }, { "code": null, "e": 2518, "s": 2245, "text": "Iterative manipulations: In case you need to perform iterative manipulations and at the same time performance is a concern, then you may have to take a look into cython or numba. For more details around these concepts you can read this section of the pandas documentation." }, { "code": null, "e": 2693, "s": 2518, "text": "Printing a DataFrame: If you want to print out a DataFrame then simply use DataFrame.to_string() method in order to render the DataFrame to a console-friendly tabular output." }, { "code": null, "e": 2877, "s": 2693, "text": "In case none of the above options will work for you, then you may still want to iterate through pandas objects. You can do so using either iterrows() or itertuples() built-in methods." }, { "code": null, "e": 2981, "s": 2877, "text": "Before seeing both methods in action, let’s create an example DataFrame that we’ll use to iterate over." }, { "code": null, "e": 3257, "s": 2981, "text": "import pandas as pddf = pd.DataFrame({ 'colA': [1, 2, 3, 4, 5], 'colB': ['a', 'b', 'c', 'd', 'e'], 'colC': [True, True, False, True, False],})print(df) colA colB colC0 1 a True1 2 b True2 3 c False3 4 d True4 5 e False" }, { "code": null, "e": 3596, "s": 3257, "text": "pandas.DataFrame.iterrows() method is used to iterate over DataFrame rows as (index, Series) pairs. Note that this method does not preserve the dtypes across rows due to the fact that this method will convert each row into a Series. If you need to preserve the dtypes of the pandas object, then you should use itertuples() method instead." }, { "code": null, "e": 3719, "s": 3596, "text": "for index, row in df.iterrows(): print(row['colA'], row['colB'], row['colC'])1 a True2 b True3 c False4 d True5 e False" }, { "code": null, "e": 3885, "s": 3719, "text": "pandas.DataFrame.itertuples() method is used to iterate over DataFrame rows as namedtuples. In general, itertuples() is expected to be faster compared to iterrows()." }, { "code": null, "e": 3994, "s": 3885, "text": "for row in df.itertuples(): print(row.colA, row.colB, row.colC)1 a True2 b True3 c False4 d True5 e False" }, { "code": null, "e": 4077, "s": 3994, "text": "For more details regarding Named Tuples in Python, you can read the article below." }, { "code": null, "e": 4100, "s": 4077, "text": "towardsdatascience.com" }, { "code": null, "e": 4413, "s": 4100, "text": "At this point, it’s important to highlight that you should never modify a pandas DataFrame or Series you are iterating over. Depending on the data types of your pandas object, the iterator may return a copy of the object rather than a view. In this case, writing anything to a copy won’t have the desired effect." }, { "code": null, "e": 4533, "s": 4413, "text": "For instance, let’s suppose we want to double the values of each row in colA. An iterative approach won’t do the trick:" }, { "code": null, "e": 4720, "s": 4533, "text": "for index, row in df.iterrows(): row['colA'] = row['colA'] * 2print(df) colA colB colC0 1 a True1 2 b True2 3 c False3 4 d True4 5 e False" }, { "code": null, "e": 4781, "s": 4720, "text": "In similar use-cases, you should use apply() method instead." }, { "code": null, "e": 4951, "s": 4781, "text": "df['colA'] = df['colA'].apply(lambda x: x * 2)print(df) colA colB colC0 2 a True1 4 b True2 6 c False3 8 d True4 10 e False" }, { "code": null, "e": 5162, "s": 4951, "text": "In today’s article, we discussed why it’s important to avoid iterative approaches while working with pandas objects and prefer vectorised or really any other approach that is suitable to your specific use-case." }, { "code": null, "e": 5448, "s": 5162, "text": "pandas comes with a rich set of built-in methods which are optimized to work on large pandas objects and you should always favour these over any other iterative solution. In case you still want/have to iterate over a DataFrame or Series, you can use iterrows() or itertuples() methods." }, { "code": null, "e": 5586, "s": 5448, "text": "Lastly, we discussed why you must always avoid modifying a pandas object that you are iterating through as this may not work as expected." }, { "code": null, "e": 5703, "s": 5586, "text": "Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read." } ]
Cypress - Data Driven Testing
Cypress data driven testing is achieved with the help of fixtures. Cypress fixtures are added to maintain and hold the test data for automation. The fixtures are kept inside the fixtures folder (example.json file) in the Cypress project.Basically, it helps us to get data input from external files. Cypress fixtures folder can have files in JavaScript Object Notation (JSON) or other formats and the data is maintained in "key:value" pairs. All the test data can be utilised by more than one test. All fixture data has to be declared within the before hook block. The syntax for Cypress data driven testing is as follows − cy.fixture(path of test data) cy.fixture(path of test data, encoding type) cy.fixture(path of test data, opts) cy.fixture(path of test data, encoding type, options) Here, path of test data is the path of test data file within fixtures folder. path of test data is the path of test data file within fixtures folder. encoding type − Encoding type (utf-8, asci, and so on) is used to read the file. encoding type − Encoding type (utf-8, asci, and so on) is used to read the file. Opts − Modifies the timeout for response. The default value is 30000ms. The wait time for cy.fixture(), prior throws an exception. Opts − Modifies the timeout for response. The default value is 30000ms. The wait time for cy.fixture(), prior throws an exception. Given below is the implementation of data driven testing with example.json in Cypress − { "email": "[email protected]", "password": "Test@123" } The implementation of actual data driven testing in Cypress is as follows − describe('Tutorialspoint Test', function () { //part of before hook before(function(){ //access fixture data cy.fixture('example').then(function(signInData){ this.signInData = signInData }) }) // test case it('Test Case1', function (){ // launch URL cy.visit("https://www.linkedin.com/") //data driven from fixture cy.get('#session_key ') .type(this.signInData.email) cy.get('# session_password').type(this.signInData.password) }); }); Execution Results The output is as follows The output logs show the values [email protected] and Test@123 being fed to the Email and Password fields respectively. These data have been passed to the test from the fixtures. 73 Lectures 12 hours Rahul Shetty Print Add Notes Bookmark this page
[ { "code": null, "e": 2642, "s": 2497, "text": "Cypress data driven testing is achieved with the help of fixtures. Cypress fixtures are added to maintain and hold the test data for automation." }, { "code": null, "e": 2796, "s": 2642, "text": "The fixtures are kept inside the fixtures folder (example.json file) in the Cypress project.Basically, it helps us to get data input from external files." }, { "code": null, "e": 2938, "s": 2796, "text": "Cypress fixtures folder can have files in JavaScript Object Notation (JSON) or other formats and the data is maintained in \"key:value\" pairs." }, { "code": null, "e": 3061, "s": 2938, "text": "All the test data can be utilised by more than one test. All fixture data has to be declared within the before hook block." }, { "code": null, "e": 3120, "s": 3061, "text": "The syntax for Cypress data driven testing is as follows −" }, { "code": null, "e": 3286, "s": 3120, "text": "cy.fixture(path of test data)\ncy.fixture(path of test data, encoding type)\ncy.fixture(path of test data, opts)\ncy.fixture(path of test data, encoding type, options)\n" }, { "code": null, "e": 3292, "s": 3286, "text": "Here," }, { "code": null, "e": 3364, "s": 3292, "text": "path of test data is the path of test data file within fixtures folder." }, { "code": null, "e": 3436, "s": 3364, "text": "path of test data is the path of test data file within fixtures folder." }, { "code": null, "e": 3517, "s": 3436, "text": "encoding type − Encoding type (utf-8, asci, and so on) is used to read the file." }, { "code": null, "e": 3598, "s": 3517, "text": "encoding type − Encoding type (utf-8, asci, and so on) is used to read the file." }, { "code": null, "e": 3729, "s": 3598, "text": "Opts − Modifies the timeout for response. The default value is 30000ms. The wait\ntime for cy.fixture(), prior throws an exception." }, { "code": null, "e": 3860, "s": 3729, "text": "Opts − Modifies the timeout for response. The default value is 30000ms. The wait\ntime for cy.fixture(), prior throws an exception." }, { "code": null, "e": 3948, "s": 3860, "text": "Given below is the implementation of data driven testing with example.json in Cypress −" }, { "code": null, "e": 4012, "s": 3948, "text": "{\n \"email\": \"[email protected]\",\n \"password\": \"Test@123\"\n}\n" }, { "code": null, "e": 4088, "s": 4012, "text": "The implementation of actual data driven testing in Cypress is as follows −" }, { "code": null, "e": 4605, "s": 4088, "text": "describe('Tutorialspoint Test', function () {\n //part of before hook\n before(function(){\n //access fixture data\n cy.fixture('example').then(function(signInData){\n this.signInData = signInData\n })\n })\n // test case\n it('Test Case1', function (){\n // launch URL\n cy.visit(\"https://www.linkedin.com/\")\n //data driven from fixture\n cy.get('#session_key ')\n .type(this.signInData.email)\n cy.get('# session_password').type(this.signInData.password)\n });\n});" }, { "code": null, "e": 4623, "s": 4605, "text": "Execution Results" }, { "code": null, "e": 4648, "s": 4623, "text": "The output is as follows" }, { "code": null, "e": 4827, "s": 4648, "text": "The output logs show the values [email protected] and Test@123 being fed to the Email and Password fields respectively. These data have been passed to the test from the fixtures." }, { "code": null, "e": 4861, "s": 4827, "text": "\n 73 Lectures \n 12 hours \n" }, { "code": null, "e": 4875, "s": 4861, "text": " Rahul Shetty" }, { "code": null, "e": 4882, "s": 4875, "text": " Print" }, { "code": null, "e": 4893, "s": 4882, "text": " Add Notes" } ]
Sentiment Analysis on the Texts of Harry Potter | by Greg Rafferty | Towards Data Science
I’m Greg Rafferty, a data scientist in the Bay Area. You can check out the code for this project on my github. Feel free to contact me with any questions! In this series of posts, I’m looking at a few handy NLP techniques, through the lens of Harry Potter. Previous posts in this series on basic NLP looked at Topic Modeling with Latent Dirichlet Allocation, Regular Expressions, and text summarization. In a previous post I looked at topic modeling, which is an NLP technique to learn the subject of a given text. Sentiment analysis exists to learn what was said about that topic — was it good or bad? With the growing use of the internet in our daily lives, vast amounts of unstructured text is being published every second of every day, in blog posts, forums, social media, and review sites, to name a few. Sentiment analysis systems can take this unstructured data and automatically add structure to it, capturing the public’s opinion about products, services, brands, politics, etc. This data holds immense value in the fields of marketing analysis, public relations, product reviews, net promoter scoring, product feedback, and customer service, for example. I’ve been demonstrating a lot of these NLP tasks using the text of Harry Potter. The books are rich in emotionally charged experiences that the reader can viscerally feel. Can a computer capture that feeling? Let’s take a look. I used C.J. Hutto’s VADER package to extract the sentiment of each book. VADER, which stands for Valence Aware Dictionary and sEntiment Reasoning, is a lexicon and rule-based tool that is specifically tuned to social media. Given a string of text, it outputs a decimal between 0 and 1 for each of negativity, positivity, and neutrality for the text, as well as a compound score from -1 to 1 which is an aggregate measure. A complete description of the development, validation, and evaluation of the VADER package can be read in this paper, but the gist is that the package’s authors first constructed a list of lexical features correlated with sentiment and then combined the list with some rules that describe how the grammatical structure of a phrase will intensify or diminish the sentiment. When tested against human raters, VADER outperforms with accuracy scores of 96% to 84%. VADER works best on short texts (a couple sentences at most), and applying it to an entire chapter at once resulted in extreme and largely worthless scores. Instead, I looped over each sentence individually, got the VADER scores, and then took an average of all sentences in a chapter. By plotting at the VADER compound score for each chapter of each book, we can clearly mark events in the books. The three greatest spikes in that chart above are Harry being chosen by the Goblet of Fire around chapter 70 of the series, Cedric Diggory’s death at about chapter 88, and Dumbledore’s death at about chapter 160. Here’s the code to produce that chart (the full notebook is available on my Github). The data exists in a dictionary with each book’s title as a key; the value for each book is another dictionary with each chapter number as a key. The value for each chapter is a tuple consisting of the chapter title and the chapter text. I defined a function to calculate the moving average of the data, which essentially smooths out the curve a bit and makes it easier to see long multi-chapter arcs throughout the stories. In order to plot each book as a different color, I created a dictionary called book_indices with each book’s title as the key and the values being a 2-element tuple of the book’s starting chapter number and ending chapter number (as if all the books were concatenated with chapters numbered sequentially throughout the entire series). I then plotted the story arc in segments based upon their chapter numbers. import matplotlib.pyplot as plt# Use FiveThirtyEight style themeplt.style.use('fivethirtyeight')# Moving Average function used for the dotted linedef movingaverage(interval, window_size): window = np.ones(int(window_size))/float(window_size) return np.convolve(interval, window, 'same')length = sum([len(hp[book]) for book in hp])x = np.linspace(0, length - 1, num=length)y = [hp[book][chapter][2]['compound'] for book in hp for chapter in hp[book]]plt.figure(figsize=(15, 10))for book in book_indices: plt.plot(x[book_indices[book][0]: book_indices[book][1]], y[book_indices[book][0]: book_indices[book][1]], label=book)plt.plot(movingaverage(y, 10), color='k', linewidth=3, linestyle=':', label = 'Moving Average')plt.axhline(y=0, xmin=0, xmax=length, alpha=.25, color='r', linestyle='--', linewidth=3)plt.legend(loc='best', fontsize=15)plt.title('Emotional Sentiment of the Harry Potter series', fontsize=20)plt.xlabel('Chapter', fontsize=15)plt.ylabel('Average Sentiment', fontsize=15)plt.show() I also made this same chart using the TextBlob Naive Bayes and Pattern analyzers with worse results (see the Jupyter notebook on my Github for these charts). The Naive Bayes model was trained on movie reviews which must not translate well to the Harry Potter universe. The Pattern analyzer worked much better (almost as well as VADER); it is based on the Pattern library, a rule-based model very similar to VADER. I also looked at emotions by using a lexicon created by the National Research Council of Canada of over 14,000 words, each scored as either associated or not-associated with any of two sentiments (negative, positive) or eight emotions (anger, anticipation, disgust, fear, joy, sadness, surprise, trust). They kindly provided me access to the lexicon, and I wrote up a Python script which loops over each word in a chapter, looks it up in the lexicon, and outputs whichever emotions the word was associated with. Each chapter was then assigned a score for each emotion corresponding to a ratio of how many words associated with that emotion the chapter contains compared to the total word count in the chapter (this basically normalizes the scores). Here are plots of the ‘Anger’ and ‘Sadness’ sentiments. I find it interesting that anger always exists with sadness, but sadness can sometimes exist without anger: Again, take a look at the Jupyter notebook on my Github to see detailed charts for all sentiments. Here’s a condensed version: Let’s see how I made all those subplots: length = sum([len(hp[book]) for book in hp])x = np.linspace(0, length - 1, num=length)fig, ax = plt.subplots(4, 3, figsize=(15, 15), facecolor='w', edgecolor='k')fig.subplots_adjust(hspace = .5, wspace=.1)fig.suptitle('Sentiment of the Harry Potter series', fontsize=20, y=1.02)fig.subplots_adjust(top=0.88)ax = ax.ravel()for i, emotion in enumerate(emotions): y = [hp_df.loc[book].loc[hp[book][chapter][0]][emotion] for book in hp for chapter in hp[book]] for book in book_indices: ax[i].plot(x[book_indices[book][0]: book_indices[book][1]], y[book_indices[book][0]: book_indices[book][1]], label=book, linewidth=2)ax[i].set_title('{} Sentiment'.format(emotion.title())) ax[i].set_xticks([])fig.legend(list(hp), loc='upper right', fontsize=15, bbox_to_anchor=(.85, .2))fig.tight_layout()fig.delaxes(ax[-1])fig.delaxes(ax[-2])plt.show() But it really becomes interesting to see how all the sentiments compare to each other. Overlaying 10 lines with this much variance quickly became a mess, so I again used the moving average: It’s interesting to see contradicting emotions acting counter to each other, most obviously the pink and brown lines above for ‘Positive’ and ‘Negative’ sentiment. Note that, due to the moving average window size of 20 data points, the first 10 and last 10 chapters have been left off the plot. I removed the y-axis because those numbers are meaningless to us (mere decimals: the ratio of words of that emotion to total words in the chapter). I also removed the horizontal and vertical chart lines to clean up the plot. I don’t particularly care to mark regular chapter numbers but I do want to mark the books; therefore, I added those vertical dotted lines. The legend has been reversed in this plot, which isn’t really necessary for readability or anything but I did it for consistency with the area and column charts coming up next. Here’s how I made it: # use the Tableau color scheme of 10 colorstab10 = matplotlib.cm.get_cmap('tab10')length = sum([len(hp[book]) for book in hp])window = 20# use index slicing to remove data points outside the windowx = np.linspace(0, length - 1, num=length)[int(window / 2): -int(window / 2)]fig = plt.figure(figsize=(15, 15))ax =fig.add_subplot(1, 1, 1)# Loop over the emotions with enumerate in order to track colorsfor c, emotion in enumerate(emotions): y = movingaverage([hp_df.loc[book].loc[hp[book][chapter][0]][emotion] for book in hp for chapter in hp[book]], window)[int(window / 2): -int(window / 2)] plt.plot(x, y, linewidth=5, label=emotion, color=(tab10(c))) # Plot vertical lines marking the booksfor book in book_indices: plt.axvline(x=book_indices[book][0], color='black', linewidth=2, linestyle=':')plt.axvline(x=book_indices[book][1], color='black', linewidth=2, linestyle=':')plt.legend(loc='best', fontsize=15, bbox_to_anchor=(1.2, 1))plt.title('Emotional Sentiment of the Harry Potter series', fontsize=20)plt.ylabel('Relative Sentiment', fontsize=15)# Use the book titles for X ticks, rotate them, center the left edgeplt.xticks([(book_indices[book][0] + book_indices[book][1]) / 2 for book in book_indices], list(hp), rotation=-30, fontsize=15, ha='left')plt.yticks([])# Reverse the order of the legendhandles, labels = ax.get_legend_handles_labels()ax.legend(handles[::-1], labels[::-1], loc='best', fontsize=15, bbox_to_anchor=(1.2, 1))ax.grid(False)plt.show() I also made an area plot to show the overall emotive qualities of each chapter. This is again a moving average in order to smooth out the more extreme spikes and to show the story arc better across all books: The books seem to start with a bit of trailing emotion from the previous story but quickly calm down during the middle chapters only to pick back up again at the end. length = sum([len(hp[book]) for book in hp])window = 10x = np.linspace(0, length - 1, num=length)[int(window / 2): -int(window / 2)]fig = plt.figure(figsize=(15, 15))ax = fig.add_subplot(1, 1, 1)y = [movingaverage(hp_df[emotion].tolist(), window)[int(window / 2): -int(window / 2)] for emotion in emotions]plt.stackplot(x, y, colors=(tab10(0), tab10(.1), tab10(.2), tab10(.3), tab10(.4), tab10(.5), tab10(.6), tab10(.7), tab10(.8), tab10(.9)), labels=emotions)# Plot vertical lines marking the booksfor book in book_indices: plt.axvline(x=book_indices[book][0], color='black', linewidth=3, linestyle=':')plt.axvline(x=book_indices[book][1], color='black', linewidth=3, linestyle=':')plt.title('Emotional Sentiment of the Harry Potter series', fontsize=20)plt.xticks([(book_indices[book][0] + book_indices[book][1]) / 2 for book in book_indices], list(hp), rotation=-30, fontsize=15, ha='left')plt.yticks([])plt.ylabel('Relative Sentiment', fontsize=15)# Reverse the legendhandles, labels = ax.get_legend_handles_labels()ax.legend(handles[::-1], labels[::-1], loc='best', fontsize=15, bbox_to_anchor=(1.2, 1))ax.grid(False)plt.show() Note how in this chart, reversing the legend became necessary for readability. By default, the legend items are added in alphabetical order going down, but the data is stacked from the bottom up. So the colors of the legend and the area plot run in opposite direction — to my eye, quite confusing and difficult to follow. So with ‘Anger’ plotted at the bottom, I also wanted it to be on the bottom of the legend and likewise with ‘Trust’ at the top. And lastly, a stacked bar chart to show the weights of the various sentiments across the books: Naturally, words associated with any of the positive emotions would also be associated with the ‘Positive’ sentiment, and likewise for ‘Negative’, so it shouldn’t come as a surprise that those two sentiments carry the bulk of the emotive quality of the books. I find it notable that the emotions are relatively consistent from book to book with just slight differences in magnitude but consistent weights, except for the ‘Fear’ emotion in red; it seems to exhibit the most variance across the series. I also would have expected the cumulative magnitude of sentiments to increase throughout the series as the stakes became higher and higher; however although the final book is indeed the highest, the other 6 books don’t show this gradual increase but almost the opposite, with a constant decline starting with book 2. books = list(hp)margin_bottom = np.zeros(len(books))fig = plt.figure(figsize=(15, 15))ax = fig.add_subplot(1, 1, 1)for c, emotion in enumerate(emotions): y = np.array(hp_df2[emotion]) plt.bar(books, y, bottom=margin_bottom, label=emotion, color=(tab10(c))) margin_bottom += y# Reverse the legendhandles, labels = ax.get_legend_handles_labels()ax.legend(handles[::-1], labels[::-1], loc='best', fontsize=15, bbox_to_anchor=(1.2, 1))plt.title('Emotional Sentiment of the Harry Potter series', fontsize=20)plt.xticks(books, books, rotation=-30, ha='left', fontsize=15)plt.ylabel('Relative Sentiment Score', fontsize=15)plt.yticks([])ax.grid(False)plt.show() The tricky bit in this plot is using the margin_bottom variable to stack each of the columns. Other than that, it just uses a couple tricks from the previous plots.
[ { "code": null, "e": 327, "s": 172, "text": "I’m Greg Rafferty, a data scientist in the Bay Area. You can check out the code for this project on my github. Feel free to contact me with any questions!" }, { "code": null, "e": 576, "s": 327, "text": "In this series of posts, I’m looking at a few handy NLP techniques, through the lens of Harry Potter. Previous posts in this series on basic NLP looked at Topic Modeling with Latent Dirichlet Allocation, Regular Expressions, and text summarization." }, { "code": null, "e": 1337, "s": 576, "text": "In a previous post I looked at topic modeling, which is an NLP technique to learn the subject of a given text. Sentiment analysis exists to learn what was said about that topic — was it good or bad? With the growing use of the internet in our daily lives, vast amounts of unstructured text is being published every second of every day, in blog posts, forums, social media, and review sites, to name a few. Sentiment analysis systems can take this unstructured data and automatically add structure to it, capturing the public’s opinion about products, services, brands, politics, etc. This data holds immense value in the fields of marketing analysis, public relations, product reviews, net promoter scoring, product feedback, and customer service, for example." }, { "code": null, "e": 1565, "s": 1337, "text": "I’ve been demonstrating a lot of these NLP tasks using the text of Harry Potter. The books are rich in emotionally charged experiences that the reader can viscerally feel. Can a computer capture that feeling? Let’s take a look." }, { "code": null, "e": 1987, "s": 1565, "text": "I used C.J. Hutto’s VADER package to extract the sentiment of each book. VADER, which stands for Valence Aware Dictionary and sEntiment Reasoning, is a lexicon and rule-based tool that is specifically tuned to social media. Given a string of text, it outputs a decimal between 0 and 1 for each of negativity, positivity, and neutrality for the text, as well as a compound score from -1 to 1 which is an aggregate measure." }, { "code": null, "e": 2448, "s": 1987, "text": "A complete description of the development, validation, and evaluation of the VADER package can be read in this paper, but the gist is that the package’s authors first constructed a list of lexical features correlated with sentiment and then combined the list with some rules that describe how the grammatical structure of a phrase will intensify or diminish the sentiment. When tested against human raters, VADER outperforms with accuracy scores of 96% to 84%." }, { "code": null, "e": 2734, "s": 2448, "text": "VADER works best on short texts (a couple sentences at most), and applying it to an entire chapter at once resulted in extreme and largely worthless scores. Instead, I looped over each sentence individually, got the VADER scores, and then took an average of all sentences in a chapter." }, { "code": null, "e": 3059, "s": 2734, "text": "By plotting at the VADER compound score for each chapter of each book, we can clearly mark events in the books. The three greatest spikes in that chart above are Harry being chosen by the Goblet of Fire around chapter 70 of the series, Cedric Diggory’s death at about chapter 88, and Dumbledore’s death at about chapter 160." }, { "code": null, "e": 3979, "s": 3059, "text": "Here’s the code to produce that chart (the full notebook is available on my Github). The data exists in a dictionary with each book’s title as a key; the value for each book is another dictionary with each chapter number as a key. The value for each chapter is a tuple consisting of the chapter title and the chapter text. I defined a function to calculate the moving average of the data, which essentially smooths out the curve a bit and makes it easier to see long multi-chapter arcs throughout the stories. In order to plot each book as a different color, I created a dictionary called book_indices with each book’s title as the key and the values being a 2-element tuple of the book’s starting chapter number and ending chapter number (as if all the books were concatenated with chapters numbered sequentially throughout the entire series). I then plotted the story arc in segments based upon their chapter numbers." }, { "code": null, "e": 5012, "s": 3979, "text": "import matplotlib.pyplot as plt# Use FiveThirtyEight style themeplt.style.use('fivethirtyeight')# Moving Average function used for the dotted linedef movingaverage(interval, window_size): window = np.ones(int(window_size))/float(window_size) return np.convolve(interval, window, 'same')length = sum([len(hp[book]) for book in hp])x = np.linspace(0, length - 1, num=length)y = [hp[book][chapter][2]['compound'] for book in hp for chapter in hp[book]]plt.figure(figsize=(15, 10))for book in book_indices: plt.plot(x[book_indices[book][0]: book_indices[book][1]], y[book_indices[book][0]: book_indices[book][1]], label=book)plt.plot(movingaverage(y, 10), color='k', linewidth=3, linestyle=':', label = 'Moving Average')plt.axhline(y=0, xmin=0, xmax=length, alpha=.25, color='r', linestyle='--', linewidth=3)plt.legend(loc='best', fontsize=15)plt.title('Emotional Sentiment of the Harry Potter series', fontsize=20)plt.xlabel('Chapter', fontsize=15)plt.ylabel('Average Sentiment', fontsize=15)plt.show()" }, { "code": null, "e": 5426, "s": 5012, "text": "I also made this same chart using the TextBlob Naive Bayes and Pattern analyzers with worse results (see the Jupyter notebook on my Github for these charts). The Naive Bayes model was trained on movie reviews which must not translate well to the Harry Potter universe. The Pattern analyzer worked much better (almost as well as VADER); it is based on the Pattern library, a rule-based model very similar to VADER." }, { "code": null, "e": 6175, "s": 5426, "text": "I also looked at emotions by using a lexicon created by the National Research Council of Canada of over 14,000 words, each scored as either associated or not-associated with any of two sentiments (negative, positive) or eight emotions (anger, anticipation, disgust, fear, joy, sadness, surprise, trust). They kindly provided me access to the lexicon, and I wrote up a Python script which loops over each word in a chapter, looks it up in the lexicon, and outputs whichever emotions the word was associated with. Each chapter was then assigned a score for each emotion corresponding to a ratio of how many words associated with that emotion the chapter contains compared to the total word count in the chapter (this basically normalizes the scores)." }, { "code": null, "e": 6339, "s": 6175, "text": "Here are plots of the ‘Anger’ and ‘Sadness’ sentiments. I find it interesting that anger always exists with sadness, but sadness can sometimes exist without anger:" }, { "code": null, "e": 6466, "s": 6339, "text": "Again, take a look at the Jupyter notebook on my Github to see detailed charts for all sentiments. Here’s a condensed version:" }, { "code": null, "e": 6507, "s": 6466, "text": "Let’s see how I made all those subplots:" }, { "code": null, "e": 7392, "s": 6507, "text": "length = sum([len(hp[book]) for book in hp])x = np.linspace(0, length - 1, num=length)fig, ax = plt.subplots(4, 3, figsize=(15, 15), facecolor='w', edgecolor='k')fig.subplots_adjust(hspace = .5, wspace=.1)fig.suptitle('Sentiment of the Harry Potter series', fontsize=20, y=1.02)fig.subplots_adjust(top=0.88)ax = ax.ravel()for i, emotion in enumerate(emotions): y = [hp_df.loc[book].loc[hp[book][chapter][0]][emotion] for book in hp for chapter in hp[book]] for book in book_indices: ax[i].plot(x[book_indices[book][0]: book_indices[book][1]], y[book_indices[book][0]: book_indices[book][1]], label=book, linewidth=2)ax[i].set_title('{} Sentiment'.format(emotion.title())) ax[i].set_xticks([])fig.legend(list(hp), loc='upper right', fontsize=15, bbox_to_anchor=(.85, .2))fig.tight_layout()fig.delaxes(ax[-1])fig.delaxes(ax[-2])plt.show()" }, { "code": null, "e": 7582, "s": 7392, "text": "But it really becomes interesting to see how all the sentiments compare to each other. Overlaying 10 lines with this much variance quickly became a mess, so I again used the moving average:" }, { "code": null, "e": 7877, "s": 7582, "text": "It’s interesting to see contradicting emotions acting counter to each other, most obviously the pink and brown lines above for ‘Positive’ and ‘Negative’ sentiment. Note that, due to the moving average window size of 20 data points, the first 10 and last 10 chapters have been left off the plot." }, { "code": null, "e": 8418, "s": 7877, "text": "I removed the y-axis because those numbers are meaningless to us (mere decimals: the ratio of words of that emotion to total words in the chapter). I also removed the horizontal and vertical chart lines to clean up the plot. I don’t particularly care to mark regular chapter numbers but I do want to mark the books; therefore, I added those vertical dotted lines. The legend has been reversed in this plot, which isn’t really necessary for readability or anything but I did it for consistency with the area and column charts coming up next." }, { "code": null, "e": 8440, "s": 8418, "text": "Here’s how I made it:" }, { "code": null, "e": 9960, "s": 8440, "text": "# use the Tableau color scheme of 10 colorstab10 = matplotlib.cm.get_cmap('tab10')length = sum([len(hp[book]) for book in hp])window = 20# use index slicing to remove data points outside the windowx = np.linspace(0, length - 1, num=length)[int(window / 2): -int(window / 2)]fig = plt.figure(figsize=(15, 15))ax =fig.add_subplot(1, 1, 1)# Loop over the emotions with enumerate in order to track colorsfor c, emotion in enumerate(emotions): y = movingaverage([hp_df.loc[book].loc[hp[book][chapter][0]][emotion] for book in hp for chapter in hp[book]], window)[int(window / 2): -int(window / 2)] plt.plot(x, y, linewidth=5, label=emotion, color=(tab10(c))) # Plot vertical lines marking the booksfor book in book_indices: plt.axvline(x=book_indices[book][0], color='black', linewidth=2, linestyle=':')plt.axvline(x=book_indices[book][1], color='black', linewidth=2, linestyle=':')plt.legend(loc='best', fontsize=15, bbox_to_anchor=(1.2, 1))plt.title('Emotional Sentiment of the Harry Potter series', fontsize=20)plt.ylabel('Relative Sentiment', fontsize=15)# Use the book titles for X ticks, rotate them, center the left edgeplt.xticks([(book_indices[book][0] + book_indices[book][1]) / 2 for book in book_indices], list(hp), rotation=-30, fontsize=15, ha='left')plt.yticks([])# Reverse the order of the legendhandles, labels = ax.get_legend_handles_labels()ax.legend(handles[::-1], labels[::-1], loc='best', fontsize=15, bbox_to_anchor=(1.2, 1))ax.grid(False)plt.show()" }, { "code": null, "e": 10169, "s": 9960, "text": "I also made an area plot to show the overall emotive qualities of each chapter. This is again a moving average in order to smooth out the more extreme spikes and to show the story arc better across all books:" }, { "code": null, "e": 10336, "s": 10169, "text": "The books seem to start with a bit of trailing emotion from the previous story but quickly calm down during the middle chapters only to pick back up again at the end." }, { "code": null, "e": 11755, "s": 10336, "text": "length = sum([len(hp[book]) for book in hp])window = 10x = np.linspace(0, length - 1, num=length)[int(window / 2): -int(window / 2)]fig = plt.figure(figsize=(15, 15))ax = fig.add_subplot(1, 1, 1)y = [movingaverage(hp_df[emotion].tolist(), window)[int(window / 2): -int(window / 2)] for emotion in emotions]plt.stackplot(x, y, colors=(tab10(0), tab10(.1), tab10(.2), tab10(.3), tab10(.4), tab10(.5), tab10(.6), tab10(.7), tab10(.8), tab10(.9)), labels=emotions)# Plot vertical lines marking the booksfor book in book_indices: plt.axvline(x=book_indices[book][0], color='black', linewidth=3, linestyle=':')plt.axvline(x=book_indices[book][1], color='black', linewidth=3, linestyle=':')plt.title('Emotional Sentiment of the Harry Potter series', fontsize=20)plt.xticks([(book_indices[book][0] + book_indices[book][1]) / 2 for book in book_indices], list(hp), rotation=-30, fontsize=15, ha='left')plt.yticks([])plt.ylabel('Relative Sentiment', fontsize=15)# Reverse the legendhandles, labels = ax.get_legend_handles_labels()ax.legend(handles[::-1], labels[::-1], loc='best', fontsize=15, bbox_to_anchor=(1.2, 1))ax.grid(False)plt.show()" }, { "code": null, "e": 12205, "s": 11755, "text": "Note how in this chart, reversing the legend became necessary for readability. By default, the legend items are added in alphabetical order going down, but the data is stacked from the bottom up. So the colors of the legend and the area plot run in opposite direction — to my eye, quite confusing and difficult to follow. So with ‘Anger’ plotted at the bottom, I also wanted it to be on the bottom of the legend and likewise with ‘Trust’ at the top." }, { "code": null, "e": 12301, "s": 12205, "text": "And lastly, a stacked bar chart to show the weights of the various sentiments across the books:" }, { "code": null, "e": 13119, "s": 12301, "text": "Naturally, words associated with any of the positive emotions would also be associated with the ‘Positive’ sentiment, and likewise for ‘Negative’, so it shouldn’t come as a surprise that those two sentiments carry the bulk of the emotive quality of the books. I find it notable that the emotions are relatively consistent from book to book with just slight differences in magnitude but consistent weights, except for the ‘Fear’ emotion in red; it seems to exhibit the most variance across the series. I also would have expected the cumulative magnitude of sentiments to increase throughout the series as the stakes became higher and higher; however although the final book is indeed the highest, the other 6 books don’t show this gradual increase but almost the opposite, with a constant decline starting with book 2." }, { "code": null, "e": 13783, "s": 13119, "text": "books = list(hp)margin_bottom = np.zeros(len(books))fig = plt.figure(figsize=(15, 15))ax = fig.add_subplot(1, 1, 1)for c, emotion in enumerate(emotions): y = np.array(hp_df2[emotion]) plt.bar(books, y, bottom=margin_bottom, label=emotion, color=(tab10(c))) margin_bottom += y# Reverse the legendhandles, labels = ax.get_legend_handles_labels()ax.legend(handles[::-1], labels[::-1], loc='best', fontsize=15, bbox_to_anchor=(1.2, 1))plt.title('Emotional Sentiment of the Harry Potter series', fontsize=20)plt.xticks(books, books, rotation=-30, ha='left', fontsize=15)plt.ylabel('Relative Sentiment Score', fontsize=15)plt.yticks([])ax.grid(False)plt.show()" } ]
How to create a Button in JavaFX?
In JavaFX the javafx.scene.control package provides various nodes (classes) specially designed for UI applications and these are re-usable. You can customize these and build view pages for your JavaFX applications. example: Button, CheckBox, Label, etc. A button is control in user interface applications, in general, on clicking the button it performs the respective action. You can create a Button by instantiating the javafx.scene.control.Button class of this package and, you can set text to the button using the setText() method. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.paint.Color; import javafx.stage.Stage; public class ButtonExample extends Application { @Override public void start(Stage stage) { //Creating a Button Button button = new Button(); //Setting text to the button button.setText("Sample Button"); //Setting the location of the button button.setTranslateX(150); button.setTranslateY(60); //Setting the stage Group root = new Group(button); Scene scene = new Scene(root, 595, 150, Color.BEIGE); stage.setTitle("Button Example"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1316, "s": 1062, "text": "In JavaFX the javafx.scene.control package provides various nodes (classes)\nspecially designed for UI applications and these are re-usable. You can customize\nthese and build view pages for your JavaFX applications. example: Button,\nCheckBox, Label, etc." }, { "code": null, "e": 1438, "s": 1316, "text": "A button is control in user interface applications, in general, on clicking the button it performs the respective action." }, { "code": null, "e": 1597, "s": 1438, "text": "You can create a Button by instantiating the javafx.scene.control.Button class of this package and, you can set text to the button using the setText() method." }, { "code": null, "e": 2416, "s": 1597, "text": "import javafx.application.Application;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Button;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\npublic class ButtonExample extends Application {\n @Override\n public void start(Stage stage) {\n //Creating a Button\n Button button = new Button();\n //Setting text to the button\n button.setText(\"Sample Button\");\n //Setting the location of the button\n button.setTranslateX(150);\n button.setTranslateY(60);\n //Setting the stage\n Group root = new Group(button);\n Scene scene = new Scene(root, 595, 150, Color.BEIGE);\n stage.setTitle(\"Button Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
Abstract Classes in Java - GeeksforGeeks
21 Apr, 2022 In C++, if a class has at least one pure virtual function, then the class becomes abstract. Unlike C++, in Java, a separate keyword abstract is used to make a class abstract. Illustration: Abstract class abstract class Shape { int color; // An abstract function abstract void draw(); } Following are some important observations about abstract classes in Java. An instance of an abstract class can not be created.Constructors are allowed.We can have an abstract class without any abstract method.There can be final method in abstract class but any abstract method in class(abstract class) can not be declared as final or in simper terms final method can not be abstract itself as it will yield error: “Illegal combination of modifiers: abstract and final”We are not allowed to create object for any abstract class.We can define static methods in an abstract class An instance of an abstract class can not be created. Constructors are allowed. We can have an abstract class without any abstract method. There can be final method in abstract class but any abstract method in class(abstract class) can not be declared as final or in simper terms final method can not be abstract itself as it will yield error: “Illegal combination of modifiers: abstract and final” We are not allowed to create object for any abstract class. We can define static methods in an abstract class Let us elaborate on these observations and do justify them with help of clean java programs as follows. Observation 1: In Java, just likely in C++ an instance of an abstract class cannot be created, we can have references to abstract class type though. It is as shown below via clean java program. Example Java // Java Program to Illustrate That an instance of Abstract// Class Can not be created // Class 1// Abstract classabstract class Base { abstract void fun();} // Class 2class Derived extends Base { void fun() { System.out.println("Derived fun() called"); }} // Class 3// Main classclass Main { // Main driver method public static void main(String args[]) { // Uncommenting the following line will cause // compiler error as the line tries to create an // instance of abstract class. Base b = new Base(); // We can have references of Base type. Base b = new Derived(); b.fun(); }} Derived fun() called Observation 2: Like C++, an abstract class can contain constructors in Java. And a constructor of abstract class is called when an instance of an inherited class is created. It is as shown in the program below as follows: Example Java // Java Program to Illustrate Abstract Class// Can contain Constructors // Class 1// Abstract classabstract class Base { // Constructor of class 1 Base() { // Print statement System.out.println("Base Constructor Called"); } // Abstract method inside class1 abstract void fun();} // Class 2class Derived extends Base { // Constructor of class2 Derived() { System.out.println("Derived Constructor Called"); } // Method of class2 void fun() { System.out.println("Derived fun() called"); }} // Class 3// Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating object of class 2 // inside main() method Derived d = new Derived(); }} Base Constructor Called Derived Constructor Called Observation 3: In Java, we can have an abstract class without any abstract method. This allows us to create classes that cannot be instantiated but can only be inherited. It is as shown below as follows with help of clean java program. Example Java // Java Program to illustrate Abstract class// Without any abstract method // Class 1// An abstract class without any abstract methodabstract class Base { // Demo method void fun() { // Print message if class 1 function is called System.out.println( "Function of Base class is called"); }} // Class 2class Derived extends Base {} // Class 3class Main { // Main driver method public static void main(String args[]) { // Creating object of class 2 Derived d = new Derived(); // Calling function defined in class 1 inside main() // with object of class 2 inside main() method d.fun(); }} Function of Base class is called Observation 4: Abstract classes can also have final methods (methods that cannot be overridden) Example Java // Java Program to Illustrate Abstract classes// Can also have Final Methods // Class 1// Abstract classabstract class Base { final void fun() { System.out.println("Base fun() called"); }} // Class 2class Derived extends Base {} // Class 3// Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating object of abstract class Base b = new Derived(); // Calling method on object created above // inside main() b.fun(); }} Base fun() called Observation 5: For any abstract java class we are not allowed to create an object i.e., for abstract class instantiation is not possible. Example Java // Java Program to Illustrate Abstract Class // Main class// An abstract classabstract class GFG { // Main driver method public static void main(String args[]) { // Trying to create an object GFG gfg = new GFG(); }} Output: Observation 6: Similar to the interface we can define static methods in an abstract class that can be called independently without an object. Example Java // Java Program to Illustrate Static Methods in Abstract// Class Can be called Independently // Class 1// Abstract classabstract class Helper { // Abstract method static void demofun() { // Print statement System.out.println("Geeks for Geeks"); }} // Class 2// Main class extending Helper classpublic class GFG extends Helper { // Main driver method public static void main(String[] args) { // Calling method inside main() // as defined in above class Helper.demofun(); }} Geeks for Geeks YouTubeGeeksforGeeks501K subscribersAbstract Classes (Java Programming Language) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 13:23•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=DWmpxZ59JW0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Must Read: Difference between Abstract class and Interface in Java Difference between Abstract class and Abstract Methods Constructors in Java Abstract Class Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. gauravmoney26 rocknaga81 solankimayank sagartomar9927 kashishsoda imkunal0306 paritoshchaudhari Java-Abstract Class and Interface java-basics Java-Object Oriented Java School Programming Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Initialize an ArrayList in Java How to iterate any Map in Java Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 28950, "s": 28922, "text": "\n21 Apr, 2022" }, { "code": null, "e": 29126, "s": 28950, "text": "In C++, if a class has at least one pure virtual function, then the class becomes abstract. Unlike C++, in Java, a separate keyword abstract is used to make a class abstract. " }, { "code": null, "e": 29155, "s": 29126, "text": "Illustration: Abstract class" }, { "code": null, "e": 29251, "s": 29155, "text": "abstract class Shape \n{\n int color;\n\n // An abstract function\n abstract void draw();\n}" }, { "code": null, "e": 29325, "s": 29251, "text": "Following are some important observations about abstract classes in Java." }, { "code": null, "e": 29829, "s": 29325, "text": "An instance of an abstract class can not be created.Constructors are allowed.We can have an abstract class without any abstract method.There can be final method in abstract class but any abstract method in class(abstract class) can not be declared as final or in simper terms final method can not be abstract itself as it will yield error: “Illegal combination of modifiers: abstract and final”We are not allowed to create object for any abstract class.We can define static methods in an abstract class" }, { "code": null, "e": 29882, "s": 29829, "text": "An instance of an abstract class can not be created." }, { "code": null, "e": 29908, "s": 29882, "text": "Constructors are allowed." }, { "code": null, "e": 29967, "s": 29908, "text": "We can have an abstract class without any abstract method." }, { "code": null, "e": 30228, "s": 29967, "text": "There can be final method in abstract class but any abstract method in class(abstract class) can not be declared as final or in simper terms final method can not be abstract itself as it will yield error: “Illegal combination of modifiers: abstract and final”" }, { "code": null, "e": 30288, "s": 30228, "text": "We are not allowed to create object for any abstract class." }, { "code": null, "e": 30338, "s": 30288, "text": "We can define static methods in an abstract class" }, { "code": null, "e": 30442, "s": 30338, "text": "Let us elaborate on these observations and do justify them with help of clean java programs as follows." }, { "code": null, "e": 30636, "s": 30442, "text": "Observation 1: In Java, just likely in C++ an instance of an abstract class cannot be created, we can have references to abstract class type though. It is as shown below via clean java program." }, { "code": null, "e": 30645, "s": 30636, "text": "Example " }, { "code": null, "e": 30650, "s": 30645, "text": "Java" }, { "code": "// Java Program to Illustrate That an instance of Abstract// Class Can not be created // Class 1// Abstract classabstract class Base { abstract void fun();} // Class 2class Derived extends Base { void fun() { System.out.println(\"Derived fun() called\"); }} // Class 3// Main classclass Main { // Main driver method public static void main(String args[]) { // Uncommenting the following line will cause // compiler error as the line tries to create an // instance of abstract class. Base b = new Base(); // We can have references of Base type. Base b = new Derived(); b.fun(); }}", "e": 31304, "s": 30650, "text": null }, { "code": null, "e": 31325, "s": 31304, "text": "Derived fun() called" }, { "code": null, "e": 31548, "s": 31325, "text": "Observation 2: Like C++, an abstract class can contain constructors in Java. And a constructor of abstract class is called when an instance of an inherited class is created. It is as shown in the program below as follows: " }, { "code": null, "e": 31557, "s": 31548, "text": "Example " }, { "code": null, "e": 31562, "s": 31557, "text": "Java" }, { "code": "// Java Program to Illustrate Abstract Class// Can contain Constructors // Class 1// Abstract classabstract class Base { // Constructor of class 1 Base() { // Print statement System.out.println(\"Base Constructor Called\"); } // Abstract method inside class1 abstract void fun();} // Class 2class Derived extends Base { // Constructor of class2 Derived() { System.out.println(\"Derived Constructor Called\"); } // Method of class2 void fun() { System.out.println(\"Derived fun() called\"); }} // Class 3// Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating object of class 2 // inside main() method Derived d = new Derived(); }}", "e": 32339, "s": 31562, "text": null }, { "code": null, "e": 32390, "s": 32339, "text": "Base Constructor Called\nDerived Constructor Called" }, { "code": null, "e": 32626, "s": 32390, "text": "Observation 3: In Java, we can have an abstract class without any abstract method. This allows us to create classes that cannot be instantiated but can only be inherited. It is as shown below as follows with help of clean java program." }, { "code": null, "e": 32635, "s": 32626, "text": "Example " }, { "code": null, "e": 32640, "s": 32635, "text": "Java" }, { "code": "// Java Program to illustrate Abstract class// Without any abstract method // Class 1// An abstract class without any abstract methodabstract class Base { // Demo method void fun() { // Print message if class 1 function is called System.out.println( \"Function of Base class is called\"); }} // Class 2class Derived extends Base {} // Class 3class Main { // Main driver method public static void main(String args[]) { // Creating object of class 2 Derived d = new Derived(); // Calling function defined in class 1 inside main() // with object of class 2 inside main() method d.fun(); }}", "e": 33312, "s": 32640, "text": null }, { "code": null, "e": 33345, "s": 33312, "text": "Function of Base class is called" }, { "code": null, "e": 33441, "s": 33345, "text": "Observation 4: Abstract classes can also have final methods (methods that cannot be overridden)" }, { "code": null, "e": 33450, "s": 33441, "text": "Example " }, { "code": null, "e": 33455, "s": 33450, "text": "Java" }, { "code": "// Java Program to Illustrate Abstract classes// Can also have Final Methods // Class 1// Abstract classabstract class Base { final void fun() { System.out.println(\"Base fun() called\"); }} // Class 2class Derived extends Base {} // Class 3// Main classclass GFG { // Main driver method public static void main(String args[]) { // Creating object of abstract class Base b = new Derived(); // Calling method on object created above // inside main() b.fun(); }}", "e": 33981, "s": 33455, "text": null }, { "code": null, "e": 33999, "s": 33981, "text": "Base fun() called" }, { "code": null, "e": 34138, "s": 33999, "text": "Observation 5: For any abstract java class we are not allowed to create an object i.e., for abstract class instantiation is not possible. " }, { "code": null, "e": 34147, "s": 34138, "text": "Example " }, { "code": null, "e": 34152, "s": 34147, "text": "Java" }, { "code": "// Java Program to Illustrate Abstract Class // Main class// An abstract classabstract class GFG { // Main driver method public static void main(String args[]) { // Trying to create an object GFG gfg = new GFG(); }}", "e": 34396, "s": 34152, "text": null }, { "code": null, "e": 34404, "s": 34396, "text": "Output:" }, { "code": null, "e": 34547, "s": 34404, "text": "Observation 6: Similar to the interface we can define static methods in an abstract class that can be called independently without an object. " }, { "code": null, "e": 34556, "s": 34547, "text": "Example " }, { "code": null, "e": 34561, "s": 34556, "text": "Java" }, { "code": "// Java Program to Illustrate Static Methods in Abstract// Class Can be called Independently // Class 1// Abstract classabstract class Helper { // Abstract method static void demofun() { // Print statement System.out.println(\"Geeks for Geeks\"); }} // Class 2// Main class extending Helper classpublic class GFG extends Helper { // Main driver method public static void main(String[] args) { // Calling method inside main() // as defined in above class Helper.demofun(); }}", "e": 35097, "s": 34561, "text": null }, { "code": null, "e": 35113, "s": 35097, "text": "Geeks for Geeks" }, { "code": null, "e": 35957, "s": 35113, "text": "YouTubeGeeksforGeeks501K subscribersAbstract Classes (Java Programming Language) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 13:23•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=DWmpxZ59JW0\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 35968, "s": 35957, "text": "Must Read:" }, { "code": null, "e": 36025, "s": 35968, "text": "Difference between Abstract class and Interface in Java " }, { "code": null, "e": 36080, "s": 36025, "text": "Difference between Abstract class and Abstract Methods" }, { "code": null, "e": 36116, "s": 36080, "text": "Constructors in Java Abstract Class" }, { "code": null, "e": 36243, "s": 36116, "text": " Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 36257, "s": 36243, "text": "gauravmoney26" }, { "code": null, "e": 36268, "s": 36257, "text": "rocknaga81" }, { "code": null, "e": 36282, "s": 36268, "text": "solankimayank" }, { "code": null, "e": 36297, "s": 36282, "text": "sagartomar9927" }, { "code": null, "e": 36309, "s": 36297, "text": "kashishsoda" }, { "code": null, "e": 36321, "s": 36309, "text": "imkunal0306" }, { "code": null, "e": 36339, "s": 36321, "text": "paritoshchaudhari" }, { "code": null, "e": 36373, "s": 36339, "text": "Java-Abstract Class and Interface" }, { "code": null, "e": 36385, "s": 36373, "text": "java-basics" }, { "code": null, "e": 36406, "s": 36385, "text": "Java-Object Oriented" }, { "code": null, "e": 36411, "s": 36406, "text": "Java" }, { "code": null, "e": 36430, "s": 36411, "text": "School Programming" }, { "code": null, "e": 36435, "s": 36430, "text": "Java" }, { "code": null, "e": 36533, "s": 36435, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36542, "s": 36533, "text": "Comments" }, { "code": null, "e": 36555, "s": 36542, "text": "Old Comments" }, { "code": null, "e": 36599, "s": 36555, "text": "Split() String method in Java with examples" }, { "code": null, "e": 36635, "s": 36599, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 36660, "s": 36635, "text": "Reverse a string in Java" }, { "code": null, "e": 36692, "s": 36660, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 36723, "s": 36692, "text": "How to iterate any Map in Java" }, { "code": null, "e": 36741, "s": 36723, "text": "Python Dictionary" }, { "code": null, "e": 36757, "s": 36741, "text": "Arrays in C/C++" }, { "code": null, "e": 36776, "s": 36757, "text": "Inheritance in C++" }, { "code": null, "e": 36801, "s": 36776, "text": "Reverse a string in Java" } ]
Bin Packing Problem (Minimize number of used Bins) - GeeksforGeeks
28 Jul, 2021 Given n items of different weights and bins each of capacity c, assign each item to a bin such that number of total used bins is minimized. It may be assumed that all items have weights smaller than bin capacity.Example: Input: weight[] = {4, 8, 1, 4, 2, 1} Bin Capacity c = 10 Output: 2 We need minimum 2 bins to accommodate all items First bin contains {4, 4, 2} and second bin {8, 1, 1} Input: weight[] = {9, 8, 2, 2, 5, 4} Bin Capacity c = 10 Output: 4 We need minimum 4 bins to accommodate all items. Input: weight[] = {2, 5, 4, 7, 1, 3, 8}; Bin Capacity c = 10 Output: 3 Lower Bound We can always find a lower bound on minimum number of bins required. The lower bound can be given as : Min no. of bins >= Ceil ((Total Weight) / (Bin Capacity)) In the above examples, lower bound for first example is “ceil(4 + 8 + 1 + 4 + 2 + 1)/10” = 2 and lower bound in second example is “ceil(9 + 8 + 2 + 2 + 5 + 4)/10” = 3. This problem is a NP Hard problem and finding an exact minimum number of bins takes exponential time. Following are approximate algorithms for this problem. Applications Loading of containers like trucks.Placing data on multiple disks.Job scheduling.Packing advertisements in fixed length radio/TV station breaks.Storing a large collection of music onto tapes/CD’s, etc. Loading of containers like trucks. Placing data on multiple disks. Job scheduling. Packing advertisements in fixed length radio/TV station breaks. Storing a large collection of music onto tapes/CD’s, etc. Online Algorithms These algorithms are for Bin Packing problems where items arrive one at a time (in unknown order), each must be put in a bin, before considering the next item.1. Next Fit: When processing next item, check if it fits in the same bin as the last item. Use a new bin only if it does not. Below is C++ implementation for this algorithm. C++ Java Python3 C# Javascript // C++ program to find number of bins required using// next fit algorithm.#include <bits/stdc++.h>using namespace std; // Returns number of bins required using next fit// online algorithmint nextFit(int weight[], int n, int c){ // Initialize result (Count of bins) and remaining // capacity in current bin. int res = 0, bin_rem = c; // Place items one by one for (int i = 0; i < n; i++) { // If this item can't fit in current bin if (weight[i] > bin_rem) { res++; // Use a new bin bin_rem = c - weight[i]; } else bin_rem -= weight[i]; } return res;} // Driver programint main(){ int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = sizeof(weight) / sizeof(weight[0]); cout << "Number of bins required in Next Fit : " << nextFit(weight, n, c); return 0;} // Java program to find number// of bins required using// next fit algorithm.class GFG { // Returns number of bins required // using next fit online algorithm static int nextFit(int weight[], int n, int c) { // Initialize result (Count of bins) and remaining // capacity in current bin. int res = 0, bin_rem = c; // Place items one by one for (int i = 0; i < n; i++) { // If this item can't fit in current bin if (weight[i] > bin_rem) { res++; // Use a new bin bin_rem = c - weight[i]; } else bin_rem -= weight[i]; } return res; } // Driver program public static void main(String[] args) { int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = weight.length; System.out.println("Number of bins required in Next Fit : " + nextFit(weight, n, c)); }} // This code has been contributed by 29AjayKumar # Python3 implementation for above approachdef nextfit(weight, c): res = 0 rem = c for _ in range(len(weight)): if rem >= weight[_]: rem = rem - weight[_] else: res += 1 rem = c - weight[_] return res # Driver Codeweight = [2, 5, 4, 7, 1, 3, 8]c = 10 print("Number of bins required in Next Fit :", nextfit(weight, c)) # This code is contributed by code_freak // C# program to find number// of bins required using// next fit algorithm.using System; class GFG{ // Returns number of bins required // using next fit online algorithm static int nextFit(int []weight, int n, int c) { // Initialize result (Count of bins) and remaining // capacity in current bin. int res = 0, bin_rem = c; // Place items one by one for (int i = 0; i < n; i++) { // If this item can't fit in current bin if (weight[i] > bin_rem) { res++; // Use a new bin bin_rem = c - weight[i]; } else bin_rem -= weight[i]; } return res; } // Driver program public static void Main(String[] args) { int []weight = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = weight.Length; Console.WriteLine("Number of bins required" + " in Next Fit : " + nextFit(weight, n, c)); }} // This code is contributed by Rajput-Ji <script> // JavaScript program to find number// of bins required using// next fit algorithm. // Returns number of bins required // using next fit online algorithm function nextFit(weight, n, c) { // Initialize result (Count of bins) and remaining // capacity in current bin. let res = 0, bin_rem = c; // Place items one by one for (let i = 0; i < n; i++) { // If this item can't fit in current bin if (weight[i] > bin_rem) { res++; // Use a new bin bin_rem = c - weight[i]; } else bin_rem -= weight[i]; } return res; } // Driver Code let weight = [ 2, 5, 4, 7, 1, 3, 8 ]; let c = 10; let n = weight.length; document.write("Number of bins required in Next Fit : " + nextFit(weight, n, c)); // This code is contributed by target_2.</script> Output: Number of bins required in Next Fit : 4 Next Fit is a simple algorithm. It requires only O(n) time and O(1) extra space to process n items. Next Fit is 2 approximate, i.e., the number of bins used by this algorithm is bounded by twice of optimal. Consider any two adjacent bins. The sum of items in these two bins must be > c; otherwise, NextFit would have put all the items of second bin into the first. The same holds for all other bins. Thus, at most half the space is wasted, and so Next Fit uses at most 2M bins if M is optimal.2. First Fit: When processing the next item, scan the previous bins in order and place the item in the first bin that fits. Start a new bin only if it does not fit in any of the existing bins. C++ Java Python3 C# Javascript // C++ program to find number of bins required using// First Fit algorithm.#include <bits/stdc++.h>using namespace std; // Returns number of bins required using first fit// online algorithmint firstFit(int weight[], int n, int c){ // Initialize result (Count of bins) int res = 0; // Create an array to store remaining space in bins // there can be at most n bins int bin_rem[n]; // Place items one by one for (int i = 0; i < n; i++) { // Find the first bin that can accommodate // weight[i] int j; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i]) { bin_rem[j] = bin_rem[j] - weight[i]; break; } } // If no bin could accommodate weight[i] if (j == res) { bin_rem[res] = c - weight[i]; res++; } } return res;} // Driver programint main(){ int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = sizeof(weight) / sizeof(weight[0]); cout << "Number of bins required in First Fit : " << firstFit(weight, n, c); return 0;} // Java program to find number of bins required using// First Fit algorithm.class GFG{ // Returns number of bins required using first fit// online algorithmstatic int firstFit(int weight[], int n, int c){ // Initialize result (Count of bins) int res = 0; // Create an array to store remaining space in bins // there can be at most n bins int []bin_rem = new int[n]; // Place items one by one for (int i = 0; i < n; i++) { // Find the first bin that can accommodate // weight[i] int j; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i]) { bin_rem[j] = bin_rem[j] - weight[i]; break; } } // If no bin could accommodate weight[i] if (j == res) { bin_rem[res] = c - weight[i]; res++; } } return res;} // Driver programpublic static void main(String[] args){ int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = weight.length; System.out.print("Number of bins required in First Fit : " + firstFit(weight, n, c));}} // This code is contributed by Rajput-Ji # Python program to find number of bins required using# First Fit algorithm. # Returns number of bins required using first fit# online algorithmdef firstFit(weight, n, c): # Initialize result (Count of bins) res = 0 # Create an array to store remaining space in bins # there can be at most n bins bin_rem = [0]*n # Place items one by one for i in range(n): # Find the first bin that can accommodate # weight[i] j = 0 while( j < res): if (bin_rem[j] >= weight[i]): bin_rem[j] = bin_rem[j] - weight[i] break j+=1 # If no bin could accommodate weight[i] if (j == res): bin_rem[res] = c - weight[i] res= res+1 return res # Driver programweight = [2, 5, 4, 7, 1, 3, 8]c = 10n = len(weight)print("Number of bins required in First Fit : ",firstFit(weight, n, c)) # This code is contributed by shubhamsingh10 // C# program to find number of bins required using// First Fit algorithm.using System; class GFG{ // Returns number of bins required using first fit// online algorithmstatic int firstFit(int []weight, int n, int c){ // Initialize result (Count of bins) int res = 0; // Create an array to store remaining space in bins // there can be at most n bins int []bin_rem = new int[n]; // Place items one by one for (int i = 0; i < n; i++) { // Find the first bin that can accommodate // weight[i] int j; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i]) { bin_rem[j] = bin_rem[j] - weight[i]; break; } } // If no bin could accommodate weight[i] if (j == res) { bin_rem[res] = c - weight[i]; res++; } } return res;} // Driver codepublic static void Main(String[] args){ int []weight = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = weight.Length; Console.Write("Number of bins required in First Fit : " + firstFit(weight, n, c));}} // This code is contributed by 29AjayKumar <script>// Javascript program to find number of bins required using// First Fit algorithm. // Returns number of bins required using first fit// online algorithmfunction firstFit(weight,n,c){ // Initialize result (Count of bins) let res = 0; // Create an array to store remaining space in bins // there can be at most n bins let bin_rem = new Array(n); // Place items one by one for (let i = 0; i < n; i++) { // Find the first bin that can accommodate // weight[i] let j; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i]) { bin_rem[j] = bin_rem[j] - weight[i]; break; } } // If no bin could accommodate weight[i] if (j == res) { bin_rem[res] = c - weight[i]; res++; } } return res;} // Driver programlet weight=[ 2, 5, 4, 7, 1, 3, 8];let c = 10;let n = weight.length;document.write("Number of bins required in First Fit : " + firstFit(weight, n, c)); // This code is contributed by patel2127</script> Output: Number of bins required in First Fit : 4 The above implementation of First Fit requires O(n2) time, but First Fit can be implemented in O(n Log n) time using Self-Balancing Binary Search Trees.If M is the optimal number of bins, then First Fit never uses more than 1.7M bins. So First-Fit is better than Next Fit in terms of upper bound on number of bins.3. Best Fit: The idea is to places the next item in the *tightest* spot. That is, put it in the bin so that the smallest empty space is left. C++ Java Python3 C# Javascript // C++ program to find number// of bins required using// Best fit algorithm.#include <bits/stdc++.h>using namespace std; // Returns number of bins required using best fit// online algorithmint bestFit(int weight[], int n, int c){ // Initialize result (Count of bins) int res = 0; // Create an array to store // remaining space in bins // there can be at most n bins int bin_rem[n]; // Place items one by one for (int i = 0; i < n; i++) { // Find the best bin that can accommodate // weight[i] int j; // Initialize minimum space left and index // of best bin int min = c + 1, bi = 0; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] < min) { bi = j; min = bin_rem[j] - weight[i]; } } // If no bin could accommodate weight[i], // create a new bin if (min == c + 1) { bin_rem[res] = c - weight[i]; res++; } else // Assign the item to best bin bin_rem[bi] -= weight[i]; } return res;} // Driver programint main(){ int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = sizeof(weight) / sizeof(weight[0]); cout << "Number of bins required in Best Fit : " << bestFit(weight, n, c); return 0;} // Java program to find number// of bins required using// Best fit algorithm.class GFG{ // Returns number of bins// required using best fit// online algorithmstatic int bestFit(int weight[], int n, int c){ // Initialize result (Count of bins) int res = 0; // Create an array to store // remaining space in bins // there can be at most n bins int []bin_rem = new int[n]; // Place items one by one for (int i = 0; i < n; i++) { // Find the best bin that // can accommodate // weight[i] int j; // Initialize minimum space // left and index // of best bin int min = c + 1, bi = 0; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] < min) { bi = j; min = bin_rem[j] - weight[i]; } } // If no bin could accommodate weight[i], // create a new bin if (min == c + 1) { bin_rem[res] = c - weight[i]; res++; } else // Assign the item to best bin bin_rem[bi] -= weight[i]; } return res;} // Driver codepublic static void main(String[] args){ int []weight = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = weight.length; System.out.print("Number of bins required in Best Fit : " + bestFit(weight, n, c));}} // This code is contributed by 29AjayKumar # Python3 program to find number# of bins required using# First Fit algorithm. # Returns number of bins required# using first fit# online algorithmdef firstFit(weight, n, c): # Initialize result (Count of bins) res = 0; # Create an array to store # remaining space in bins # there can be at most n bins bin_rem = [0]*n; # Place items one by one for i in range(n): # Find the first bin that # can accommodate # weight[i] j = 0; # Initialize minimum space # left and index # of best bin min = c + 1; bi = 0; for j in range(res): if (bin_rem[j] >= weight[i] and bin_rem[j] - weight[i] < min): bi = j; min = bin_rem[j] - weight[i]; # If no bin could accommodate weight[i], # create a new bin if (min == c + 1): bin_rem[res] = c - weight[i]; res += 1; else: # Assign the item to best bin bin_rem[bi] -= weight[i]; return res; # Driver codeif __name__ == '__main__': weight = [ 2, 5, 4, 7, 1, 3, 8 ]; c = 10; n = len(weight); print("Number of bins required in First Fit : ", firstFit(weight, n, c)); # This code is contributed by Rajput-Ji // C# program to find number// of bins required using// Best fit algorithm.using System; class GFG { // Returns number of bins // required using best fit // online algorithm static int bestFit(int[] weight, int n, int c) { // Initialize result (Count of bins) int res = 0; // Create an array to store // remaining space in bins // there can be at most n bins int[] bin_rem = new int[n]; // Place items one by one for (int i = 0; i < n; i++) { // Find the best bin that // can accommodate // weight[i] int j; // Initialize minimum space // left and index // of best bin int min = c + 1, bi = 0; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] < min) { bi = j; min = bin_rem[j] - weight[i]; } } // If no bin could accommodate weight[i], // create a new bin if (min == c + 1) { bin_rem[res] = c - weight[i]; res++; } // Assign the item to best bin else bin_rem[bi] -= weight[i]; } return res; } // Driver code public static void Main(String[] args) { int[] weight = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = weight.Length; Console.Write( "Number of bins required in Best Fit : " + bestFit(weight, n, c)); }} // This code is contributed by 29AjayKumar <script>// javascript program to find number// of bins required using// Best fit algorithm.// Returns number of bins // required using best fit // online algorithm function bestFit(weight , n , c) { // Initialize result (Count of bins) var res = 0; // Create an array to store // remaining space in bins // there can be at most n bins var bin_rem = Array(n).fill(0); // Place items one by one for (i = 0; i < n; i++) { // Find the best bin that // can accommodate // weight[i] var j; // Initialize minimum space // left and index // of best bin var min = c + 1, bi = 0; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] < min) { bi = j; min = bin_rem[j] - weight[i]; } } // If no bin could accommodate weight[i], // create a new bin if (min == c + 1) { bin_rem[res] = c - weight[i]; res++; } else // Assign the item to best bin bin_rem[bi] -= weight[i]; } return res; } // Driver code var weight = [ 2, 5, 4, 7, 1, 3, 8 ]; var c = 10; var n = weight.length; document.write("Number of bins required in Best Fit : " + bestFit(weight, n, c)); // This code contributed by gauravrajput1</script> Output: Number of bins required in Best Fit : 4 Best Fit can also be implemented in O(n Log n) time using Self-Balancing Binary Search Trees.If M is the optimal number of bins, then Best Fit never uses more than 1.7M bins. So Best Fit is same as First Fit and better than Next Fit in terms of upper bound on number of bins.4. Worst Fit: The idea is to places the next item in the least tight spot to even out the bins. That is, put it in the bin so that most empty space is left. C++ Java C# Javascript // C++ program to find number of bins required using// Worst fit algorithm.#include <bits/stdc++.h>using namespace std; // Returns number of bins required using worst fit// online algorithmint worstFit(int weight[], int n, int c){ // Initialize result (Count of bins) int res = 0; // Create an array to store remaining space in bins // there can be at most n bins int bin_rem[n]; // Place items one by one for (int i = 0; i < n; i++) { // Find the best bin that ca\n accommodate // weight[i] int j; // Initialize maximum space left and index // of worst bin int mx = -1, wi = 0; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] > mx) { wi = j; mx = bin_rem[j] - weight[i]; } } // If no bin could accommodate weight[i], // create a new bin if (mx == -1) { bin_rem[res] = c - weight[i]; res++; } else // Assign the item to best bin bin_rem[wi] -= weight[i]; } return res;} // Driver programint main(){ int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = sizeof(weight) / sizeof(weight[0]); cout << "Number of bins required in Worst Fit : " << worstFit(weight, n, c); return 0;} // This code is contributed by gromperen // Java program to find number of bins required using// Worst fit algorithm.class GFG{ // Returns number of bins required using worst fit// online algorithmstatic int worstFit(int weight[], int n, int c){ // Initialize result (Count of bins) int res = 0; // Create an array to store remaining space in bins // there can be at most n bins int bin_rem[]= new int[n]; // Place items one by one for (int i = 0; i < n; i++) { // Find the best bin that ca\n accommodate // weight[i] int j; // Initialize maximum space left and index // of worst bin int mx = -1, wi = 0; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] > mx) { wi = j; mx = bin_rem[j] - weight[i]; } } // If no bin could accommodate weight[i], // create a new bin if (mx == -1) { bin_rem[res] = c - weight[i]; res++; } else // Assign the item to best bin bin_rem[wi] -= weight[i]; } return res;} // Driver programpublic static void main(String[] args){ int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = weight.length; System.out.print("Number of bins required in Worst Fit : " +worstFit(weight, n, c));}} // This code is contributed by shivanisinghss2110 // C# program to find number of bins required using// Worst fit algorithm.using System;class GFG{ // Returns number of bins required using worst fit// online algorithmstatic int worstFit(int []weight, int n, int c){ // Initialize result (Count of bins) int res = 0; // Create an array to store remaining space in bins // there can be at most n bins int []bin_rem= new int[n]; // Place items one by one for (int i = 0; i < n; i++) { // Find the best bin that ca\n accommodate // weight[i] int j; // Initialize maximum space left and index // of worst bin int mx = -1, wi = 0; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] > mx) { wi = j; mx = bin_rem[j] - weight[i]; } } // If no bin could accommodate weight[i], // create a new bin if (mx == -1) { bin_rem[res] = c - weight[i]; res++; } else // Assign the item to best bin bin_rem[wi] -= weight[i]; } return res;} // Driver programpublic static void Main(String[] args){ int []weight = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = weight.Length; Console.Write("Number of bins required in Worst Fit : " +worstFit(weight, n, c));}} // This code is contributed by shivanisinghss2110 <script> // javascript program to find number of bins required using// Worst fit algorithm.// Returns number of bins required using worst fit// online algorithmfunction worstFit( weight, n, c){ // Initialize result (Count of bins) var res = 0; // Create an array to store remaining space in bins // there can be at most n bins var bin_rem = Array(n).fill(0); // Place items one by one for (var i = 0; i < n; i++) { // Find the best bin that ca\n accommodate // weight[i] var j; // Initialize maximum space left and index // of worst bin var mx = -1, wi = 0; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] > mx) { wi = j; mx = bin_rem[j] - weight[i]; } } // If no bin could accommodate weight[i], // create a new bin if (mx == -1) { bin_rem[res] = c - weight[i]; res++; } else // Assign the item to best bin bin_rem[wi] -= weight[i]; } return res;} // Driver program var weight = [ 2, 5, 4, 7, 1, 3, 8 ]; var c = 10; var n = weight.length; document.write("Number of bins required in Worst Fit : " +worstFit(weight, n, c)); // This code is contributed by shivanisinghss2110 </script> Output: Number of bins required in Worst Fit : 4 Worst Fit can also be implemented in O(n Log n) time using Self-Balancing Binary Search Trees.If M is the optimal number of bins, then Best Fit never uses more than 2M-2 bins. So Worst Fit is same as Next Fit in terms of upper bound on number of bins. Offline Algorithms In the offline version, we have all items upfront. Unfortunately offline version is also NP Complete, but we have a better approximate algorithm for it. First Fit Decreasing uses at most (4M + 1)/3 bins if the optimal is M.4. First Fit Decreasing: A trouble with online algorithms is that packing large items is difficult, especially if they occur late in the sequence. We can circumvent this by *sorting* the input sequence, and placing the large items first. With sorting, we get First Fit Decreasing and Best Fit Decreasing, as offline analogues of online First Fit and Best Fit. C++ Java C# // C++ program to find number of bins required using// First Fit Decreasing algorithm.#include <bits/stdc++.h>using namespace std; /* Copy firstFit() from above */ // Returns number of bins required using first fit// decreasing offline algorithmint firstFitDec(int weight[], int n, int c){ // First sort all weights in decreasing order sort(weight, weight + n, std::greater<int>()); // Now call first fit for sorted items return firstFit(weight, n, c);} // Driver programint main(){ int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = sizeof(weight) / sizeof(weight[0]); cout << "Number of bins required in First Fit " << "Decreasing : " << firstFitDec(weight, n, c); return 0;} // Java program to find number of bins required using// First Fit Decreasing algorithm.import java.util.*; class GFG{ /* Copy firstFit() from above */ // Returns number of bins required using first fit // decreasing offline algorithm static int firstFitDec(Integer weight[], int n, int c) { // First sort all weights in decreasing order Arrays.sort(weight, Collections.reverseOrder()); // Now call first fit for sorted items return firstFit(weight, n, c); } // Driver code public static void main(String[] args) { Integer weight[] = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = weight.length; System.out.print("Number of bins required in First Fit " + "Decreasing : " + firstFitDec(weight, n, c)); }} // This code is contributed by Rajput-Ji // C# program to find number of bins required using// First Fit Decreasing algorithm.using System; public class GFG{ /* Copy firstFit() from above */ // Returns number of bins required using first fit // decreasing offline algorithm static int firstFitDec(int []weight, int n, int c) { // First sort all weights in decreasing order Array.Sort(weight); Array.Reverse(weight); // Now call first fit for sorted items return firstFit(weight, n, c); } static int firstFit(int []weight, int n, int c) { // Initialize result (Count of bins) int res = 0; // Create an array to store remaining space in bins // there can be at most n bins int []bin_rem = new int[n]; // Place items one by one for (int i = 0; i < n; i++) { // Find the first bin that can accommodate // weight[i] int j; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i]) { bin_rem[j] = bin_rem[j] - weight[i]; break; } } // If no bin could accommodate weight[i] if (j == res) { bin_rem[res] = c - weight[i]; res++; } } return res; } // Driver code public static void Main(String[] args) { int []weight = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = weight.Length; Console.Write("Number of bins required in First Fit " + "Decreasing : " + firstFitDec(weight, n, c)); }} // This code is contributed by 29AjayKumar Output: Number of bins required in First Fit Decreasing : 3 First Fit decreasing produces the best result for the sample input because items are sorted first.First Fit Decreasing can also be implemented in O(n Log n) time using Self-Balancing Binary Search Trees.This article is contributed by Dheeraj Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 29AjayKumar GiulioMecocci code_freak Rajput-Ji gromperen firoz_baba target_2 GauravRajput1 sooda367 clintra adnanirshad158 patel2127 shivanisinghss2110 SHUBHAMSINGH10 Greedy Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Split the given array into K sub-arrays such that maximum sum of all sub arrays is minimum Program for First Fit algorithm in Memory Management Optimal Page Replacement Algorithm Program for Best Fit algorithm in Memory Management Max Flow Problem Introduction Program for Worst Fit algorithm in Memory Management Optimal File Merge Patterns Huffman Decoding Maximum items that can be bought from the cost Array based on given conditions Maximum Sum Subsequence
[ { "code": null, "e": 24929, "s": 24901, "text": "\n28 Jul, 2021" }, { "code": null, "e": 25151, "s": 24929, "text": "Given n items of different weights and bins each of capacity c, assign each item to a bin such that number of total used bins is minimized. It may be assumed that all items have weights smaller than bin capacity.Example: " }, { "code": null, "e": 25557, "s": 25151, "text": "Input: weight[] = {4, 8, 1, 4, 2, 1}\n Bin Capacity c = 10\nOutput: 2\nWe need minimum 2 bins to accommodate all items\nFirst bin contains {4, 4, 2} and second bin {8, 1, 1}\n\nInput: weight[] = {9, 8, 2, 2, 5, 4}\n Bin Capacity c = 10\nOutput: 4\nWe need minimum 4 bins to accommodate all items. \n\nInput: weight[] = {2, 5, 4, 7, 1, 3, 8}; \n Bin Capacity c = 10\nOutput: 3" }, { "code": null, "e": 25673, "s": 25557, "text": "Lower Bound We can always find a lower bound on minimum number of bins required. The lower bound can be given as : " }, { "code": null, "e": 25736, "s": 25673, "text": " Min no. of bins >= Ceil ((Total Weight) / (Bin Capacity))" }, { "code": null, "e": 26075, "s": 25736, "text": "In the above examples, lower bound for first example is “ceil(4 + 8 + 1 + 4 + 2 + 1)/10” = 2 and lower bound in second example is “ceil(9 + 8 + 2 + 2 + 5 + 4)/10” = 3. This problem is a NP Hard problem and finding an exact minimum number of bins takes exponential time. Following are approximate algorithms for this problem. Applications " }, { "code": null, "e": 26276, "s": 26075, "text": "Loading of containers like trucks.Placing data on multiple disks.Job scheduling.Packing advertisements in fixed length radio/TV station breaks.Storing a large collection of music onto tapes/CD’s, etc." }, { "code": null, "e": 26311, "s": 26276, "text": "Loading of containers like trucks." }, { "code": null, "e": 26343, "s": 26311, "text": "Placing data on multiple disks." }, { "code": null, "e": 26359, "s": 26343, "text": "Job scheduling." }, { "code": null, "e": 26423, "s": 26359, "text": "Packing advertisements in fixed length radio/TV station breaks." }, { "code": null, "e": 26481, "s": 26423, "text": "Storing a large collection of music onto tapes/CD’s, etc." }, { "code": null, "e": 26834, "s": 26481, "text": "Online Algorithms These algorithms are for Bin Packing problems where items arrive one at a time (in unknown order), each must be put in a bin, before considering the next item.1. Next Fit: When processing next item, check if it fits in the same bin as the last item. Use a new bin only if it does not. Below is C++ implementation for this algorithm. " }, { "code": null, "e": 26838, "s": 26834, "text": "C++" }, { "code": null, "e": 26843, "s": 26838, "text": "Java" }, { "code": null, "e": 26851, "s": 26843, "text": "Python3" }, { "code": null, "e": 26854, "s": 26851, "text": "C#" }, { "code": null, "e": 26865, "s": 26854, "text": "Javascript" }, { "code": "// C++ program to find number of bins required using// next fit algorithm.#include <bits/stdc++.h>using namespace std; // Returns number of bins required using next fit// online algorithmint nextFit(int weight[], int n, int c){ // Initialize result (Count of bins) and remaining // capacity in current bin. int res = 0, bin_rem = c; // Place items one by one for (int i = 0; i < n; i++) { // If this item can't fit in current bin if (weight[i] > bin_rem) { res++; // Use a new bin bin_rem = c - weight[i]; } else bin_rem -= weight[i]; } return res;} // Driver programint main(){ int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = sizeof(weight) / sizeof(weight[0]); cout << \"Number of bins required in Next Fit : \" << nextFit(weight, n, c); return 0;}", "e": 27732, "s": 26865, "text": null }, { "code": "// Java program to find number// of bins required using// next fit algorithm.class GFG { // Returns number of bins required // using next fit online algorithm static int nextFit(int weight[], int n, int c) { // Initialize result (Count of bins) and remaining // capacity in current bin. int res = 0, bin_rem = c; // Place items one by one for (int i = 0; i < n; i++) { // If this item can't fit in current bin if (weight[i] > bin_rem) { res++; // Use a new bin bin_rem = c - weight[i]; } else bin_rem -= weight[i]; } return res; } // Driver program public static void main(String[] args) { int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = weight.length; System.out.println(\"Number of bins required in Next Fit : \" + nextFit(weight, n, c)); }} // This code has been contributed by 29AjayKumar", "e": 28732, "s": 27732, "text": null }, { "code": "# Python3 implementation for above approachdef nextfit(weight, c): res = 0 rem = c for _ in range(len(weight)): if rem >= weight[_]: rem = rem - weight[_] else: res += 1 rem = c - weight[_] return res # Driver Codeweight = [2, 5, 4, 7, 1, 3, 8]c = 10 print(\"Number of bins required in Next Fit :\", nextfit(weight, c)) # This code is contributed by code_freak", "e": 29176, "s": 28732, "text": null }, { "code": " // C# program to find number// of bins required using// next fit algorithm.using System; class GFG{ // Returns number of bins required // using next fit online algorithm static int nextFit(int []weight, int n, int c) { // Initialize result (Count of bins) and remaining // capacity in current bin. int res = 0, bin_rem = c; // Place items one by one for (int i = 0; i < n; i++) { // If this item can't fit in current bin if (weight[i] > bin_rem) { res++; // Use a new bin bin_rem = c - weight[i]; } else bin_rem -= weight[i]; } return res; } // Driver program public static void Main(String[] args) { int []weight = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = weight.Length; Console.WriteLine(\"Number of bins required\" + \" in Next Fit : \" + nextFit(weight, n, c)); }} // This code is contributed by Rajput-Ji", "e": 30221, "s": 29176, "text": null }, { "code": "<script> // JavaScript program to find number// of bins required using// next fit algorithm. // Returns number of bins required // using next fit online algorithm function nextFit(weight, n, c) { // Initialize result (Count of bins) and remaining // capacity in current bin. let res = 0, bin_rem = c; // Place items one by one for (let i = 0; i < n; i++) { // If this item can't fit in current bin if (weight[i] > bin_rem) { res++; // Use a new bin bin_rem = c - weight[i]; } else bin_rem -= weight[i]; } return res; } // Driver Code let weight = [ 2, 5, 4, 7, 1, 3, 8 ]; let c = 10; let n = weight.length; document.write(\"Number of bins required in Next Fit : \" + nextFit(weight, n, c)); // This code is contributed by target_2.</script>", "e": 31184, "s": 30221, "text": null }, { "code": null, "e": 31193, "s": 31184, "text": "Output: " }, { "code": null, "e": 31233, "s": 31193, "text": "Number of bins required in Next Fit : 4" }, { "code": null, "e": 31920, "s": 31233, "text": "Next Fit is a simple algorithm. It requires only O(n) time and O(1) extra space to process n items. Next Fit is 2 approximate, i.e., the number of bins used by this algorithm is bounded by twice of optimal. Consider any two adjacent bins. The sum of items in these two bins must be > c; otherwise, NextFit would have put all the items of second bin into the first. The same holds for all other bins. Thus, at most half the space is wasted, and so Next Fit uses at most 2M bins if M is optimal.2. First Fit: When processing the next item, scan the previous bins in order and place the item in the first bin that fits. Start a new bin only if it does not fit in any of the existing bins. " }, { "code": null, "e": 31924, "s": 31920, "text": "C++" }, { "code": null, "e": 31929, "s": 31924, "text": "Java" }, { "code": null, "e": 31937, "s": 31929, "text": "Python3" }, { "code": null, "e": 31940, "s": 31937, "text": "C#" }, { "code": null, "e": 31951, "s": 31940, "text": "Javascript" }, { "code": "// C++ program to find number of bins required using// First Fit algorithm.#include <bits/stdc++.h>using namespace std; // Returns number of bins required using first fit// online algorithmint firstFit(int weight[], int n, int c){ // Initialize result (Count of bins) int res = 0; // Create an array to store remaining space in bins // there can be at most n bins int bin_rem[n]; // Place items one by one for (int i = 0; i < n; i++) { // Find the first bin that can accommodate // weight[i] int j; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i]) { bin_rem[j] = bin_rem[j] - weight[i]; break; } } // If no bin could accommodate weight[i] if (j == res) { bin_rem[res] = c - weight[i]; res++; } } return res;} // Driver programint main(){ int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = sizeof(weight) / sizeof(weight[0]); cout << \"Number of bins required in First Fit : \" << firstFit(weight, n, c); return 0;}", "e": 33086, "s": 31951, "text": null }, { "code": "// Java program to find number of bins required using// First Fit algorithm.class GFG{ // Returns number of bins required using first fit// online algorithmstatic int firstFit(int weight[], int n, int c){ // Initialize result (Count of bins) int res = 0; // Create an array to store remaining space in bins // there can be at most n bins int []bin_rem = new int[n]; // Place items one by one for (int i = 0; i < n; i++) { // Find the first bin that can accommodate // weight[i] int j; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i]) { bin_rem[j] = bin_rem[j] - weight[i]; break; } } // If no bin could accommodate weight[i] if (j == res) { bin_rem[res] = c - weight[i]; res++; } } return res;} // Driver programpublic static void main(String[] args){ int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = weight.length; System.out.print(\"Number of bins required in First Fit : \" + firstFit(weight, n, c));}} // This code is contributed by Rajput-Ji", "e": 34269, "s": 33086, "text": null }, { "code": "# Python program to find number of bins required using# First Fit algorithm. # Returns number of bins required using first fit# online algorithmdef firstFit(weight, n, c): # Initialize result (Count of bins) res = 0 # Create an array to store remaining space in bins # there can be at most n bins bin_rem = [0]*n # Place items one by one for i in range(n): # Find the first bin that can accommodate # weight[i] j = 0 while( j < res): if (bin_rem[j] >= weight[i]): bin_rem[j] = bin_rem[j] - weight[i] break j+=1 # If no bin could accommodate weight[i] if (j == res): bin_rem[res] = c - weight[i] res= res+1 return res # Driver programweight = [2, 5, 4, 7, 1, 3, 8]c = 10n = len(weight)print(\"Number of bins required in First Fit : \",firstFit(weight, n, c)) # This code is contributed by shubhamsingh10", "e": 35249, "s": 34269, "text": null }, { "code": "// C# program to find number of bins required using// First Fit algorithm.using System; class GFG{ // Returns number of bins required using first fit// online algorithmstatic int firstFit(int []weight, int n, int c){ // Initialize result (Count of bins) int res = 0; // Create an array to store remaining space in bins // there can be at most n bins int []bin_rem = new int[n]; // Place items one by one for (int i = 0; i < n; i++) { // Find the first bin that can accommodate // weight[i] int j; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i]) { bin_rem[j] = bin_rem[j] - weight[i]; break; } } // If no bin could accommodate weight[i] if (j == res) { bin_rem[res] = c - weight[i]; res++; } } return res;} // Driver codepublic static void Main(String[] args){ int []weight = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = weight.Length; Console.Write(\"Number of bins required in First Fit : \" + firstFit(weight, n, c));}} // This code is contributed by 29AjayKumar", "e": 36440, "s": 35249, "text": null }, { "code": "<script>// Javascript program to find number of bins required using// First Fit algorithm. // Returns number of bins required using first fit// online algorithmfunction firstFit(weight,n,c){ // Initialize result (Count of bins) let res = 0; // Create an array to store remaining space in bins // there can be at most n bins let bin_rem = new Array(n); // Place items one by one for (let i = 0; i < n; i++) { // Find the first bin that can accommodate // weight[i] let j; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i]) { bin_rem[j] = bin_rem[j] - weight[i]; break; } } // If no bin could accommodate weight[i] if (j == res) { bin_rem[res] = c - weight[i]; res++; } } return res;} // Driver programlet weight=[ 2, 5, 4, 7, 1, 3, 8];let c = 10;let n = weight.length;document.write(\"Number of bins required in First Fit : \" + firstFit(weight, n, c)); // This code is contributed by patel2127</script>", "e": 37557, "s": 36440, "text": null }, { "code": null, "e": 37566, "s": 37557, "text": "Output: " }, { "code": null, "e": 37607, "s": 37566, "text": "Number of bins required in First Fit : 4" }, { "code": null, "e": 38064, "s": 37607, "text": "The above implementation of First Fit requires O(n2) time, but First Fit can be implemented in O(n Log n) time using Self-Balancing Binary Search Trees.If M is the optimal number of bins, then First Fit never uses more than 1.7M bins. So First-Fit is better than Next Fit in terms of upper bound on number of bins.3. Best Fit: The idea is to places the next item in the *tightest* spot. That is, put it in the bin so that the smallest empty space is left. " }, { "code": null, "e": 38068, "s": 38064, "text": "C++" }, { "code": null, "e": 38073, "s": 38068, "text": "Java" }, { "code": null, "e": 38081, "s": 38073, "text": "Python3" }, { "code": null, "e": 38084, "s": 38081, "text": "C#" }, { "code": null, "e": 38095, "s": 38084, "text": "Javascript" }, { "code": "// C++ program to find number// of bins required using// Best fit algorithm.#include <bits/stdc++.h>using namespace std; // Returns number of bins required using best fit// online algorithmint bestFit(int weight[], int n, int c){ // Initialize result (Count of bins) int res = 0; // Create an array to store // remaining space in bins // there can be at most n bins int bin_rem[n]; // Place items one by one for (int i = 0; i < n; i++) { // Find the best bin that can accommodate // weight[i] int j; // Initialize minimum space left and index // of best bin int min = c + 1, bi = 0; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] < min) { bi = j; min = bin_rem[j] - weight[i]; } } // If no bin could accommodate weight[i], // create a new bin if (min == c + 1) { bin_rem[res] = c - weight[i]; res++; } else // Assign the item to best bin bin_rem[bi] -= weight[i]; } return res;} // Driver programint main(){ int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = sizeof(weight) / sizeof(weight[0]); cout << \"Number of bins required in Best Fit : \" << bestFit(weight, n, c); return 0;}", "e": 39497, "s": 38095, "text": null }, { "code": "// Java program to find number// of bins required using// Best fit algorithm.class GFG{ // Returns number of bins// required using best fit// online algorithmstatic int bestFit(int weight[], int n, int c){ // Initialize result (Count of bins) int res = 0; // Create an array to store // remaining space in bins // there can be at most n bins int []bin_rem = new int[n]; // Place items one by one for (int i = 0; i < n; i++) { // Find the best bin that // can accommodate // weight[i] int j; // Initialize minimum space // left and index // of best bin int min = c + 1, bi = 0; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] < min) { bi = j; min = bin_rem[j] - weight[i]; } } // If no bin could accommodate weight[i], // create a new bin if (min == c + 1) { bin_rem[res] = c - weight[i]; res++; } else // Assign the item to best bin bin_rem[bi] -= weight[i]; } return res;} // Driver codepublic static void main(String[] args){ int []weight = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = weight.length; System.out.print(\"Number of bins required in Best Fit : \" + bestFit(weight, n, c));}} // This code is contributed by 29AjayKumar", "e": 40980, "s": 39497, "text": null }, { "code": "# Python3 program to find number# of bins required using# First Fit algorithm. # Returns number of bins required# using first fit# online algorithmdef firstFit(weight, n, c): # Initialize result (Count of bins) res = 0; # Create an array to store # remaining space in bins # there can be at most n bins bin_rem = [0]*n; # Place items one by one for i in range(n): # Find the first bin that # can accommodate # weight[i] j = 0; # Initialize minimum space # left and index # of best bin min = c + 1; bi = 0; for j in range(res): if (bin_rem[j] >= weight[i] and bin_rem[j] - weight[i] < min): bi = j; min = bin_rem[j] - weight[i]; # If no bin could accommodate weight[i], # create a new bin if (min == c + 1): bin_rem[res] = c - weight[i]; res += 1; else: # Assign the item to best bin bin_rem[bi] -= weight[i]; return res; # Driver codeif __name__ == '__main__': weight = [ 2, 5, 4, 7, 1, 3, 8 ]; c = 10; n = len(weight); print(\"Number of bins required in First Fit : \", firstFit(weight, n, c)); # This code is contributed by Rajput-Ji", "e": 42334, "s": 40980, "text": null }, { "code": "// C# program to find number// of bins required using// Best fit algorithm.using System; class GFG { // Returns number of bins // required using best fit // online algorithm static int bestFit(int[] weight, int n, int c) { // Initialize result (Count of bins) int res = 0; // Create an array to store // remaining space in bins // there can be at most n bins int[] bin_rem = new int[n]; // Place items one by one for (int i = 0; i < n; i++) { // Find the best bin that // can accommodate // weight[i] int j; // Initialize minimum space // left and index // of best bin int min = c + 1, bi = 0; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] < min) { bi = j; min = bin_rem[j] - weight[i]; } } // If no bin could accommodate weight[i], // create a new bin if (min == c + 1) { bin_rem[res] = c - weight[i]; res++; } // Assign the item to best bin else bin_rem[bi] -= weight[i]; } return res; } // Driver code public static void Main(String[] args) { int[] weight = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = weight.Length; Console.Write( \"Number of bins required in Best Fit : \" + bestFit(weight, n, c)); }} // This code is contributed by 29AjayKumar", "e": 44015, "s": 42334, "text": null }, { "code": "<script>// javascript program to find number// of bins required using// Best fit algorithm.// Returns number of bins // required using best fit // online algorithm function bestFit(weight , n , c) { // Initialize result (Count of bins) var res = 0; // Create an array to store // remaining space in bins // there can be at most n bins var bin_rem = Array(n).fill(0); // Place items one by one for (i = 0; i < n; i++) { // Find the best bin that // can accommodate // weight[i] var j; // Initialize minimum space // left and index // of best bin var min = c + 1, bi = 0; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] < min) { bi = j; min = bin_rem[j] - weight[i]; } } // If no bin could accommodate weight[i], // create a new bin if (min == c + 1) { bin_rem[res] = c - weight[i]; res++; } else // Assign the item to best bin bin_rem[bi] -= weight[i]; } return res; } // Driver code var weight = [ 2, 5, 4, 7, 1, 3, 8 ]; var c = 10; var n = weight.length; document.write(\"Number of bins required in Best Fit : \" + bestFit(weight, n, c)); // This code contributed by gauravrajput1</script>", "e": 45531, "s": 44015, "text": null }, { "code": null, "e": 45540, "s": 45531, "text": "Output: " }, { "code": null, "e": 45580, "s": 45540, "text": "Number of bins required in Best Fit : 4" }, { "code": null, "e": 46014, "s": 45580, "text": "Best Fit can also be implemented in O(n Log n) time using Self-Balancing Binary Search Trees.If M is the optimal number of bins, then Best Fit never uses more than 1.7M bins. So Best Fit is same as First Fit and better than Next Fit in terms of upper bound on number of bins.4. Worst Fit: The idea is to places the next item in the least tight spot to even out the bins. That is, put it in the bin so that most empty space is left. " }, { "code": null, "e": 46018, "s": 46014, "text": "C++" }, { "code": null, "e": 46023, "s": 46018, "text": "Java" }, { "code": null, "e": 46026, "s": 46023, "text": "C#" }, { "code": null, "e": 46037, "s": 46026, "text": "Javascript" }, { "code": "// C++ program to find number of bins required using// Worst fit algorithm.#include <bits/stdc++.h>using namespace std; // Returns number of bins required using worst fit// online algorithmint worstFit(int weight[], int n, int c){ // Initialize result (Count of bins) int res = 0; // Create an array to store remaining space in bins // there can be at most n bins int bin_rem[n]; // Place items one by one for (int i = 0; i < n; i++) { // Find the best bin that ca\\n accommodate // weight[i] int j; // Initialize maximum space left and index // of worst bin int mx = -1, wi = 0; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] > mx) { wi = j; mx = bin_rem[j] - weight[i]; } } // If no bin could accommodate weight[i], // create a new bin if (mx == -1) { bin_rem[res] = c - weight[i]; res++; } else // Assign the item to best bin bin_rem[wi] -= weight[i]; } return res;} // Driver programint main(){ int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = sizeof(weight) / sizeof(weight[0]); cout << \"Number of bins required in Worst Fit : \" << worstFit(weight, n, c); return 0;} // This code is contributed by gromperen", "e": 47426, "s": 46037, "text": null }, { "code": "// Java program to find number of bins required using// Worst fit algorithm.class GFG{ // Returns number of bins required using worst fit// online algorithmstatic int worstFit(int weight[], int n, int c){ // Initialize result (Count of bins) int res = 0; // Create an array to store remaining space in bins // there can be at most n bins int bin_rem[]= new int[n]; // Place items one by one for (int i = 0; i < n; i++) { // Find the best bin that ca\\n accommodate // weight[i] int j; // Initialize maximum space left and index // of worst bin int mx = -1, wi = 0; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] > mx) { wi = j; mx = bin_rem[j] - weight[i]; } } // If no bin could accommodate weight[i], // create a new bin if (mx == -1) { bin_rem[res] = c - weight[i]; res++; } else // Assign the item to best bin bin_rem[wi] -= weight[i]; } return res;} // Driver programpublic static void main(String[] args){ int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = weight.length; System.out.print(\"Number of bins required in Worst Fit : \" +worstFit(weight, n, c));}} // This code is contributed by shivanisinghss2110", "e": 48821, "s": 47426, "text": null }, { "code": "// C# program to find number of bins required using// Worst fit algorithm.using System;class GFG{ // Returns number of bins required using worst fit// online algorithmstatic int worstFit(int []weight, int n, int c){ // Initialize result (Count of bins) int res = 0; // Create an array to store remaining space in bins // there can be at most n bins int []bin_rem= new int[n]; // Place items one by one for (int i = 0; i < n; i++) { // Find the best bin that ca\\n accommodate // weight[i] int j; // Initialize maximum space left and index // of worst bin int mx = -1, wi = 0; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] > mx) { wi = j; mx = bin_rem[j] - weight[i]; } } // If no bin could accommodate weight[i], // create a new bin if (mx == -1) { bin_rem[res] = c - weight[i]; res++; } else // Assign the item to best bin bin_rem[wi] -= weight[i]; } return res;} // Driver programpublic static void Main(String[] args){ int []weight = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = weight.Length; Console.Write(\"Number of bins required in Worst Fit : \" +worstFit(weight, n, c));}} // This code is contributed by shivanisinghss2110", "e": 50224, "s": 48821, "text": null }, { "code": "<script> // javascript program to find number of bins required using// Worst fit algorithm.// Returns number of bins required using worst fit// online algorithmfunction worstFit( weight, n, c){ // Initialize result (Count of bins) var res = 0; // Create an array to store remaining space in bins // there can be at most n bins var bin_rem = Array(n).fill(0); // Place items one by one for (var i = 0; i < n; i++) { // Find the best bin that ca\\n accommodate // weight[i] var j; // Initialize maximum space left and index // of worst bin var mx = -1, wi = 0; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i] && bin_rem[j] - weight[i] > mx) { wi = j; mx = bin_rem[j] - weight[i]; } } // If no bin could accommodate weight[i], // create a new bin if (mx == -1) { bin_rem[res] = c - weight[i]; res++; } else // Assign the item to best bin bin_rem[wi] -= weight[i]; } return res;} // Driver program var weight = [ 2, 5, 4, 7, 1, 3, 8 ]; var c = 10; var n = weight.length; document.write(\"Number of bins required in Worst Fit : \" +worstFit(weight, n, c)); // This code is contributed by shivanisinghss2110 </script>", "e": 51580, "s": 50224, "text": null }, { "code": null, "e": 51589, "s": 51580, "text": "Output: " }, { "code": null, "e": 51630, "s": 51589, "text": "Number of bins required in Worst Fit : 4" }, { "code": null, "e": 52485, "s": 51630, "text": "Worst Fit can also be implemented in O(n Log n) time using Self-Balancing Binary Search Trees.If M is the optimal number of bins, then Best Fit never uses more than 2M-2 bins. So Worst Fit is same as Next Fit in terms of upper bound on number of bins. Offline Algorithms In the offline version, we have all items upfront. Unfortunately offline version is also NP Complete, but we have a better approximate algorithm for it. First Fit Decreasing uses at most (4M + 1)/3 bins if the optimal is M.4. First Fit Decreasing: A trouble with online algorithms is that packing large items is difficult, especially if they occur late in the sequence. We can circumvent this by *sorting* the input sequence, and placing the large items first. With sorting, we get First Fit Decreasing and Best Fit Decreasing, as offline analogues of online First Fit and Best Fit. " }, { "code": null, "e": 52489, "s": 52485, "text": "C++" }, { "code": null, "e": 52494, "s": 52489, "text": "Java" }, { "code": null, "e": 52497, "s": 52494, "text": "C#" }, { "code": "// C++ program to find number of bins required using// First Fit Decreasing algorithm.#include <bits/stdc++.h>using namespace std; /* Copy firstFit() from above */ // Returns number of bins required using first fit// decreasing offline algorithmint firstFitDec(int weight[], int n, int c){ // First sort all weights in decreasing order sort(weight, weight + n, std::greater<int>()); // Now call first fit for sorted items return firstFit(weight, n, c);} // Driver programint main(){ int weight[] = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = sizeof(weight) / sizeof(weight[0]); cout << \"Number of bins required in First Fit \" << \"Decreasing : \" << firstFitDec(weight, n, c); return 0;}", "e": 53220, "s": 52497, "text": null }, { "code": "// Java program to find number of bins required using// First Fit Decreasing algorithm.import java.util.*; class GFG{ /* Copy firstFit() from above */ // Returns number of bins required using first fit // decreasing offline algorithm static int firstFitDec(Integer weight[], int n, int c) { // First sort all weights in decreasing order Arrays.sort(weight, Collections.reverseOrder()); // Now call first fit for sorted items return firstFit(weight, n, c); } // Driver code public static void main(String[] args) { Integer weight[] = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = weight.length; System.out.print(\"Number of bins required in First Fit \" + \"Decreasing : \" + firstFitDec(weight, n, c)); }} // This code is contributed by Rajput-Ji", "e": 54076, "s": 53220, "text": null }, { "code": "// C# program to find number of bins required using// First Fit Decreasing algorithm.using System; public class GFG{ /* Copy firstFit() from above */ // Returns number of bins required using first fit // decreasing offline algorithm static int firstFitDec(int []weight, int n, int c) { // First sort all weights in decreasing order Array.Sort(weight); Array.Reverse(weight); // Now call first fit for sorted items return firstFit(weight, n, c); } static int firstFit(int []weight, int n, int c) { // Initialize result (Count of bins) int res = 0; // Create an array to store remaining space in bins // there can be at most n bins int []bin_rem = new int[n]; // Place items one by one for (int i = 0; i < n; i++) { // Find the first bin that can accommodate // weight[i] int j; for (j = 0; j < res; j++) { if (bin_rem[j] >= weight[i]) { bin_rem[j] = bin_rem[j] - weight[i]; break; } } // If no bin could accommodate weight[i] if (j == res) { bin_rem[res] = c - weight[i]; res++; } } return res; } // Driver code public static void Main(String[] args) { int []weight = { 2, 5, 4, 7, 1, 3, 8 }; int c = 10; int n = weight.Length; Console.Write(\"Number of bins required in First Fit \" + \"Decreasing : \" + firstFitDec(weight, n, c)); }} // This code is contributed by 29AjayKumar", "e": 55781, "s": 54076, "text": null }, { "code": null, "e": 55789, "s": 55781, "text": "Output:" }, { "code": null, "e": 55841, "s": 55789, "text": "Number of bins required in First Fit Decreasing : 3" }, { "code": null, "e": 56215, "s": 55841, "text": "First Fit decreasing produces the best result for the sample input because items are sorted first.First Fit Decreasing can also be implemented in O(n Log n) time using Self-Balancing Binary Search Trees.This article is contributed by Dheeraj Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 56227, "s": 56215, "text": "29AjayKumar" }, { "code": null, "e": 56241, "s": 56227, "text": "GiulioMecocci" }, { "code": null, "e": 56252, "s": 56241, "text": "code_freak" }, { "code": null, "e": 56262, "s": 56252, "text": "Rajput-Ji" }, { "code": null, "e": 56272, "s": 56262, "text": "gromperen" }, { "code": null, "e": 56283, "s": 56272, "text": "firoz_baba" }, { "code": null, "e": 56292, "s": 56283, "text": "target_2" }, { "code": null, "e": 56306, "s": 56292, "text": "GauravRajput1" }, { "code": null, "e": 56315, "s": 56306, "text": "sooda367" }, { "code": null, "e": 56323, "s": 56315, "text": "clintra" }, { "code": null, "e": 56338, "s": 56323, "text": "adnanirshad158" }, { "code": null, "e": 56348, "s": 56338, "text": "patel2127" }, { "code": null, "e": 56367, "s": 56348, "text": "shivanisinghss2110" }, { "code": null, "e": 56382, "s": 56367, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 56389, "s": 56382, "text": "Greedy" }, { "code": null, "e": 56396, "s": 56389, "text": "Greedy" }, { "code": null, "e": 56494, "s": 56396, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 56503, "s": 56494, "text": "Comments" }, { "code": null, "e": 56516, "s": 56503, "text": "Old Comments" }, { "code": null, "e": 56607, "s": 56516, "text": "Split the given array into K sub-arrays such that maximum sum of all sub arrays is minimum" }, { "code": null, "e": 56660, "s": 56607, "text": "Program for First Fit algorithm in Memory Management" }, { "code": null, "e": 56695, "s": 56660, "text": "Optimal Page Replacement Algorithm" }, { "code": null, "e": 56747, "s": 56695, "text": "Program for Best Fit algorithm in Memory Management" }, { "code": null, "e": 56777, "s": 56747, "text": "Max Flow Problem Introduction" }, { "code": null, "e": 56830, "s": 56777, "text": "Program for Worst Fit algorithm in Memory Management" }, { "code": null, "e": 56858, "s": 56830, "text": "Optimal File Merge Patterns" }, { "code": null, "e": 56875, "s": 56858, "text": "Huffman Decoding" }, { "code": null, "e": 56954, "s": 56875, "text": "Maximum items that can be bought from the cost Array based on given conditions" } ]
Types of Operator Overloading in C++
17 May, 2021 Operator Overloading: C++ provides a special function to change the current functionality of some operators within its class which is often called as operator overloading. Operator Overloading is the method by which we can change the function of some specific operators to do some different task. This can be done by declaring the function, its syntax is, Return_Type classname :: operator op(Argument list) { Function Body } In the above syntax Return_Type is value type to be returned to another object, operator op is the function where the operator is a keyword and op is the operator to be overloaded.Operator function must be either non-static (member function) or friend function.Operator Overloading can be done by using three approaches, they are Overloading unary operator.Overloading binary operator.Overloading binary operator using a friend function. Overloading unary operator. Overloading binary operator. Overloading binary operator using a friend function. Below are some criteria/rules to define the operator function: In case of a non-static function, the binary operator should have only one argument and unary should not have an argument. In the case of a friend function, the binary operator should have only two argument and unary should have only one argument. All the class member object should be public if operator overloading is implemented. Operators that cannot be overloaded are . .* :: ?: Operator cannot be used to overload when declaring that function as friend function = () [] ->. Refer this, for more rules of Operator Overloading Overloading Unary Operator: Let us consider to overload (-) unary operator. In unary operator function, no arguments should be passed. It works only with one class objects. It is a overloading of an operator operating on a single operand.Example: Assume that class Distance takes two member object i.e. feet and inches, create a function by which Distance object should decrement the value of feet and inches by 1 (having single operand of Distance Type). Overloading Unary Operator: Let us consider to overload (-) unary operator. In unary operator function, no arguments should be passed. It works only with one class objects. It is a overloading of an operator operating on a single operand.Example: Assume that class Distance takes two member object i.e. feet and inches, create a function by which Distance object should decrement the value of feet and inches by 1 (having single operand of Distance Type). CPP // C++ program to show unary operator overloading#include <iostream> using namespace std; class Distance {public: // Member Object int feet, inch; // Constructor to initialize the object's value Distance(int f, int i) { this->feet = f; this->inch = i; } // Overloading(-) operator to perform decrement // operation of Distance object void operator-() { feet--; inch--; cout << "\nFeet & Inches(Decrement): " << feet << "'" << inch; }}; // Driver Codeint main(){ // Declare and Initialize the constructor Distance d1(8, 9); // Use (-) unary operator by single operand -d1; return 0;} Feet & Inches(Decrement): 7'8 In the above program, it shows that no argument is passed and no return_type value is returned, because unary operator works on a single operand. (-) operator change the functionality to its member function.Note: d2 = -d1 will not work, because operator-() does not return any value.Overloading Binary Operator: In binary operator overloading function, there should be one argument to be passed. It is overloading of an operator operating on two operands.Let’s take the same example of class Distance, but this time, add two distance objects. In the above program, it shows that no argument is passed and no return_type value is returned, because unary operator works on a single operand. (-) operator change the functionality to its member function.Note: d2 = -d1 will not work, because operator-() does not return any value. Overloading Binary Operator: In binary operator overloading function, there should be one argument to be passed. It is overloading of an operator operating on two operands.Let’s take the same example of class Distance, but this time, add two distance objects. CPP // C++ program to show binary operator overloading#include <iostream> using namespace std; class Distance {public: // Member Object int feet, inch; // No Parameter Constructor Distance() { this->feet = 0; this->inch = 0; } // Constructor to initialize the object's value // Parameterized Constructor Distance(int f, int i) { this->feet = f; this->inch = i; } // Overloading (+) operator to perform addition of // two distance object Distance operator+(Distance& d2) // Call by reference { // Create an object to return Distance d3; // Perform addition of feet and inches d3.feet = this->feet + d2.feet; d3.inch = this->inch + d2.inch; // Return the resulting object return d3; }}; // Driver Codeint main(){ // Declaring and Initializing first object Distance d1(8, 9); // Declaring and Initializing second object Distance d2(10, 2); // Declaring third object Distance d3; // Use overloaded operator d3 = d1 + d2; // Display the result cout << "\nTotal Feet & Inches: " << d3.feet << "'" << d3.inch; return 0;} Total Feet & Inches: 18'11 Here in the above program, See Line no. 26, Distance operator+(Distance &d2), here return type of function is distance and it uses call by references to pass an argument. See Line no. 49, d3 = d1 + d2; here, d1 calls the operator function of its class object and takes d2 as a parameter, by which operator function return object and the result will reflect in the d3 object.Pictorial View of working of Binary Operator: Here in the above program, See Line no. 26, Distance operator+(Distance &d2), here return type of function is distance and it uses call by references to pass an argument. See Line no. 49, d3 = d1 + d2; here, d1 calls the operator function of its class object and takes d2 as a parameter, by which operator function return object and the result will reflect in the d3 object.Pictorial View of working of Binary Operator: Overloading Binary Operator using a Friend function: In this approach, the operator overloading function must precede with friend keyword, and declare a function class scope. Keeping in mind, friend operator function takes two parameters in a binary operator, varies one parameter in a unary operator. All the working and implementation would same as binary operator function except this function will be implemented outside of the class scope.Let’s take the same example using the friend function. Overloading Binary Operator using a Friend function: In this approach, the operator overloading function must precede with friend keyword, and declare a function class scope. Keeping in mind, friend operator function takes two parameters in a binary operator, varies one parameter in a unary operator. All the working and implementation would same as binary operator function except this function will be implemented outside of the class scope.Let’s take the same example using the friend function. CPP // C++ program to show binary operator overloading#include <iostream> using namespace std; class Distance {public: // Member Object int feet, inch; // No Parameter Constructor Distance() { this->feet = 0; this->inch = 0; } // Constructor to initialize the object's value // Parameterized Constructor Distance(int f, int i) { this->feet = f; this->inch = i; } // Declaring friend function using friend keyword friend Distance operator+(Distance&, Distance&);}; // Implementing friend function with two parametersDistance operator+(Distance& d1, Distance& d2) // Call by reference{ // Create an object to return Distance d3; // Perform addition of feet and inches d3.feet = d1.feet + d2.feet; d3.inch = d1.inch + d2.inch; // Return the resulting object return d3;} // Driver Codeint main(){ // Declaring and Initializing first object Distance d1(8, 9); // Declaring and Initializing second object Distance d2(10, 2); // Declaring third object Distance d3; // Use overloaded operator d3 = d1 + d2; // Display the result cout << "\nTotal Feet & Inches: " << d3.feet << "'" << d3.inch; return 0;} Total Feet & Inches: 18'11 Here in the above program, operator function is implemented outside of class scope by declaring that function as the friend function. Here in the above program, operator function is implemented outside of class scope by declaring that function as the friend function. In these ways, an operator can be overloaded to perform certain tasks by changing the functionality of operators. gaurav_jain adnanirshad158 cpp-operator cpp-operator-overloading C++ Technical Scripter cpp-operator CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Priority Queue in C++ Standard Template Library (STL) Sorting a vector in C++ Inheritance in C++ The C++ Standard Template Library (STL) C++ Classes and Objects Substring in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n17 May, 2021" }, { "code": null, "e": 78, "s": 54, "text": "Operator Overloading: " }, { "code": null, "e": 354, "s": 78, "text": "C++ provides a special function to change the current functionality of some operators within its class which is often called as operator overloading. Operator Overloading is the method by which we can change the function of some specific operators to do some different task. " }, { "code": null, "e": 415, "s": 354, "text": "This can be done by declaring the function, its syntax is, " }, { "code": null, "e": 489, "s": 415, "text": "Return_Type classname :: operator op(Argument list)\n{\n Function Body\n}" }, { "code": null, "e": 821, "s": 489, "text": "In the above syntax Return_Type is value type to be returned to another object, operator op is the function where the operator is a keyword and op is the operator to be overloaded.Operator function must be either non-static (member function) or friend function.Operator Overloading can be done by using three approaches, they are " }, { "code": null, "e": 929, "s": 821, "text": "Overloading unary operator.Overloading binary operator.Overloading binary operator using a friend function." }, { "code": null, "e": 957, "s": 929, "text": "Overloading unary operator." }, { "code": null, "e": 986, "s": 957, "text": "Overloading binary operator." }, { "code": null, "e": 1039, "s": 986, "text": "Overloading binary operator using a friend function." }, { "code": null, "e": 1104, "s": 1039, "text": "Below are some criteria/rules to define the operator function: " }, { "code": null, "e": 1227, "s": 1104, "text": "In case of a non-static function, the binary operator should have only one argument and unary should not have an argument." }, { "code": null, "e": 1352, "s": 1227, "text": "In the case of a friend function, the binary operator should have only two argument and unary should have only one argument." }, { "code": null, "e": 1437, "s": 1352, "text": "All the class member object should be public if operator overloading is implemented." }, { "code": null, "e": 1488, "s": 1437, "text": "Operators that cannot be overloaded are . .* :: ?:" }, { "code": null, "e": 1584, "s": 1488, "text": "Operator cannot be used to overload when declaring that function as friend function = () [] ->." }, { "code": null, "e": 1636, "s": 1584, "text": "Refer this, for more rules of Operator Overloading " }, { "code": null, "e": 2093, "s": 1636, "text": "Overloading Unary Operator: Let us consider to overload (-) unary operator. In unary operator function, no arguments should be passed. It works only with one class objects. It is a overloading of an operator operating on a single operand.Example: Assume that class Distance takes two member object i.e. feet and inches, create a function by which Distance object should decrement the value of feet and inches by 1 (having single operand of Distance Type). " }, { "code": null, "e": 2550, "s": 2093, "text": "Overloading Unary Operator: Let us consider to overload (-) unary operator. In unary operator function, no arguments should be passed. It works only with one class objects. It is a overloading of an operator operating on a single operand.Example: Assume that class Distance takes two member object i.e. feet and inches, create a function by which Distance object should decrement the value of feet and inches by 1 (having single operand of Distance Type). " }, { "code": null, "e": 2554, "s": 2550, "text": "CPP" }, { "code": "// C++ program to show unary operator overloading#include <iostream> using namespace std; class Distance {public: // Member Object int feet, inch; // Constructor to initialize the object's value Distance(int f, int i) { this->feet = f; this->inch = i; } // Overloading(-) operator to perform decrement // operation of Distance object void operator-() { feet--; inch--; cout << \"\\nFeet & Inches(Decrement): \" << feet << \"'\" << inch; }}; // Driver Codeint main(){ // Declare and Initialize the constructor Distance d1(8, 9); // Use (-) unary operator by single operand -d1; return 0;}", "e": 3224, "s": 2554, "text": null }, { "code": null, "e": 3258, "s": 3228, "text": "Feet & Inches(Decrement): 7'8" }, { "code": null, "e": 3805, "s": 3260, "text": "In the above program, it shows that no argument is passed and no return_type value is returned, because unary operator works on a single operand. (-) operator change the functionality to its member function.Note: d2 = -d1 will not work, because operator-() does not return any value.Overloading Binary Operator: In binary operator overloading function, there should be one argument to be passed. It is overloading of an operator operating on two operands.Let’s take the same example of class Distance, but this time, add two distance objects. " }, { "code": null, "e": 4089, "s": 3805, "text": "In the above program, it shows that no argument is passed and no return_type value is returned, because unary operator works on a single operand. (-) operator change the functionality to its member function.Note: d2 = -d1 will not work, because operator-() does not return any value." }, { "code": null, "e": 4351, "s": 4089, "text": "Overloading Binary Operator: In binary operator overloading function, there should be one argument to be passed. It is overloading of an operator operating on two operands.Let’s take the same example of class Distance, but this time, add two distance objects. " }, { "code": null, "e": 4355, "s": 4351, "text": "CPP" }, { "code": "// C++ program to show binary operator overloading#include <iostream> using namespace std; class Distance {public: // Member Object int feet, inch; // No Parameter Constructor Distance() { this->feet = 0; this->inch = 0; } // Constructor to initialize the object's value // Parameterized Constructor Distance(int f, int i) { this->feet = f; this->inch = i; } // Overloading (+) operator to perform addition of // two distance object Distance operator+(Distance& d2) // Call by reference { // Create an object to return Distance d3; // Perform addition of feet and inches d3.feet = this->feet + d2.feet; d3.inch = this->inch + d2.inch; // Return the resulting object return d3; }}; // Driver Codeint main(){ // Declaring and Initializing first object Distance d1(8, 9); // Declaring and Initializing second object Distance d2(10, 2); // Declaring third object Distance d3; // Use overloaded operator d3 = d1 + d2; // Display the result cout << \"\\nTotal Feet & Inches: \" << d3.feet << \"'\" << d3.inch; return 0;}", "e": 5531, "s": 4355, "text": null }, { "code": null, "e": 5562, "s": 5535, "text": "Total Feet & Inches: 18'11" }, { "code": null, "e": 5986, "s": 5564, "text": "Here in the above program, See Line no. 26, Distance operator+(Distance &d2), here return type of function is distance and it uses call by references to pass an argument. See Line no. 49, d3 = d1 + d2; here, d1 calls the operator function of its class object and takes d2 as a parameter, by which operator function return object and the result will reflect in the d3 object.Pictorial View of working of Binary Operator: " }, { "code": null, "e": 6408, "s": 5986, "text": "Here in the above program, See Line no. 26, Distance operator+(Distance &d2), here return type of function is distance and it uses call by references to pass an argument. See Line no. 49, d3 = d1 + d2; here, d1 calls the operator function of its class object and takes d2 as a parameter, by which operator function return object and the result will reflect in the d3 object.Pictorial View of working of Binary Operator: " }, { "code": null, "e": 6909, "s": 6408, "text": "Overloading Binary Operator using a Friend function: In this approach, the operator overloading function must precede with friend keyword, and declare a function class scope. Keeping in mind, friend operator function takes two parameters in a binary operator, varies one parameter in a unary operator. All the working and implementation would same as binary operator function except this function will be implemented outside of the class scope.Let’s take the same example using the friend function. " }, { "code": null, "e": 7410, "s": 6909, "text": "Overloading Binary Operator using a Friend function: In this approach, the operator overloading function must precede with friend keyword, and declare a function class scope. Keeping in mind, friend operator function takes two parameters in a binary operator, varies one parameter in a unary operator. All the working and implementation would same as binary operator function except this function will be implemented outside of the class scope.Let’s take the same example using the friend function. " }, { "code": null, "e": 7414, "s": 7410, "text": "CPP" }, { "code": "// C++ program to show binary operator overloading#include <iostream> using namespace std; class Distance {public: // Member Object int feet, inch; // No Parameter Constructor Distance() { this->feet = 0; this->inch = 0; } // Constructor to initialize the object's value // Parameterized Constructor Distance(int f, int i) { this->feet = f; this->inch = i; } // Declaring friend function using friend keyword friend Distance operator+(Distance&, Distance&);}; // Implementing friend function with two parametersDistance operator+(Distance& d1, Distance& d2) // Call by reference{ // Create an object to return Distance d3; // Perform addition of feet and inches d3.feet = d1.feet + d2.feet; d3.inch = d1.inch + d2.inch; // Return the resulting object return d3;} // Driver Codeint main(){ // Declaring and Initializing first object Distance d1(8, 9); // Declaring and Initializing second object Distance d2(10, 2); // Declaring third object Distance d3; // Use overloaded operator d3 = d1 + d2; // Display the result cout << \"\\nTotal Feet & Inches: \" << d3.feet << \"'\" << d3.inch; return 0;}", "e": 8637, "s": 7414, "text": null }, { "code": null, "e": 8668, "s": 8641, "text": "Total Feet & Inches: 18'11" }, { "code": null, "e": 8804, "s": 8670, "text": "Here in the above program, operator function is implemented outside of class scope by declaring that function as the friend function." }, { "code": null, "e": 8938, "s": 8804, "text": "Here in the above program, operator function is implemented outside of class scope by declaring that function as the friend function." }, { "code": null, "e": 9053, "s": 8938, "text": "In these ways, an operator can be overloaded to perform certain tasks by changing the functionality of operators. " }, { "code": null, "e": 9065, "s": 9053, "text": "gaurav_jain" }, { "code": null, "e": 9080, "s": 9065, "text": "adnanirshad158" }, { "code": null, "e": 9093, "s": 9080, "text": "cpp-operator" }, { "code": null, "e": 9118, "s": 9093, "text": "cpp-operator-overloading" }, { "code": null, "e": 9122, "s": 9118, "text": "C++" }, { "code": null, "e": 9141, "s": 9122, "text": "Technical Scripter" }, { "code": null, "e": 9154, "s": 9141, "text": "cpp-operator" }, { "code": null, "e": 9158, "s": 9154, "text": "CPP" }, { "code": null, "e": 9256, "s": 9158, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9283, "s": 9256, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 9326, "s": 9283, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 9360, "s": 9326, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 9385, "s": 9360, "text": "unordered_map in C++ STL" }, { "code": null, "e": 9439, "s": 9385, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 9463, "s": 9439, "text": "Sorting a vector in C++" }, { "code": null, "e": 9482, "s": 9463, "text": "Inheritance in C++" }, { "code": null, "e": 9522, "s": 9482, "text": "The C++ Standard Template Library (STL)" }, { "code": null, "e": 9546, "s": 9522, "text": "C++ Classes and Objects" } ]
Minimal to Canonical Form Conversion
02 Jun, 2020 Canonical Form is also called standard form, we directly obtained it from truth table and hence we have all the variable in normal or complimented form in each minterm. There are 3 steps for conversion of minimal form to canonical form. Find the Total Number of variable present in minimal form. Find the variables absent in each minterm. Try to apply operation for converting min to canonical term using one(1) or zero(o) logic. Conversion of Sum of Products (SOP) form to Canonical Form –Set of rules are same as stated above. Example-1: Input : Y=A+B'C Output : (A.B.C)+(A.B.C')+(A.B'.C)+(A.B'.C')+(A'.B'.C) Explanation – Step-1:Find the Total Number of variable present in minimal form like in this variables present are A, B, C. Step-2:Find the variables absent in each term like in this in this variable absent in minterm(0) is B and C and variable absent in minterm(1) is A. Step-3:Try to apply operation for converting min to canonical term using one(1) or zero(o) logic, In this case it is SOP form so we AND one(1) to each minterm where variables are absent in simple term if we multiply each minterm by one(1) then there is no effect on resultant equation so in this case, after that we replace one(1) by Sum (Variable +Complement of variable) then use Properties of switching algebra to solve further. Conversion steps – = A+B.C = (A.1)+(B.C.1) = (A.(B+B'))+((A+A').(B.C)) = ((A.B.C)+(A.B.C')+(A.B'.C)+(A.B'.C')+(A'.B'.C)) Conversion of Product of Sums(POS) form to Canonical Form –Set of rules are same as stated above. Example-2: Input : Y=(A+B+C).(A'+C) Output : (A+B+C').(A'+C+B).(A'+C+B') Explanation – Step-1:Find the Total Number of variable present in minimal form like in this variables present are A, B, C.Step-2:Find the variables absent in each term like in this in this variable absent is C in maxterm(1)Step-3:Try to apply operation for converting minimal to canonical term using one(1) or zero(o) logic, In this case it is POS form so we OR zero(0) to each maxterm where variables are absent in simple term if we add each maxterm by zero(0) then there is no effect on resultant equation so in this case, after that we replace zero(0) by Product(Variable * Complement of variable) then use Properties of switching algebra to solve further. Step-1:Find the Total Number of variable present in minimal form like in this variables present are A, B, C. Step-2:Find the variables absent in each term like in this in this variable absent is C in maxterm(1) Step-3:Try to apply operation for converting minimal to canonical term using one(1) or zero(o) logic, In this case it is POS form so we OR zero(0) to each maxterm where variables are absent in simple term if we add each maxterm by zero(0) then there is no effect on resultant equation so in this case, after that we replace zero(0) by Product(Variable * Complement of variable) then use Properties of switching algebra to solve further. Conversion steps – = (A+B+C).(A'+B) = (A+B+C').(A'+(B.B')+C) = (A+B+C').(A'+C+B).(A'+C+B') Digital Electronics & Logic Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Jun, 2020" }, { "code": null, "e": 223, "s": 54, "text": "Canonical Form is also called standard form, we directly obtained it from truth table and hence we have all the variable in normal or complimented form in each minterm." }, { "code": null, "e": 291, "s": 223, "text": "There are 3 steps for conversion of minimal form to canonical form." }, { "code": null, "e": 350, "s": 291, "text": "Find the Total Number of variable present in minimal form." }, { "code": null, "e": 393, "s": 350, "text": "Find the variables absent in each minterm." }, { "code": null, "e": 484, "s": 393, "text": "Try to apply operation for converting min to canonical term using one(1) or zero(o) logic." }, { "code": null, "e": 583, "s": 484, "text": "Conversion of Sum of Products (SOP) form to Canonical Form –Set of rules are same as stated above." }, { "code": null, "e": 594, "s": 583, "text": "Example-1:" }, { "code": null, "e": 668, "s": 594, "text": "Input : \nY=A+B'C \nOutput :\n(A.B.C)+(A.B.C')+(A.B'.C)+(A.B'.C')+(A'.B'.C) " }, { "code": null, "e": 682, "s": 668, "text": "Explanation –" }, { "code": null, "e": 791, "s": 682, "text": "Step-1:Find the Total Number of variable present in minimal form like in this variables present are A, B, C." }, { "code": null, "e": 939, "s": 791, "text": "Step-2:Find the variables absent in each term like in this in this variable absent in minterm(0) is B and C and variable absent in minterm(1) is A." }, { "code": null, "e": 1371, "s": 939, "text": "Step-3:Try to apply operation for converting min to canonical term using one(1) or zero(o) logic, In this case it is SOP form so we AND one(1) to each minterm where variables are absent in simple term if we multiply each minterm by one(1) then there is no effect on resultant equation so in this case, after that we replace one(1) by Sum (Variable +Complement of variable) then use Properties of switching algebra to solve further." }, { "code": null, "e": 1390, "s": 1371, "text": "Conversion steps –" }, { "code": null, "e": 1497, "s": 1390, "text": "= A+B.C \n= (A.1)+(B.C.1) \n= (A.(B+B'))+((A+A').(B.C)) \n= ((A.B.C)+(A.B.C')+(A.B'.C)+(A.B'.C')+(A'.B'.C)) " }, { "code": null, "e": 1595, "s": 1497, "text": "Conversion of Product of Sums(POS) form to Canonical Form –Set of rules are same as stated above." }, { "code": null, "e": 1606, "s": 1595, "text": "Example-2:" }, { "code": null, "e": 1671, "s": 1606, "text": "Input :\nY=(A+B+C).(A'+C)\n \nOutput :\n(A+B+C').(A'+C+B).(A'+C+B') " }, { "code": null, "e": 1685, "s": 1671, "text": "Explanation –" }, { "code": null, "e": 2331, "s": 1685, "text": "Step-1:Find the Total Number of variable present in minimal form like in this variables present are A, B, C.Step-2:Find the variables absent in each term like in this in this variable absent is C in maxterm(1)Step-3:Try to apply operation for converting minimal to canonical term using one(1) or zero(o) logic, In this case it is POS form so we OR zero(0) to each maxterm where variables are absent in simple term if we add each maxterm by zero(0) then there is no effect on resultant equation so in this case, after that we replace zero(0) by Product(Variable * Complement of variable) then use Properties of switching algebra to solve further." }, { "code": null, "e": 2440, "s": 2331, "text": "Step-1:Find the Total Number of variable present in minimal form like in this variables present are A, B, C." }, { "code": null, "e": 2542, "s": 2440, "text": "Step-2:Find the variables absent in each term like in this in this variable absent is C in maxterm(1)" }, { "code": null, "e": 2979, "s": 2542, "text": "Step-3:Try to apply operation for converting minimal to canonical term using one(1) or zero(o) logic, In this case it is POS form so we OR zero(0) to each maxterm where variables are absent in simple term if we add each maxterm by zero(0) then there is no effect on resultant equation so in this case, after that we replace zero(0) by Product(Variable * Complement of variable) then use Properties of switching algebra to solve further." }, { "code": null, "e": 2998, "s": 2979, "text": "Conversion steps –" }, { "code": null, "e": 3072, "s": 2998, "text": "= (A+B+C).(A'+B) \n= (A+B+C').(A'+(B.B')+C)\n= (A+B+C').(A'+C+B).(A'+C+B') " }, { "code": null, "e": 3107, "s": 3072, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 3115, "s": 3107, "text": "GATE CS" } ]
Toasts for Android Studio
22 May, 2018 A toast provides a simple popup message that is displayed on the current activity UI screen (e.g. Main Activity). Example : Syntax : // to get ContextContext context = getApplicationContext(); // message to displayString text = "Toast message"; // toast time duration, can also set manual value int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration);// to show the toasttoast.show(); We can also create toast with single line by passing variables directly to makeText() function. This method takes three parameters context, popup text message, the toast duration. After creating Toast object you can display the toast by using show() method. Example : Toast.makeText(MainActivity.this, "Error"+ msg, Toast.LENGTH_SHORT).show(); Creating a Custom Toast :If you are not satisfied with simple Toast view in Android, then you can go ahead to make a custom Toast. Actually, custom Toast is a modified simple Toast that makes your UI more attractive. So that when you create a custom Toast then two things are required, one is XML (custom_toast.xml) required for layout view of custom Toast and another is activity class (custom_activity.class) file where you can write Java code. Java class file passes the root View object to the setView(View) method. custom_toast.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/custom_toast_container" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#00AABB" android:orientation="horizontal" android:padding="8dp"> <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="8dp" android:src="@drawable/ic_warning" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#FFFFFF" android:textSize="8pt" android:textStyle="italic" /></LinearLayout> This is a XML layout for example purposes, so if you want your own design then you can create your own XML. Custom_Activity.class // get layout inflator object to inflate custom_toast layoutLayoutInflater inflater = getLayoutInflater(); // inflating custom_toast layoutView layout = inflater.inflate(R.layout.custom_toast,(ViewGroup)findViewById(R.id.custom_toast_container)); // Find TextView elements with help of layout object.TextView text = (TextView)layout.findViewById(R.id.text); // set custom Toast message.text.setText("Custom Toast message"); // Create the Toast objectToast toast = new Toast(getApplicationContext()); // to show toast at centre of screentoast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); // display duration then show() method displays Toast.toast.setDuration(Toast.LENGTH_LONG); // set custom layout toast.setView(layout); // show toasttoast.show(); android Technical Scripter TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Find the Wi-Fi Password Using CMD in Windows? Docker - COPY Instruction Setting up the environment in Java How to Run a Python Script using Docker? Running Python script on GPU. How to setup cron jobs in Ubuntu How to Add External JAR File to an IntelliJ IDEA Project? 'dd' command in Linux How to Delete Temporary Files in Windows 10? How to set up Command Prompt for Python in Windows10 ?
[ { "code": null, "e": 28, "s": 0, "text": "\n22 May, 2018" }, { "code": null, "e": 142, "s": 28, "text": "A toast provides a simple popup message that is displayed on the current activity UI screen (e.g. Main Activity)." }, { "code": null, "e": 152, "s": 142, "text": "Example :" }, { "code": null, "e": 161, "s": 152, "text": "Syntax :" }, { "code": "// to get ContextContext context = getApplicationContext(); // message to displayString text = \"Toast message\"; // toast time duration, can also set manual value int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration);// to show the toasttoast.show(); ", "e": 447, "s": 161, "text": null }, { "code": null, "e": 705, "s": 447, "text": "We can also create toast with single line by passing variables directly to makeText() function. This method takes three parameters context, popup text message, the toast duration. After creating Toast object you can display the toast by using show() method." }, { "code": null, "e": 715, "s": 705, "text": "Example :" }, { "code": "Toast.makeText(MainActivity.this, \"Error\"+ msg, Toast.LENGTH_SHORT).show();", "e": 791, "s": 715, "text": null }, { "code": null, "e": 1311, "s": 791, "text": "Creating a Custom Toast :If you are not satisfied with simple Toast view in Android, then you can go ahead to make a custom Toast. Actually, custom Toast is a modified simple Toast that makes your UI more attractive. So that when you create a custom Toast then two things are required, one is XML (custom_toast.xml) required for layout view of custom Toast and another is activity class (custom_activity.class) file where you can write Java code. Java class file passes the root View object to the setView(View) method." }, { "code": null, "e": 1328, "s": 1311, "text": "custom_toast.xml" }, { "code": "<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:id=\"@+id/custom_toast_container\" android:layout_width=\"fill_parent\" android:layout_height=\"fill_parent\" android:background=\"#00AABB\" android:orientation=\"horizontal\" android:padding=\"8dp\"> <ImageView android:id=\"@+id/image\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginRight=\"8dp\" android:src=\"@drawable/ic_warning\" /> <TextView android:id=\"@+id/text\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textColor=\"#FFFFFF\" android:textSize=\"8pt\" android:textStyle=\"italic\" /></LinearLayout>", "e": 2084, "s": 1328, "text": null }, { "code": null, "e": 2192, "s": 2084, "text": "This is a XML layout for example purposes, so if you want your own design then you can create your own XML." }, { "code": null, "e": 2214, "s": 2192, "text": "Custom_Activity.class" }, { "code": "// get layout inflator object to inflate custom_toast layoutLayoutInflater inflater = getLayoutInflater(); // inflating custom_toast layoutView layout = inflater.inflate(R.layout.custom_toast,(ViewGroup)findViewById(R.id.custom_toast_container)); // Find TextView elements with help of layout object.TextView text = (TextView)layout.findViewById(R.id.text); // set custom Toast message.text.setText(\"Custom Toast message\"); // Create the Toast objectToast toast = new Toast(getApplicationContext()); // to show toast at centre of screentoast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); // display duration then show() method displays Toast.toast.setDuration(Toast.LENGTH_LONG); // set custom layout toast.setView(layout); // show toasttoast.show();", "e": 2970, "s": 2214, "text": null }, { "code": null, "e": 2978, "s": 2970, "text": "android" }, { "code": null, "e": 2997, "s": 2978, "text": "Technical Scripter" }, { "code": null, "e": 3006, "s": 2997, "text": "TechTips" }, { "code": null, "e": 3104, "s": 3006, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3157, "s": 3104, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 3183, "s": 3157, "text": "Docker - COPY Instruction" }, { "code": null, "e": 3218, "s": 3183, "text": "Setting up the environment in Java" }, { "code": null, "e": 3259, "s": 3218, "text": "How to Run a Python Script using Docker?" }, { "code": null, "e": 3289, "s": 3259, "text": "Running Python script on GPU." }, { "code": null, "e": 3322, "s": 3289, "text": "How to setup cron jobs in Ubuntu" }, { "code": null, "e": 3380, "s": 3322, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 3402, "s": 3380, "text": "'dd' command in Linux" }, { "code": null, "e": 3447, "s": 3402, "text": "How to Delete Temporary Files in Windows 10?" } ]
How to group Bar Charts in Python-Plotly?
03 Jul, 2020 Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Grouping bar charts can be used to show multiple set of data items which are been compared with a single color which is used to indicate a specific series across all sets. Method 1: Using graph_objects class Example: Python3 import plotly.graph_objects as pximport numpy # creating random data through randomint # function of numpy.random np.random.seed(42) random_x= np.random.randint(1,101,100) random_y= np.random.randint(1,101,100) x = ['A', 'B', 'C', 'D'] plot = px.Figure(data=[go.Bar( name = 'Data 1', x = x, y = [100, 200, 500, 673] ), go.Bar( name = 'Data 2', x = x, y = [56, 123, 982, 213] )]) plot.show() Output: Method 2: Using express class Example 1: Iris dataset Python3 import plotly.express as px df = px.data.iris() fig = px.bar(df, x="sepal_width", y="sepal_length", color="species", hover_data=['petal_width'], barmode = 'group') fig.show() Output: Example 2: Tips dataset Python3 import plotly.express as px df = px.data.tips() fig = px.bar(df, x="tota_bill", y="day", color="sex", barmode = 'group') fig.show() Output: Python-Plotly Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jul, 2020" }, { "code": null, "e": 331, "s": 28, "text": "Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. " }, { "code": null, "e": 504, "s": 331, "text": "Grouping bar charts can be used to show multiple set of data items which are been compared with a single color which is used to indicate a specific series across all sets." }, { "code": null, "e": 540, "s": 504, "text": "Method 1: Using graph_objects class" }, { "code": null, "e": 549, "s": 540, "text": "Example:" }, { "code": null, "e": 557, "s": 549, "text": "Python3" }, { "code": "import plotly.graph_objects as pximport numpy # creating random data through randomint # function of numpy.random np.random.seed(42) random_x= np.random.randint(1,101,100) random_y= np.random.randint(1,101,100) x = ['A', 'B', 'C', 'D'] plot = px.Figure(data=[go.Bar( name = 'Data 1', x = x, y = [100, 200, 500, 673] ), go.Bar( name = 'Data 2', x = x, y = [56, 123, 982, 213] )]) plot.show()", "e": 1016, "s": 557, "text": null }, { "code": null, "e": 1024, "s": 1016, "text": "Output:" }, { "code": null, "e": 1054, "s": 1024, "text": "Method 2: Using express class" }, { "code": null, "e": 1078, "s": 1054, "text": "Example 1: Iris dataset" }, { "code": null, "e": 1086, "s": 1078, "text": "Python3" }, { "code": "import plotly.express as px df = px.data.iris() fig = px.bar(df, x=\"sepal_width\", y=\"sepal_length\", color=\"species\", hover_data=['petal_width'], barmode = 'group') fig.show()", "e": 1291, "s": 1086, "text": null }, { "code": null, "e": 1299, "s": 1291, "text": "Output:" }, { "code": null, "e": 1323, "s": 1299, "text": "Example 2: Tips dataset" }, { "code": null, "e": 1331, "s": 1323, "text": "Python3" }, { "code": "import plotly.express as px df = px.data.tips() fig = px.bar(df, x=\"tota_bill\", y=\"day\", color=\"sex\", barmode = 'group') fig.show()", "e": 1479, "s": 1331, "text": null }, { "code": null, "e": 1487, "s": 1479, "text": "Output:" }, { "code": null, "e": 1501, "s": 1487, "text": "Python-Plotly" }, { "code": null, "e": 1508, "s": 1501, "text": "Python" }, { "code": null, "e": 1606, "s": 1508, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1638, "s": 1606, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1665, "s": 1638, "text": "Python Classes and Objects" }, { "code": null, "e": 1686, "s": 1665, "text": "Python OOPs Concepts" }, { "code": null, "e": 1717, "s": 1686, "text": "Python | os.path.join() method" }, { "code": null, "e": 1773, "s": 1717, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1796, "s": 1773, "text": "Introduction To PYTHON" }, { "code": null, "e": 1838, "s": 1796, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1880, "s": 1838, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1919, "s": 1880, "text": "Python | datetime.timedelta() function" } ]
Java AWT | Choice Class
24 Oct, 2019 Choice class is part of Java Abstract Window Toolkit(AWT). The Choice class presents a pop- up menu for the user, the user may select an item from the popup menu. The selected item appears on the top. The Choice class inherits the Component. Constructor for the Choice class Choice() : creates an new empty choice menu . Different Methods for the Choice Class Below programs illustrate the Choice class in Java AWT: Program to create a simple choice and add elements to it:// Java Program to create a simple // choice and add elements to it .import java.awt.*;import javax.swing.*; class choice { // choice static Choice c; // frame static JFrame f; // default constructor choice() { } // Main Method public static void main(String args[]) { // create a frame f = new JFrame("choice"); // create e panel JPanel p = new JPanel(); // create a choice c = new Choice(); // add element to the list c.add("Andrew"); c.add("Arnab"); c.add("Ankit"); // add choice to panel p.add(c); // add panel to the frame f.add(p); // show the frame f.show(); f.setSize(300, 300); }}Output : // Java Program to create a simple // choice and add elements to it .import java.awt.*;import javax.swing.*; class choice { // choice static Choice c; // frame static JFrame f; // default constructor choice() { } // Main Method public static void main(String args[]) { // create a frame f = new JFrame("choice"); // create e panel JPanel p = new JPanel(); // create a choice c = new Choice(); // add element to the list c.add("Andrew"); c.add("Arnab"); c.add("Ankit"); // add choice to panel p.add(c); // add panel to the frame f.add(p); // show the frame f.show(); f.setSize(300, 300); }} Output : Program to create a simple choice and add ItemListener to it:// Java Program to create a simple// choice and add ItemListener to itimport java.awt.*;import javax.swing.*;import java.awt.event.*; class choice implements ItemListener { // choice static Choice c; // frame static JFrame f; // label static Label l; // default constructor choice() { } // Main Method public static void main(String args[]) { // create a frame f = new JFrame("choice"); // object choice ch = new choice(); // create e panel JPanel p = new JPanel(); // create a choice c = new Choice(); // add element to the list c.add("Andrew"); c.add("Arnab"); c.add("Ankit"); // add itemListener to it c.addItemListener(ch); // create a label l = new Label(); // set the label text l.setText(c.getSelectedItem() + " selected"); // add choice to panel p.add(c); p.add(l); // add panel to the frame f.add(p); // show the frame f.show(); f.setSize(300, 300); } // if an item is selected public void itemStateChanged(ItemEvent e) { l.setText(c.getSelectedItem() + " selected"); }}Output : // Java Program to create a simple// choice and add ItemListener to itimport java.awt.*;import javax.swing.*;import java.awt.event.*; class choice implements ItemListener { // choice static Choice c; // frame static JFrame f; // label static Label l; // default constructor choice() { } // Main Method public static void main(String args[]) { // create a frame f = new JFrame("choice"); // object choice ch = new choice(); // create e panel JPanel p = new JPanel(); // create a choice c = new Choice(); // add element to the list c.add("Andrew"); c.add("Arnab"); c.add("Ankit"); // add itemListener to it c.addItemListener(ch); // create a label l = new Label(); // set the label text l.setText(c.getSelectedItem() + " selected"); // add choice to panel p.add(c); p.add(l); // add panel to the frame f.add(p); // show the frame f.show(); f.setSize(300, 300); } // if an item is selected public void itemStateChanged(ItemEvent e) { l.setText(c.getSelectedItem() + " selected"); }} Output : Program to create a choice and manually add elements to it (using add(String s) function):// Java Program to create a choice and// manually add elements to it // (using add(String s) function)import java.awt.*;import javax.swing.*;import java.awt.event.*; class choice implements ItemListener, ActionListener { // choice static Choice c; // frame static JFrame f; // label static Label l; // textfield static TextField tf; // default constructor choice() { } // Main Method public static void main(String args[]) { // create a frame f = new JFrame("choice"); // object choice ch = new choice(); // create e panel JPanel p = new JPanel(); // create a choice c = new Choice(); // add element to the list c.add("Andrew"); // create a textfield tf = new TextField(7); // create a button Button b = new Button("ok"); // add actionListener b.addActionListener(ch); // add itemListener to it c.addItemListener(ch); // create a label l = new Label(); Label l1 = new Label("add names"); // set the label text l.setText(c.getSelectedItem() + " selected"); // add choice to panel p.add(c); p.add(l); p.add(l1); p.add(tf); p.add(b); // add panel to the frame f.add(p); // show the frame f.show(); f.setSize(250, 300); } // if an item is selected public void itemStateChanged(ItemEvent e) { l.setText(c.getSelectedItem() + " selected"); } // if button is pressed public void actionPerformed(ActionEvent e) { // add item to the choice c.add(tf.getText()); }}Output : Program to create a choice and manually add elements to it (using add(String s) function): // Java Program to create a choice and// manually add elements to it // (using add(String s) function)import java.awt.*;import javax.swing.*;import java.awt.event.*; class choice implements ItemListener, ActionListener { // choice static Choice c; // frame static JFrame f; // label static Label l; // textfield static TextField tf; // default constructor choice() { } // Main Method public static void main(String args[]) { // create a frame f = new JFrame("choice"); // object choice ch = new choice(); // create e panel JPanel p = new JPanel(); // create a choice c = new Choice(); // add element to the list c.add("Andrew"); // create a textfield tf = new TextField(7); // create a button Button b = new Button("ok"); // add actionListener b.addActionListener(ch); // add itemListener to it c.addItemListener(ch); // create a label l = new Label(); Label l1 = new Label("add names"); // set the label text l.setText(c.getSelectedItem() + " selected"); // add choice to panel p.add(c); p.add(l); p.add(l1); p.add(tf); p.add(b); // add panel to the frame f.add(p); // show the frame f.show(); f.setSize(250, 300); } // if an item is selected public void itemStateChanged(ItemEvent e) { l.setText(c.getSelectedItem() + " selected"); } // if button is pressed public void actionPerformed(ActionEvent e) { // add item to the choice c.add(tf.getText()); }} Output : Note: The programs might not run in an online IDE please use an offline IDE. Reference : https://docs.oracle.com/javase/7/docs/api/java/awt/Choice.html ManasChhabra2 Java-AWT Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Oct, 2019" }, { "code": null, "e": 270, "s": 28, "text": "Choice class is part of Java Abstract Window Toolkit(AWT). The Choice class presents a pop- up menu for the user, the user may select an item from the popup menu. The selected item appears on the top. The Choice class inherits the Component." }, { "code": null, "e": 303, "s": 270, "text": "Constructor for the Choice class" }, { "code": null, "e": 349, "s": 303, "text": "Choice() : creates an new empty choice menu ." }, { "code": null, "e": 388, "s": 349, "text": "Different Methods for the Choice Class" }, { "code": null, "e": 444, "s": 388, "text": "Below programs illustrate the Choice class in Java AWT:" }, { "code": null, "e": 1277, "s": 444, "text": "Program to create a simple choice and add elements to it:// Java Program to create a simple // choice and add elements to it .import java.awt.*;import javax.swing.*; class choice { // choice static Choice c; // frame static JFrame f; // default constructor choice() { } // Main Method public static void main(String args[]) { // create a frame f = new JFrame(\"choice\"); // create e panel JPanel p = new JPanel(); // create a choice c = new Choice(); // add element to the list c.add(\"Andrew\"); c.add(\"Arnab\"); c.add(\"Ankit\"); // add choice to panel p.add(c); // add panel to the frame f.add(p); // show the frame f.show(); f.setSize(300, 300); }}Output :" }, { "code": "// Java Program to create a simple // choice and add elements to it .import java.awt.*;import javax.swing.*; class choice { // choice static Choice c; // frame static JFrame f; // default constructor choice() { } // Main Method public static void main(String args[]) { // create a frame f = new JFrame(\"choice\"); // create e panel JPanel p = new JPanel(); // create a choice c = new Choice(); // add element to the list c.add(\"Andrew\"); c.add(\"Arnab\"); c.add(\"Ankit\"); // add choice to panel p.add(c); // add panel to the frame f.add(p); // show the frame f.show(); f.setSize(300, 300); }}", "e": 2045, "s": 1277, "text": null }, { "code": null, "e": 2054, "s": 2045, "text": "Output :" }, { "code": null, "e": 3382, "s": 2054, "text": "Program to create a simple choice and add ItemListener to it:// Java Program to create a simple// choice and add ItemListener to itimport java.awt.*;import javax.swing.*;import java.awt.event.*; class choice implements ItemListener { // choice static Choice c; // frame static JFrame f; // label static Label l; // default constructor choice() { } // Main Method public static void main(String args[]) { // create a frame f = new JFrame(\"choice\"); // object choice ch = new choice(); // create e panel JPanel p = new JPanel(); // create a choice c = new Choice(); // add element to the list c.add(\"Andrew\"); c.add(\"Arnab\"); c.add(\"Ankit\"); // add itemListener to it c.addItemListener(ch); // create a label l = new Label(); // set the label text l.setText(c.getSelectedItem() + \" selected\"); // add choice to panel p.add(c); p.add(l); // add panel to the frame f.add(p); // show the frame f.show(); f.setSize(300, 300); } // if an item is selected public void itemStateChanged(ItemEvent e) { l.setText(c.getSelectedItem() + \" selected\"); }}Output :" }, { "code": "// Java Program to create a simple// choice and add ItemListener to itimport java.awt.*;import javax.swing.*;import java.awt.event.*; class choice implements ItemListener { // choice static Choice c; // frame static JFrame f; // label static Label l; // default constructor choice() { } // Main Method public static void main(String args[]) { // create a frame f = new JFrame(\"choice\"); // object choice ch = new choice(); // create e panel JPanel p = new JPanel(); // create a choice c = new Choice(); // add element to the list c.add(\"Andrew\"); c.add(\"Arnab\"); c.add(\"Ankit\"); // add itemListener to it c.addItemListener(ch); // create a label l = new Label(); // set the label text l.setText(c.getSelectedItem() + \" selected\"); // add choice to panel p.add(c); p.add(l); // add panel to the frame f.add(p); // show the frame f.show(); f.setSize(300, 300); } // if an item is selected public void itemStateChanged(ItemEvent e) { l.setText(c.getSelectedItem() + \" selected\"); }}", "e": 4641, "s": 3382, "text": null }, { "code": null, "e": 4650, "s": 4641, "text": "Output :" }, { "code": null, "e": 6479, "s": 4650, "text": "Program to create a choice and manually add elements to it (using add(String s) function):// Java Program to create a choice and// manually add elements to it // (using add(String s) function)import java.awt.*;import javax.swing.*;import java.awt.event.*; class choice implements ItemListener, ActionListener { // choice static Choice c; // frame static JFrame f; // label static Label l; // textfield static TextField tf; // default constructor choice() { } // Main Method public static void main(String args[]) { // create a frame f = new JFrame(\"choice\"); // object choice ch = new choice(); // create e panel JPanel p = new JPanel(); // create a choice c = new Choice(); // add element to the list c.add(\"Andrew\"); // create a textfield tf = new TextField(7); // create a button Button b = new Button(\"ok\"); // add actionListener b.addActionListener(ch); // add itemListener to it c.addItemListener(ch); // create a label l = new Label(); Label l1 = new Label(\"add names\"); // set the label text l.setText(c.getSelectedItem() + \" selected\"); // add choice to panel p.add(c); p.add(l); p.add(l1); p.add(tf); p.add(b); // add panel to the frame f.add(p); // show the frame f.show(); f.setSize(250, 300); } // if an item is selected public void itemStateChanged(ItemEvent e) { l.setText(c.getSelectedItem() + \" selected\"); } // if button is pressed public void actionPerformed(ActionEvent e) { // add item to the choice c.add(tf.getText()); }}Output :" }, { "code": null, "e": 6570, "s": 6479, "text": "Program to create a choice and manually add elements to it (using add(String s) function):" }, { "code": "// Java Program to create a choice and// manually add elements to it // (using add(String s) function)import java.awt.*;import javax.swing.*;import java.awt.event.*; class choice implements ItemListener, ActionListener { // choice static Choice c; // frame static JFrame f; // label static Label l; // textfield static TextField tf; // default constructor choice() { } // Main Method public static void main(String args[]) { // create a frame f = new JFrame(\"choice\"); // object choice ch = new choice(); // create e panel JPanel p = new JPanel(); // create a choice c = new Choice(); // add element to the list c.add(\"Andrew\"); // create a textfield tf = new TextField(7); // create a button Button b = new Button(\"ok\"); // add actionListener b.addActionListener(ch); // add itemListener to it c.addItemListener(ch); // create a label l = new Label(); Label l1 = new Label(\"add names\"); // set the label text l.setText(c.getSelectedItem() + \" selected\"); // add choice to panel p.add(c); p.add(l); p.add(l1); p.add(tf); p.add(b); // add panel to the frame f.add(p); // show the frame f.show(); f.setSize(250, 300); } // if an item is selected public void itemStateChanged(ItemEvent e) { l.setText(c.getSelectedItem() + \" selected\"); } // if button is pressed public void actionPerformed(ActionEvent e) { // add item to the choice c.add(tf.getText()); }}", "e": 8301, "s": 6570, "text": null }, { "code": null, "e": 8310, "s": 8301, "text": "Output :" }, { "code": null, "e": 8387, "s": 8310, "text": "Note: The programs might not run in an online IDE please use an offline IDE." }, { "code": null, "e": 8462, "s": 8387, "text": "Reference : https://docs.oracle.com/javase/7/docs/api/java/awt/Choice.html" }, { "code": null, "e": 8476, "s": 8462, "text": "ManasChhabra2" }, { "code": null, "e": 8485, "s": 8476, "text": "Java-AWT" }, { "code": null, "e": 8490, "s": 8485, "text": "Java" }, { "code": null, "e": 8504, "s": 8490, "text": "Java Programs" }, { "code": null, "e": 8509, "s": 8504, "text": "Java" }, { "code": null, "e": 8607, "s": 8509, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8622, "s": 8607, "text": "Stream In Java" }, { "code": null, "e": 8643, "s": 8622, "text": "Introduction to Java" }, { "code": null, "e": 8664, "s": 8643, "text": "Constructors in Java" }, { "code": null, "e": 8683, "s": 8664, "text": "Exceptions in Java" }, { "code": null, "e": 8700, "s": 8683, "text": "Generics in Java" }, { "code": null, "e": 8726, "s": 8700, "text": "Java Programming Examples" }, { "code": null, "e": 8760, "s": 8726, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 8807, "s": 8760, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 8845, "s": 8807, "text": "Factory method design pattern in Java" } ]
Java - String copyValueOf() Method
This method returns a String that represents the character sequence in the array specified. Here is the syntax of this method − public static String copyValueOf(char[] data) Here is the detail of parameters − data − the character array. data − the character array. This method returns a String that contains the characters of the character array. This method returns a String that contains the characters of the character array. public class Test { public static void main(String args[]) { char[] Str1 = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'}; String Str2 = ""; Str2 = Str2.copyValueOf( Str1 ); System.out.println("Returned String: " + Str2); } } This will produce the following result − Returned String: hello world
[ { "code": null, "e": 2603, "s": 2511, "text": "This method returns a String that represents the character sequence in the array specified." }, { "code": null, "e": 2639, "s": 2603, "text": "Here is the syntax of this method −" }, { "code": null, "e": 2686, "s": 2639, "text": "public static String copyValueOf(char[] data)\n" }, { "code": null, "e": 2721, "s": 2686, "text": "Here is the detail of parameters −" }, { "code": null, "e": 2749, "s": 2721, "text": "data − the character array." }, { "code": null, "e": 2777, "s": 2749, "text": "data − the character array." }, { "code": null, "e": 2859, "s": 2777, "text": "This method returns a String that contains the characters of the character array." }, { "code": null, "e": 2941, "s": 2859, "text": "This method returns a String that contains the characters of the character array." }, { "code": null, "e": 3207, "s": 2941, "text": "public class Test {\n\n public static void main(String args[]) {\n char[] Str1 = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};\n String Str2 = \"\";\n Str2 = Str2.copyValueOf( Str1 );\n System.out.println(\"Returned String: \" + Str2);\n }\n}" }, { "code": null, "e": 3248, "s": 3207, "text": "This will produce the following result −" } ]
Survival Analysis in R
13 Dec, 2021 Survival analysis in R Programming Language deals with the prediction of events at a specified time. It deals with the occurrence of an interesting event within a specified time and failure of it produces censored observations i.e incomplete observations. Biological sciences are the most important application of survival analysis in which we can predict the time for organisms eg. when they will multiply to sizes etc. There are two methods that can be used to perform survival analysis in R programming language: Kaplan-Meier method Cox Proportional hazard model The Kaplan-Meier method is used in survival distribution using the Kaplan-Meier estimator for truncated or censored data. It’s a non-parametric statistic that allows us to estimate the survival function and thus not based on underlying probability distribution. The Kaplan–Meier estimates are based on the number of patients (each patient as a row of data) from the total number of patients who survive for a certain time after treatment. (which is the event). We represent the Kaplan–Meier function by the formula: Here S(t) represents the probability that life is longer than t with ti(At least one event happened), di represents the number of events(e.g. deaths) that happened in time ti and ni represents the number of individuals who survived up to time ti. Example: We will use the Survival package for the analysis. Using Lung dataset preloaded in survival package which contains data of 228 patients with advanced lung cancer from North Central cancer treatment group based on 10 features. The dataset contains missing values so, missing value treatment is presumed to be done at your side before the building model. R # Installing packageinstall.packages("survival") # Loading packagelibrary(survival) # Dataset information?lung # Fitting the survival modelSurvival_Function = survfit(Surv(lung$time, lung$status == 2)~1)Survival_Function # Plotting the functionplot(Survival_Function) Here, we are interested in “time” and “status” as they play an important role in the analysis. Time represents the survival time of patients. Since patients survive, we will consider their status as dead or non-dead(censored). The Surv() function takes two times and status as input and creates an object which serves as the input of survfir() function. We pass ~1 in survfit() function to ensure that we are telling the function to fit the model on basis of the survival object and have an interrupt. survfit() creates survival curves and prints the number of values, number of events(people suffering from cancer), the median time and 95% confidence interval. The plot gives the following output: Here, the x-axis specifies “Number of days” and the y-axis specifies the “probability of survival“. The dashed lines are upper confidence interval and lower confidence interval. We also have the confidence interval which shows the margin of error expected i.e In days of surviving 200 days, upper confidence interval reaches 0.76 or 76% and then goes down to 0.60 or 60%. It is a regression modeling that measures the instantaneous risk of deaths and is bit more difficult to illustrate than the Kaplan-Meier estimator. It consists of hazard function h(t) which describes the probability of event or hazard h(e.g. survival) up to a particular time t. Hazard function considers covariates(independent variables in regression) to compare the survival of patient groups. It does not assume an underlying probability distribution but it assumes that the hazards of the patient groups we compare are constant over time and because of this it is known as “Proportional hazard model“. Example: We will use the Survival package for the analysis. Using Lung dataset preloaded in survival package which contains data of 228 patients with advanced lung cancer from North Central cancer treatment group based on 10 features. The dataset contains missing values so, missing value treatment is presumed to be done at your side before the building model. We will be using the cox proportional hazard function coxph() to build the model. R # Installing packageinstall.packages("survival") # Loading packagelibrary(survival) # Dataset information?lung # Fitting the Cox modelCox_mod <- coxph(Surv(lung$time, lung$status == 2)~., data = lung) # Summarizing the modelsummary(Cox_mod) # Fitting survfit()Cox <- survfit(Cox_mod) # Plotting the functionplot(Cox) Here, we are interested in “time” and “status” as they play an important role in the analysis. Time represents the survival time of patients. Since patients survive, we will consider their status as dead or non-dead(censored). The Surv() function takes two times and status as input and creates an object which serves as the input of survfir() function. We pass ~1 in survfit() function to ensure that we are telling the function to fit the model on basis of the survival object and have an interrupt. The Cox_mod output is similar to the regression model. There are some important features like age, sex, ph.ecog and wt. loss. The plot gives the following output: Here, the x-axis specifies “Number of days” and the y-axis specifies “probability of survival“. The dashed lines are upper confidence interval and lower confidence interval. In comparison with the Kaplan-Meier plot, the Cox plot is high for initial values and lower for higher values because of more variables in the Cox plot. We also have the confidence interval which shows the margin of error expected i.e In days of surviving 200 days, the upper confidence interval reaches 0.82 or 82% and then goes down to 0.70 or 70%. Note: Cox model serves better results than Kaplan-Meier as it is most volatile with data and features. Cox model is also higher for lower values and vice-versa i.e drops down sharply when the time increases. kumar_satyam avtarkumar719 Picked statistical-algorithms R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Dec, 2021" }, { "code": null, "e": 309, "s": 52, "text": "Survival analysis in R Programming Language deals with the prediction of events at a specified time. It deals with the occurrence of an interesting event within a specified time and failure of it produces censored observations i.e incomplete observations. " }, { "code": null, "e": 474, "s": 309, "text": "Biological sciences are the most important application of survival analysis in which we can predict the time for organisms eg. when they will multiply to sizes etc." }, { "code": null, "e": 570, "s": 474, "text": "There are two methods that can be used to perform survival analysis in R programming language: " }, { "code": null, "e": 590, "s": 570, "text": "Kaplan-Meier method" }, { "code": null, "e": 620, "s": 590, "text": "Cox Proportional hazard model" }, { "code": null, "e": 1082, "s": 620, "text": "The Kaplan-Meier method is used in survival distribution using the Kaplan-Meier estimator for truncated or censored data. It’s a non-parametric statistic that allows us to estimate the survival function and thus not based on underlying probability distribution. The Kaplan–Meier estimates are based on the number of patients (each patient as a row of data) from the total number of patients who survive for a certain time after treatment. (which is the event). " }, { "code": null, "e": 1138, "s": 1082, "text": "We represent the Kaplan–Meier function by the formula: " }, { "code": null, "e": 1385, "s": 1138, "text": "Here S(t) represents the probability that life is longer than t with ti(At least one event happened), di represents the number of events(e.g. deaths) that happened in time ti and ni represents the number of individuals who survived up to time ti." }, { "code": null, "e": 1395, "s": 1385, "text": "Example: " }, { "code": null, "e": 1749, "s": 1395, "text": "We will use the Survival package for the analysis. Using Lung dataset preloaded in survival package which contains data of 228 patients with advanced lung cancer from North Central cancer treatment group based on 10 features. The dataset contains missing values so, missing value treatment is presumed to be done at your side before the building model. " }, { "code": null, "e": 1751, "s": 1749, "text": "R" }, { "code": "# Installing packageinstall.packages(\"survival\") # Loading packagelibrary(survival) # Dataset information?lung # Fitting the survival modelSurvival_Function = survfit(Surv(lung$time, lung$status == 2)~1)Survival_Function # Plotting the functionplot(Survival_Function)", "e": 2051, "s": 1751, "text": null }, { "code": null, "e": 2279, "s": 2051, "text": "Here, we are interested in “time” and “status” as they play an important role in the analysis. Time represents the survival time of patients. Since patients survive, we will consider their status as dead or non-dead(censored). " }, { "code": null, "e": 2554, "s": 2279, "text": "The Surv() function takes two times and status as input and creates an object which serves as the input of survfir() function. We pass ~1 in survfit() function to ensure that we are telling the function to fit the model on basis of the survival object and have an interrupt." }, { "code": null, "e": 2752, "s": 2554, "text": "survfit() creates survival curves and prints the number of values, number of events(people suffering from cancer), the median time and 95% confidence interval. The plot gives the following output: " }, { "code": null, "e": 2931, "s": 2752, "text": "Here, the x-axis specifies “Number of days” and the y-axis specifies the “probability of survival“. The dashed lines are upper confidence interval and lower confidence interval. " }, { "code": null, "e": 3126, "s": 2931, "text": "We also have the confidence interval which shows the margin of error expected i.e In days of surviving 200 days, upper confidence interval reaches 0.76 or 76% and then goes down to 0.60 or 60%. " }, { "code": null, "e": 3733, "s": 3126, "text": "It is a regression modeling that measures the instantaneous risk of deaths and is bit more difficult to illustrate than the Kaplan-Meier estimator. It consists of hazard function h(t) which describes the probability of event or hazard h(e.g. survival) up to a particular time t. Hazard function considers covariates(independent variables in regression) to compare the survival of patient groups. It does not assume an underlying probability distribution but it assumes that the hazards of the patient groups we compare are constant over time and because of this it is known as “Proportional hazard model“. " }, { "code": null, "e": 3743, "s": 3733, "text": "Example: " }, { "code": null, "e": 4179, "s": 3743, "text": "We will use the Survival package for the analysis. Using Lung dataset preloaded in survival package which contains data of 228 patients with advanced lung cancer from North Central cancer treatment group based on 10 features. The dataset contains missing values so, missing value treatment is presumed to be done at your side before the building model. We will be using the cox proportional hazard function coxph() to build the model. " }, { "code": null, "e": 4181, "s": 4179, "text": "R" }, { "code": "# Installing packageinstall.packages(\"survival\") # Loading packagelibrary(survival) # Dataset information?lung # Fitting the Cox modelCox_mod <- coxph(Surv(lung$time, lung$status == 2)~., data = lung) # Summarizing the modelsummary(Cox_mod) # Fitting survfit()Cox <- survfit(Cox_mod) # Plotting the functionplot(Cox)", "e": 4519, "s": 4181, "text": null }, { "code": null, "e": 4747, "s": 4519, "text": "Here, we are interested in “time” and “status” as they play an important role in the analysis. Time represents the survival time of patients. Since patients survive, we will consider their status as dead or non-dead(censored). " }, { "code": null, "e": 5022, "s": 4747, "text": "The Surv() function takes two times and status as input and creates an object which serves as the input of survfir() function. We pass ~1 in survfit() function to ensure that we are telling the function to fit the model on basis of the survival object and have an interrupt." }, { "code": null, "e": 5186, "s": 5022, "text": "The Cox_mod output is similar to the regression model. There are some important features like age, sex, ph.ecog and wt. loss. The plot gives the following output: " }, { "code": null, "e": 5513, "s": 5186, "text": "Here, the x-axis specifies “Number of days” and the y-axis specifies “probability of survival“. The dashed lines are upper confidence interval and lower confidence interval. In comparison with the Kaplan-Meier plot, the Cox plot is high for initial values and lower for higher values because of more variables in the Cox plot." }, { "code": null, "e": 5711, "s": 5513, "text": "We also have the confidence interval which shows the margin of error expected i.e In days of surviving 200 days, the upper confidence interval reaches 0.82 or 82% and then goes down to 0.70 or 70%." }, { "code": null, "e": 5919, "s": 5711, "text": "Note: Cox model serves better results than Kaplan-Meier as it is most volatile with data and features. Cox model is also higher for lower values and vice-versa i.e drops down sharply when the time increases." }, { "code": null, "e": 5932, "s": 5919, "text": "kumar_satyam" }, { "code": null, "e": 5946, "s": 5932, "text": "avtarkumar719" }, { "code": null, "e": 5953, "s": 5946, "text": "Picked" }, { "code": null, "e": 5976, "s": 5953, "text": "statistical-algorithms" }, { "code": null, "e": 5987, "s": 5976, "text": "R Language" } ]
Underscore.js _.findIndex() Function
24 Nov, 2021 _.findIndex() function: It is used to find the index of an element which is passed in the second parameter. We can use this for any kind of array like number array, string array, character array etc. If we do not know what all elements are present in the array but we want to find out whether a single element is present or not then we use this function. Syntax: _.findIndex(array, predicate, [context]) Parameters:It takes three arguments: The array The predicate The context (optional) Return value:It returns the index at which the element to be searched is present.Examples: Passing a list of only one key and it’s value to _.findIndex() function:The ._findIndex() function takes the element from the list one by one and compares it with the element passed as the second parameter. If they match then it returns it’s index otherwise it just skips this element and goes on to the next. This process goes on till the match is not found or the list finishes. If the list finishes without finding the element passed then the result is -1.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> console.log(_.findIndex([{rollNo:1}, {rollNo:2}, {rollNo:3}], { rollNo : 1})); </script></body> </html>Output:Passing a full structure to the _.findIndex() function:We can even pass a structure with many properties to the _.findIndex() function and it will work in the same way. For this we also need to mention which property need to be compared. Like in the below example, the array has 3 properties, the is, name, last. Out of these we have mentioned that we want to compare and find out the index of the element with first name as ‘Teddy’.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> var users = [{'id': 1, 'name': 'Bobby', 'last': 'Stark'}, {'id': 2, 'name': 'Teddy', 'last': 'Lime'}, {'id': 3, 'name': 'Franky', 'last': 'Frail'}, {'id': 4, 'name': 'Teddy', 'last': 'Frail'}]; console.log(_.findIndex(users, { name: 'Teddy'})); </script></body> </html>Output:Comparing the property with number:In this we have passed the same structure as the above but we have used the property to match and compare as ‘id’ which contains the numbers. It will work in the same way and compare all the ids until we get id as ‘3’ which is mentioned in the second parameter.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> var users = [{'id': 1, 'name': 'Bobby', 'last': 'Stark'}, {'id': 2, 'name': 'Teddy', 'last': 'Lime'}, {'id': 3, 'name': 'Franky', 'last': 'Frail'}, {'id': 4, 'name': 'Teddy', 'last': 'Frail'}, {'id': 3, 'name': 'Tinu', 'last': 'Thauus'}]; console.log(_.findIndex(users, { id : 3})); </script></body> </html>Output:Passing an element in the second parameter which is not present in the list:If we pass an element which the list does not contain then the result will be a negative number -1. There will be no errors. This is the case where the list ends but the element is not present in it.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> var users = [{'id': 1, 'name': 'Bobby', 'last': 'Stark'}, {'id': 2, 'name': 'Teddy', 'last': 'Lime'}, {'id': 3, 'name': 'Franky', 'last': 'Frail'}, {'id': 4, 'name': 'Teddy', 'last': 'Frail'}, {'id': 3, 'name': 'Tinu', 'last': 'Thauus'}]; console.log(_.findIndex(users, { id : 100})); </script></body> </html>Output: Passing a list of only one key and it’s value to _.findIndex() function:The ._findIndex() function takes the element from the list one by one and compares it with the element passed as the second parameter. If they match then it returns it’s index otherwise it just skips this element and goes on to the next. This process goes on till the match is not found or the list finishes. If the list finishes without finding the element passed then the result is -1.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> console.log(_.findIndex([{rollNo:1}, {rollNo:2}, {rollNo:3}], { rollNo : 1})); </script></body> </html>Output: <!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> console.log(_.findIndex([{rollNo:1}, {rollNo:2}, {rollNo:3}], { rollNo : 1})); </script></body> </html> Output: Passing a full structure to the _.findIndex() function:We can even pass a structure with many properties to the _.findIndex() function and it will work in the same way. For this we also need to mention which property need to be compared. Like in the below example, the array has 3 properties, the is, name, last. Out of these we have mentioned that we want to compare and find out the index of the element with first name as ‘Teddy’.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> var users = [{'id': 1, 'name': 'Bobby', 'last': 'Stark'}, {'id': 2, 'name': 'Teddy', 'last': 'Lime'}, {'id': 3, 'name': 'Franky', 'last': 'Frail'}, {'id': 4, 'name': 'Teddy', 'last': 'Frail'}]; console.log(_.findIndex(users, { name: 'Teddy'})); </script></body> </html>Output: <!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> var users = [{'id': 1, 'name': 'Bobby', 'last': 'Stark'}, {'id': 2, 'name': 'Teddy', 'last': 'Lime'}, {'id': 3, 'name': 'Franky', 'last': 'Frail'}, {'id': 4, 'name': 'Teddy', 'last': 'Frail'}]; console.log(_.findIndex(users, { name: 'Teddy'})); </script></body> </html> Output: Comparing the property with number:In this we have passed the same structure as the above but we have used the property to match and compare as ‘id’ which contains the numbers. It will work in the same way and compare all the ids until we get id as ‘3’ which is mentioned in the second parameter.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> var users = [{'id': 1, 'name': 'Bobby', 'last': 'Stark'}, {'id': 2, 'name': 'Teddy', 'last': 'Lime'}, {'id': 3, 'name': 'Franky', 'last': 'Frail'}, {'id': 4, 'name': 'Teddy', 'last': 'Frail'}, {'id': 3, 'name': 'Tinu', 'last': 'Thauus'}]; console.log(_.findIndex(users, { id : 3})); </script></body> </html>Output: <!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> var users = [{'id': 1, 'name': 'Bobby', 'last': 'Stark'}, {'id': 2, 'name': 'Teddy', 'last': 'Lime'}, {'id': 3, 'name': 'Franky', 'last': 'Frail'}, {'id': 4, 'name': 'Teddy', 'last': 'Frail'}, {'id': 3, 'name': 'Tinu', 'last': 'Thauus'}]; console.log(_.findIndex(users, { id : 3})); </script></body> </html> Output: Passing an element in the second parameter which is not present in the list:If we pass an element which the list does not contain then the result will be a negative number -1. There will be no errors. This is the case where the list ends but the element is not present in it.<!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> var users = [{'id': 1, 'name': 'Bobby', 'last': 'Stark'}, {'id': 2, 'name': 'Teddy', 'last': 'Lime'}, {'id': 3, 'name': 'Franky', 'last': 'Frail'}, {'id': 4, 'name': 'Teddy', 'last': 'Frail'}, {'id': 3, 'name': 'Tinu', 'last': 'Thauus'}]; console.log(_.findIndex(users, { id : 100})); </script></body> </html>Output: <!-- Write HTML code here --><html> <head> <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script></head> <body> <script type="text/javascript"> var users = [{'id': 1, 'name': 'Bobby', 'last': 'Stark'}, {'id': 2, 'name': 'Teddy', 'last': 'Lime'}, {'id': 3, 'name': 'Franky', 'last': 'Frail'}, {'id': 4, 'name': 'Teddy', 'last': 'Frail'}, {'id': 3, 'name': 'Tinu', 'last': 'Thauus'}]; console.log(_.findIndex(users, { id : 100})); </script></body> </html> Output: NOTE:These commands will not work in Google console or in firefox as for these additional files need to be added which they didn’t have added.So, add the given links to your HTML file and then run them.The links are as follows: <!-- Write HTML code here --><script type="text/javascript" src ="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script> An example is shown below: shubham_singh JavaScript - Underscore.js JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Nov, 2021" }, { "code": null, "e": 52, "s": 28, "text": "_.findIndex() function:" }, { "code": null, "e": 136, "s": 52, "text": "It is used to find the index of an element which is passed in the second parameter." }, { "code": null, "e": 228, "s": 136, "text": "We can use this for any kind of array like number array, string array, character array etc." }, { "code": null, "e": 383, "s": 228, "text": "If we do not know what all elements are present in the array but we want to find out whether a single element is present or not then we use this function." }, { "code": null, "e": 391, "s": 383, "text": "Syntax:" }, { "code": null, "e": 432, "s": 391, "text": "_.findIndex(array, predicate, [context])" }, { "code": null, "e": 469, "s": 432, "text": "Parameters:It takes three arguments:" }, { "code": null, "e": 479, "s": 469, "text": "The array" }, { "code": null, "e": 493, "s": 479, "text": "The predicate" }, { "code": null, "e": 516, "s": 493, "text": "The context (optional)" }, { "code": null, "e": 607, "s": 516, "text": "Return value:It returns the index at which the element to be searched is present.Examples:" }, { "code": null, "e": 4122, "s": 607, "text": "Passing a list of only one key and it’s value to _.findIndex() function:The ._findIndex() function takes the element from the list one by one and compares it with the element passed as the second parameter. If they match then it returns it’s index otherwise it just skips this element and goes on to the next. This process goes on till the match is not found or the list finishes. If the list finishes without finding the element passed then the result is -1.<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> console.log(_.findIndex([{rollNo:1}, {rollNo:2}, {rollNo:3}], { rollNo : 1})); </script></body> </html>Output:Passing a full structure to the _.findIndex() function:We can even pass a structure with many properties to the _.findIndex() function and it will work in the same way. For this we also need to mention which property need to be compared. Like in the below example, the array has 3 properties, the is, name, last. Out of these we have mentioned that we want to compare and find out the index of the element with first name as ‘Teddy’.<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> var users = [{'id': 1, 'name': 'Bobby', 'last': 'Stark'}, {'id': 2, 'name': 'Teddy', 'last': 'Lime'}, {'id': 3, 'name': 'Franky', 'last': 'Frail'}, {'id': 4, 'name': 'Teddy', 'last': 'Frail'}]; console.log(_.findIndex(users, { name: 'Teddy'})); </script></body> </html>Output:Comparing the property with number:In this we have passed the same structure as the above but we have used the property to match and compare as ‘id’ which contains the numbers. It will work in the same way and compare all the ids until we get id as ‘3’ which is mentioned in the second parameter.<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> var users = [{'id': 1, 'name': 'Bobby', 'last': 'Stark'}, {'id': 2, 'name': 'Teddy', 'last': 'Lime'}, {'id': 3, 'name': 'Franky', 'last': 'Frail'}, {'id': 4, 'name': 'Teddy', 'last': 'Frail'}, {'id': 3, 'name': 'Tinu', 'last': 'Thauus'}]; console.log(_.findIndex(users, { id : 3})); </script></body> </html>Output:Passing an element in the second parameter which is not present in the list:If we pass an element which the list does not contain then the result will be a negative number -1. There will be no errors. This is the case where the list ends but the element is not present in it.<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> var users = [{'id': 1, 'name': 'Bobby', 'last': 'Stark'}, {'id': 2, 'name': 'Teddy', 'last': 'Lime'}, {'id': 3, 'name': 'Franky', 'last': 'Frail'}, {'id': 4, 'name': 'Teddy', 'last': 'Frail'}, {'id': 3, 'name': 'Tinu', 'last': 'Thauus'}]; console.log(_.findIndex(users, { id : 100})); </script></body> </html>Output:" }, { "code": null, "e": 4917, "s": 4122, "text": "Passing a list of only one key and it’s value to _.findIndex() function:The ._findIndex() function takes the element from the list one by one and compares it with the element passed as the second parameter. If they match then it returns it’s index otherwise it just skips this element and goes on to the next. This process goes on till the match is not found or the list finishes. If the list finishes without finding the element passed then the result is -1.<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> console.log(_.findIndex([{rollNo:1}, {rollNo:2}, {rollNo:3}], { rollNo : 1})); </script></body> </html>Output:" }, { "code": "<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> console.log(_.findIndex([{rollNo:1}, {rollNo:2}, {rollNo:3}], { rollNo : 1})); </script></body> </html>", "e": 5246, "s": 4917, "text": null }, { "code": null, "e": 5254, "s": 5246, "text": "Output:" }, { "code": null, "e": 6226, "s": 5254, "text": "Passing a full structure to the _.findIndex() function:We can even pass a structure with many properties to the _.findIndex() function and it will work in the same way. For this we also need to mention which property need to be compared. Like in the below example, the array has 3 properties, the is, name, last. Out of these we have mentioned that we want to compare and find out the index of the element with first name as ‘Teddy’.<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> var users = [{'id': 1, 'name': 'Bobby', 'last': 'Stark'}, {'id': 2, 'name': 'Teddy', 'last': 'Lime'}, {'id': 3, 'name': 'Franky', 'last': 'Frail'}, {'id': 4, 'name': 'Teddy', 'last': 'Frail'}]; console.log(_.findIndex(users, { name: 'Teddy'})); </script></body> </html>Output:" }, { "code": "<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> var users = [{'id': 1, 'name': 'Bobby', 'last': 'Stark'}, {'id': 2, 'name': 'Teddy', 'last': 'Lime'}, {'id': 3, 'name': 'Franky', 'last': 'Frail'}, {'id': 4, 'name': 'Teddy', 'last': 'Frail'}]; console.log(_.findIndex(users, { name: 'Teddy'})); </script></body> </html>", "e": 6758, "s": 6226, "text": null }, { "code": null, "e": 6766, "s": 6758, "text": "Output:" }, { "code": null, "e": 7651, "s": 6766, "text": "Comparing the property with number:In this we have passed the same structure as the above but we have used the property to match and compare as ‘id’ which contains the numbers. It will work in the same way and compare all the ids until we get id as ‘3’ which is mentioned in the second parameter.<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> var users = [{'id': 1, 'name': 'Bobby', 'last': 'Stark'}, {'id': 2, 'name': 'Teddy', 'last': 'Lime'}, {'id': 3, 'name': 'Franky', 'last': 'Frail'}, {'id': 4, 'name': 'Teddy', 'last': 'Frail'}, {'id': 3, 'name': 'Tinu', 'last': 'Thauus'}]; console.log(_.findIndex(users, { id : 3})); </script></body> </html>Output:" }, { "code": "<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> var users = [{'id': 1, 'name': 'Bobby', 'last': 'Stark'}, {'id': 2, 'name': 'Teddy', 'last': 'Lime'}, {'id': 3, 'name': 'Franky', 'last': 'Frail'}, {'id': 4, 'name': 'Teddy', 'last': 'Frail'}, {'id': 3, 'name': 'Tinu', 'last': 'Thauus'}]; console.log(_.findIndex(users, { id : 3})); </script></body> </html>", "e": 8233, "s": 7651, "text": null }, { "code": null, "e": 8241, "s": 8233, "text": "Output:" }, { "code": null, "e": 9107, "s": 8241, "text": "Passing an element in the second parameter which is not present in the list:If we pass an element which the list does not contain then the result will be a negative number -1. There will be no errors. This is the case where the list ends but the element is not present in it.<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> var users = [{'id': 1, 'name': 'Bobby', 'last': 'Stark'}, {'id': 2, 'name': 'Teddy', 'last': 'Lime'}, {'id': 3, 'name': 'Franky', 'last': 'Frail'}, {'id': 4, 'name': 'Teddy', 'last': 'Frail'}, {'id': 3, 'name': 'Tinu', 'last': 'Thauus'}]; console.log(_.findIndex(users, { id : 100})); </script></body> </html>Output:" }, { "code": "<!-- Write HTML code here --><html> <head> <script src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script></head> <body> <script type=\"text/javascript\"> var users = [{'id': 1, 'name': 'Bobby', 'last': 'Stark'}, {'id': 2, 'name': 'Teddy', 'last': 'Lime'}, {'id': 3, 'name': 'Franky', 'last': 'Frail'}, {'id': 4, 'name': 'Teddy', 'last': 'Frail'}, {'id': 3, 'name': 'Tinu', 'last': 'Thauus'}]; console.log(_.findIndex(users, { id : 100})); </script></body> </html>", "e": 9691, "s": 9107, "text": null }, { "code": null, "e": 9699, "s": 9691, "text": "Output:" }, { "code": null, "e": 9927, "s": 9699, "text": "NOTE:These commands will not work in Google console or in firefox as for these additional files need to be added which they didn’t have added.So, add the given links to your HTML file and then run them.The links are as follows:" }, { "code": "<!-- Write HTML code here --><script type=\"text/javascript\" src =\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"></script>", "e": 10081, "s": 9927, "text": null }, { "code": null, "e": 10108, "s": 10081, "text": "An example is shown below:" }, { "code": null, "e": 10122, "s": 10108, "text": "shubham_singh" }, { "code": null, "e": 10149, "s": 10122, "text": "JavaScript - Underscore.js" }, { "code": null, "e": 10160, "s": 10149, "text": "JavaScript" } ]
How to Install Lazy Script in Kali Linux?
05 Oct, 2021 Kali Linux is one of the most advanced hacking OS systems from Linux family. Kali Linux is filled with many hacking tools and supporting learners and hackers worldwide. There are many versions of Kali Linux which provides a good user interface and desired environment.The Lazy Script is designed to help many users to save time and work. The script can install many hacking tools easily with just a few inputs, saving a lot of time of the users. The user is helped in the way all the manual tasks are avoided. To Install the Lazy Script you will first need Kali Linux system which you can download from its official website. Step 1: Copy the github repository from the following Link. Before doing everything note that it is all about Linux and not windows so please make sure you are doing everything in Kali Linux itself. Step 2: Open the terminal and type the following commands: cd Desktop git clone https://github.com/arismelachroinos/lscript.git We used cd Desktop for simplicity and to find the folder easily. After cloning the script change your directory to lscript by using the following command cd lscript Step 3: After that check for the installer .sh file and follow the command: ./install.sh If the terminal shows permission denied, then it is because the file is not given executable permission. To give it permission type the following command chmod +x install.sh Again type the command ./install.sh and this time you have prior permissions to do that. Step 4: After running the script you will be asked to accept terms and conditions, type YES to accept. Then you will be asked to enter network interfaces that the system use. For the first line type eth0mon and for second line type eth0. The Script looks like this after installing. Use the script and enjoy many tools with one choice, no wasting of time in searching and installing, make your life easier.A sample working: Madhusudan_Soni how-to-install How To Installation Guide Linux-Unix TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Java Tutorial How to filter object array based on attributes? How to Align Text in HTML? How to Install FFmpeg on Windows? How to Set Git Username and Password in GitBash? Installation of Node.js on Linux How to Install FFmpeg on Windows? How to Install Anaconda on Windows? Installation of Node.js on Windows How to Install and Run Apache Kafka on Windows?
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Oct, 2021" }, { "code": null, "e": 538, "s": 28, "text": "Kali Linux is one of the most advanced hacking OS systems from Linux family. Kali Linux is filled with many hacking tools and supporting learners and hackers worldwide. There are many versions of Kali Linux which provides a good user interface and desired environment.The Lazy Script is designed to help many users to save time and work. The script can install many hacking tools easily with just a few inputs, saving a lot of time of the users. The user is helped in the way all the manual tasks are avoided." }, { "code": null, "e": 653, "s": 538, "text": "To Install the Lazy Script you will first need Kali Linux system which you can download from its official website." }, { "code": null, "e": 852, "s": 653, "text": "Step 1: Copy the github repository from the following Link. Before doing everything note that it is all about Linux and not windows so please make sure you are doing everything in Kali Linux itself." }, { "code": null, "e": 911, "s": 852, "text": "Step 2: Open the terminal and type the following commands:" }, { "code": null, "e": 981, "s": 911, "text": "cd Desktop\ngit clone https://github.com/arismelachroinos/lscript.git\n" }, { "code": null, "e": 1135, "s": 981, "text": "We used cd Desktop for simplicity and to find the folder easily. After cloning the script change your directory to lscript by using the following command" }, { "code": null, "e": 1146, "s": 1135, "text": "cd lscript" }, { "code": null, "e": 1222, "s": 1146, "text": "Step 3: After that check for the installer .sh file and follow the command:" }, { "code": null, "e": 1235, "s": 1222, "text": "./install.sh" }, { "code": null, "e": 1389, "s": 1235, "text": "If the terminal shows permission denied, then it is because the file is not given executable permission. To give it permission type the following command" }, { "code": null, "e": 1409, "s": 1389, "text": "chmod +x install.sh" }, { "code": null, "e": 1498, "s": 1409, "text": "Again type the command ./install.sh and this time you have prior permissions to do that." }, { "code": null, "e": 1736, "s": 1498, "text": "Step 4: After running the script you will be asked to accept terms and conditions, type YES to accept. Then you will be asked to enter network interfaces that the system use. For the first line type eth0mon and for second line type eth0." }, { "code": null, "e": 1781, "s": 1736, "text": "The Script looks like this after installing." }, { "code": null, "e": 1922, "s": 1781, "text": "Use the script and enjoy many tools with one choice, no wasting of time in searching and installing, make your life easier.A sample working:" }, { "code": null, "e": 1938, "s": 1922, "text": "Madhusudan_Soni" }, { "code": null, "e": 1953, "s": 1938, "text": "how-to-install" }, { "code": null, "e": 1960, "s": 1953, "text": "How To" }, { "code": null, "e": 1979, "s": 1960, "text": "Installation Guide" }, { "code": null, "e": 1990, "s": 1979, "text": "Linux-Unix" }, { "code": null, "e": 1999, "s": 1990, "text": "TechTips" }, { "code": null, "e": 2097, "s": 1999, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2111, "s": 2097, "text": "Java Tutorial" }, { "code": null, "e": 2159, "s": 2111, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 2186, "s": 2159, "text": "How to Align Text in HTML?" }, { "code": null, "e": 2220, "s": 2186, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 2269, "s": 2220, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 2302, "s": 2269, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2336, "s": 2302, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 2372, "s": 2336, "text": "How to Install Anaconda on Windows?" }, { "code": null, "e": 2407, "s": 2372, "text": "Installation of Node.js on Windows" } ]
vfork() - Unix, Linux System Call
Unix - Home Unix - Getting Started Unix - File Management Unix - Directories Unix - File Permission Unix - Environment Unix - Basic Utilities Unix - Pipes & Filters Unix - Processes Unix - Communication Unix - The vi Editor Unix - What is Shell? Unix - Using Variables Unix - Special Variables Unix - Using Arrays Unix - Basic Operators Unix - Decision Making Unix - Shell Loops Unix - Loop Control Unix - Shell Substitutions Unix - Quoting Mechanisms Unix - IO Redirections Unix - Shell Functions Unix - Manpage Help Unix - Regular Expressions Unix - File System Basics Unix - User Administration Unix - System Performance Unix - System Logging Unix - Signals and Traps Unix - Useful Commands Unix - Quick Guide Unix - Builtin Functions Unix - System Calls Unix - Commands List Unix Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint vfork - create a child process and block parent #include <sys/types.h> #include <unistd.h> pid_t vfork(void); pid_t vfork(void); (From SUSv2 / POSIX draft.) The vfork() function has the same effect as fork(), except that the behaviour is undefined if the process created by vfork() either modifies any data other than a variable of type pid_t used to store the return value from vfork(), or returns from the function in which vfork() was called, or calls any other function before successfully calling _exit() or one of the exec() family of functions. vfork(), just like fork(2), creates a child process of the calling process. For details and return value and errors, see fork(2). vfork() is a special case of clone(2). It is used to create new processes without copying the page tables of the parent process. It may be useful in performance sensitive applications where a child will be created which then immediately issues an execve(). vfork() differs from fork() in that the parent is suspended until the child makes a call to execve(2) or _exit(2). The child shares all memory with its parent, including the stack, until execve() is issued by the child. The child must not return from the current function or call exit(), but may call _exit(). Signal handlers are inherited, but not shared. Signals to the parent arrive after the child releases the parent’s memory. Under Linux, fork() is implemented using copy-on-write pages, so the only penalty incurred by fork() is the time and memory required to duplicate the parent’s page tables, and to create a unique task structure for the child. However, in the bad old days a fork() would require making a complete copy of the caller’s data space, often needlessly, since usually immediately afterwards an exec() is done. Thus, for greater efficiency, BSD introduced the vfork() system call, that did not fully copy the address space of the parent process, but borrowed the parent’s memory and thread of control until a call to execve() or an exit occurred. The parent process was suspended while the child was using its resources. The use of vfork() was tricky: for example, not modifying data in the parent process depended on knowing which variables are held in a register. It is rather unfortunate that Linux revived this spectre from the past. The BSD manpage states: "This system call will be eliminated when proper system sharing mechanisms are implemented. Users should not depend on the memory sharing semantics of vfork() as it will, in that case, be made synonymous to fork(). " Formally speaking, the standard description given above does not allow one to use vfork() since a following exec() might fail, and then what happens is undefined. Details of the signal handling are obscure and differ between systems. The BSD manpage states: "To avoid a possible deadlock situation, processes that are children in the middle of a vfork() are never sent SIGTTOU or SIGTTIN signals; rather, output or ioctls are allowed and input attempts result in an end-of-file indication." Currently (Linux 2.3.25), strace(1) cannot follow vfork() and requires a kernel patch. The vfork() system call appeared in 3.0BSD. In 4.4BSD it was made synonymous to fork() but NetBSD introduced it again, cf. http://www.netbsd.org/Documentation/kernel/vfork.html . In Linux, it has been equivalent to fork() until 2.2.0-pre6 or so. Since 2.2.0-pre9 (on i386, somewhat later on other architectures) it is an independent system call. Support was added in glibc 2.0.112. 4.3BSD, POSIX.1-2001. The requirements put on vfork() by the standards are weaker than those put on fork(), so an implementation where the two are synonymous is compliant. In particular, the programmer cannot rely on the parent remaining blocked until a call of execve() or _exit() and cannot rely on any specific behaviour w.r.t. shared memory.
[ { "code": null, "e": 1600, "s": 1588, "text": "Unix - Home" }, { "code": null, "e": 1623, "s": 1600, "text": "Unix - Getting Started" }, { "code": null, "e": 1646, "s": 1623, "text": "Unix - File Management" }, { "code": null, "e": 1665, "s": 1646, "text": "Unix - Directories" }, { "code": null, "e": 1688, "s": 1665, "text": "Unix - File Permission" }, { "code": null, "e": 1707, "s": 1688, "text": "Unix - Environment" }, { "code": null, "e": 1730, "s": 1707, "text": "Unix - Basic Utilities" }, { "code": null, "e": 1753, "s": 1730, "text": "Unix - Pipes & Filters" }, { "code": null, "e": 1770, "s": 1753, "text": "Unix - Processes" }, { "code": null, "e": 1791, "s": 1770, "text": "Unix - Communication" }, { "code": null, "e": 1812, "s": 1791, "text": "Unix - The vi Editor" }, { "code": null, "e": 1834, "s": 1812, "text": "Unix - What is Shell?" }, { "code": null, "e": 1857, "s": 1834, "text": "Unix - Using Variables" }, { "code": null, "e": 1882, "s": 1857, "text": "Unix - Special Variables" }, { "code": null, "e": 1902, "s": 1882, "text": "Unix - Using Arrays" }, { "code": null, "e": 1925, "s": 1902, "text": "Unix - Basic Operators" }, { "code": null, "e": 1948, "s": 1925, "text": "Unix - Decision Making" }, { "code": null, "e": 1967, "s": 1948, "text": "Unix - Shell Loops" }, { "code": null, "e": 1987, "s": 1967, "text": "Unix - Loop Control" }, { "code": null, "e": 2014, "s": 1987, "text": "Unix - Shell Substitutions" }, { "code": null, "e": 2040, "s": 2014, "text": "Unix - Quoting Mechanisms" }, { "code": null, "e": 2063, "s": 2040, "text": "Unix - IO Redirections" }, { "code": null, "e": 2086, "s": 2063, "text": "Unix - Shell Functions" }, { "code": null, "e": 2106, "s": 2086, "text": "Unix - Manpage Help" }, { "code": null, "e": 2133, "s": 2106, "text": "Unix - Regular Expressions" }, { "code": null, "e": 2159, "s": 2133, "text": "Unix - File System Basics" }, { "code": null, "e": 2186, "s": 2159, "text": "Unix - User Administration" }, { "code": null, "e": 2212, "s": 2186, "text": "Unix - System Performance" }, { "code": null, "e": 2234, "s": 2212, "text": "Unix - System Logging" }, { "code": null, "e": 2259, "s": 2234, "text": "Unix - Signals and Traps" }, { "code": null, "e": 2282, "s": 2259, "text": "Unix - Useful Commands" }, { "code": null, "e": 2301, "s": 2282, "text": "Unix - Quick Guide" }, { "code": null, "e": 2326, "s": 2301, "text": "Unix - Builtin Functions" }, { "code": null, "e": 2346, "s": 2326, "text": "Unix - System Calls" }, { "code": null, "e": 2367, "s": 2346, "text": "Unix - Commands List" }, { "code": null, "e": 2389, "s": 2367, "text": "Unix Useful Resources" }, { "code": null, "e": 2407, "s": 2389, "text": "Computer Glossary" }, { "code": null, "e": 2418, "s": 2407, "text": "Who is Who" }, { "code": null, "e": 2453, "s": 2418, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2501, "s": 2453, "text": "vfork - create a child process and block parent" }, { "code": null, "e": 2566, "s": 2501, "text": "#include <sys/types.h>\n#include <unistd.h> \npid_t vfork(void); \n" }, { "code": null, "e": 2588, "s": 2566, "text": "\npid_t vfork(void); \n" }, { "code": null, "e": 3011, "s": 2588, "text": "(From SUSv2 / POSIX draft.) The vfork() function has the same effect as\nfork(), except that the behaviour is undefined if the process created by\nvfork() either modifies any data other than a variable of type\npid_t used to store the return value from\nvfork(), or returns from the function in which\nvfork() was called, or calls any other function before successfully calling\n_exit() or one of the\nexec() family of functions." }, { "code": null, "e": 3141, "s": 3011, "text": "vfork(), just like\nfork(2),\ncreates a child process of the calling process.\nFor details and return value and errors, see\nfork(2)." }, { "code": null, "e": 3400, "s": 3141, "text": "vfork() is a special case of\nclone(2).\nIt is used to create new processes without copying the page tables of\nthe parent process. It may be useful in performance sensitive applications\nwhere a child will be created which then immediately issues an\nexecve(). " }, { "code": null, "e": 3712, "s": 3400, "text": "\nvfork() differs from\nfork() in that the parent is suspended until the child makes a call to\nexecve(2)\nor\n_exit(2).\nThe child shares all memory with its parent, including the stack, until\nexecve() is issued by the child. The child must not return from the\ncurrent function or call\nexit(), but may call\n_exit()." }, { "code": null, "e": 3835, "s": 3712, "text": "Signal handlers are inherited, but not shared. Signals to the parent\narrive after the child releases the parent’s memory." }, { "code": null, "e": 4692, "s": 3835, "text": "Under Linux, fork() is implemented using copy-on-write pages, so the only penalty incurred by\nfork() is the time and memory required to duplicate the parent’s page tables,\nand to create a unique task structure for the child.\nHowever, in the bad old days a\nfork() would require making a complete copy of the caller’s data space,\noften needlessly, since usually immediately afterwards an\nexec() is done. Thus, for greater efficiency, BSD introduced the\nvfork() system call, that did not fully copy the address space of\nthe parent process, but borrowed the parent’s memory and thread\nof control until a call to\nexecve() or an exit occurred. The parent process was suspended while the\nchild was using its resources.\nThe use of\nvfork() was tricky: for example, not modifying data\nin the parent process depended on knowing which variables are\nheld in a register." }, { "code": null, "e": 5005, "s": 4692, "text": "It is rather unfortunate that Linux revived this spectre from the past.\nThe BSD manpage states:\n\"This system call will be eliminated when proper system sharing mechanisms\nare implemented. Users should not depend on the memory sharing semantics of\nvfork() as it will, in that case, be made synonymous to\nfork(). \"" }, { "code": null, "e": 5168, "s": 5005, "text": "Formally speaking, the standard description given above does not allow\none to use\nvfork() since a following\nexec() might fail, and then what happens is undefined." }, { "code": null, "e": 5496, "s": 5168, "text": "Details of the signal handling are obscure and differ between systems.\nThe BSD manpage states:\n\"To avoid a possible deadlock situation, processes that are children\nin the middle of a\nvfork() are never sent SIGTTOU or SIGTTIN signals; rather, output or\nioctls are allowed and input attempts result in an end-of-file indication.\"" }, { "code": null, "e": 5583, "s": 5496, "text": "Currently (Linux 2.3.25),\nstrace(1)\ncannot follow\nvfork() and requires a kernel patch." }, { "code": null, "e": 5965, "s": 5583, "text": "The vfork() system call appeared in 3.0BSD.\nIn 4.4BSD it was made synonymous to\nfork() but NetBSD introduced it again,\ncf. http://www.netbsd.org/Documentation/kernel/vfork.html .\nIn Linux, it has been equivalent to\nfork() until 2.2.0-pre6 or so. Since 2.2.0-pre9 (on i386, somewhat later on\nother architectures) it is an independent system call. Support was\nadded in glibc 2.0.112." } ]
Find minimum positive integer x such that a(x^2) + b(x) + c >= k
25 May, 2022 Given four integers a, b, c and k. The task is to find the minimum positive value of x such that ax2 + bx + c ≥ k.Examples: Input: a = 3, b = 4, c = 5, k = 6 Output: 1 For x = 0, a * 0 + b * 0 + c = 5 < 6 For x = 1, a * 1 + b * 1 + c = 3 + 4 + 5 = 12 > 6Input: a = 2, b = 7, c = 6, k = 3 Output: 0 Approach: The idea is to use binary search. The lower limit for our search will be 0 since x has to be minimum positive integer.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum positive// integer satisfying the given equationint MinimumX(int a, int b, int c, int k){ int x = INT_MAX; if (k <= c) return 0; int h = k - c; int l = 0; // Binary search to find the value of x while (l <= h) { int m = (l + h) / 2; if ((a * m * m) + (b * m) > (k - c)) { x = min(x, m); h = m - 1; } else if ((a * m * m) + (b * m) < (k - c)) l = m + 1; else return m; } // Return the answer return x;} // Driver codeint main(){ int a = 3, b = 2, c = 4, k = 15; cout << MinimumX(a, b, c, k); return 0;} // Java implementation of the approachclass GFG{ // Function to return the minimum positive// integer satisfying the given equationstatic int MinimumX(int a, int b, int c, int k){ int x = Integer.MAX_VALUE; if (k <= c) return 0; int h = k - c; int l = 0; // Binary search to find the value of x while (l <= h) { int m = (l + h) / 2; if ((a * m * m) + (b * m) > (k - c)) { x = Math.min(x, m); h = m - 1; } else if ((a * m * m) + (b * m) < (k - c)) l = m + 1; else return m; } // Return the answer return x;} // Driver codepublic static void main(String[] args){ int a = 3, b = 2, c = 4, k = 15; System.out.println(MinimumX(a, b, c, k));}} // This code is contributed by Code_Mech. # Python3 implementation of the approach # Function to return the minimum positive# integer satisfying the given equationdef MinimumX(a, b, c, k): x = 10**9 if (k <= c): return 0 h = k - c l = 0 # Binary search to find the value of x while (l <= h): m = (l + h) // 2 if ((a * m * m) + (b * m) > (k - c)): x = min(x, m) h = m - 1 elif ((a * m * m) + (b * m) < (k - c)): l = m + 1 else: return m # Return the answer return x # Driver codea, b, c, k = 3, 2, 4, 15print(MinimumX(a, b, c, k)) # This code is contributed by mohit kumar // C# implementation of the approachusing System; class GFG{ // Function to return the minimum positive// integer satisfying the given equationstatic int MinimumX(int a, int b, int c, int k){ int x = int.MaxValue; if (k <= c) return 0; int h = k - c; int l = 0; // Binary search to find the value of x while (l <= h) { int m = (l + h) / 2; if ((a * m * m) + (b * m) > (k - c)) { x = Math.Min(x, m); h = m - 1; } else if ((a * m * m) + (b * m) < (k - c)) l = m + 1; else return m; } // Return the answer return x;} // Driver codepublic static void Main(){ int a = 3, b = 2, c = 4, k = 15; Console.Write(MinimumX(a, b, c, k));}} // This code is contributed by Akanksha Rai <?php// PHP implementation of the approach // Function to return the minimum positive// integer satisfying the given equationfunction MinimumX($a, $b, $c, $k){ $x = PHP_INT_MAX; if ($k <= $c) return 0; $h = $k - $c; $l = 0; // Binary search to find the value of x while ($l <= $h) { $m = floor(($l + $h) / 2); if (($a * $m * $m) + ($b * $m) > ($k - $c)) { $x = min($x, $m); $h = $m - 1; } else if (($a * $m * $m) + ($b * $m) < ($k - $c)) $l = $m + 1; else return $m; } // Return the answer return $x;} // Driver code$a = 3; $b = 2; $c = 4; $k = 15; echo MinimumX($a, $b, $c, $k); // This code is contributed by Ryuga?> <script>// Javascript implementation of the approach // Function to return the minimum positive// integer satisfying the given equationfunction MinimumX(a,b,c,k){ let x = Number.MAX_VALUE; if (k <= c) return 0; let h = k - c; let l = 0; // Binary search to find the value of x while (l <= h) { let m = Math.floor((l + h) / 2); if ((a * m * m) + (b * m) > (k - c)) { x = Math.min(x, m); h = m - 1; } else if ((a * m * m) + (b * m) < (k - c)) l = m + 1; else return m; } // Return the answer return x;} // Driver codelet a = 3, b = 2, c = 4, k = 15;document.write(MinimumX(a, b, c, k)); // This code is contributed by patel2127</script> 2 Time Complexity : O(logN) Auxiliary Space : O(1) mohit kumar 29 ankthon Code_Mech Akanksha_Rai patel2127 jayanth_mkv Binary Search Algorithms Searching Searching Binary Search Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Find if there is a path between two vertices in an undirected graph How to Start Learning DSA? Complete Roadmap To Learn DSA From Scratch Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search K'th Smallest/Largest Element in Unsorted Array | Set 1 Search an element in a sorted and rotated array
[ { "code": null, "e": 52, "s": 24, "text": "\n25 May, 2022" }, { "code": null, "e": 178, "s": 52, "text": "Given four integers a, b, c and k. The task is to find the minimum positive value of x such that ax2 + bx + c ≥ k.Examples: " }, { "code": null, "e": 354, "s": 178, "text": "Input: a = 3, b = 4, c = 5, k = 6 Output: 1 For x = 0, a * 0 + b * 0 + c = 5 < 6 For x = 1, a * 1 + b * 1 + c = 3 + 4 + 5 = 12 > 6Input: a = 2, b = 7, c = 6, k = 3 Output: 0 " }, { "code": null, "e": 537, "s": 356, "text": "Approach: The idea is to use binary search. The lower limit for our search will be 0 since x has to be minimum positive integer.Below is the implementation of the above approach: " }, { "code": null, "e": 541, "s": 537, "text": "C++" }, { "code": null, "e": 546, "s": 541, "text": "Java" }, { "code": null, "e": 554, "s": 546, "text": "Python3" }, { "code": null, "e": 557, "s": 554, "text": "C#" }, { "code": null, "e": 561, "s": 557, "text": "PHP" }, { "code": null, "e": 572, "s": 561, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum positive// integer satisfying the given equationint MinimumX(int a, int b, int c, int k){ int x = INT_MAX; if (k <= c) return 0; int h = k - c; int l = 0; // Binary search to find the value of x while (l <= h) { int m = (l + h) / 2; if ((a * m * m) + (b * m) > (k - c)) { x = min(x, m); h = m - 1; } else if ((a * m * m) + (b * m) < (k - c)) l = m + 1; else return m; } // Return the answer return x;} // Driver codeint main(){ int a = 3, b = 2, c = 4, k = 15; cout << MinimumX(a, b, c, k); return 0;}", "e": 1317, "s": 572, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the minimum positive// integer satisfying the given equationstatic int MinimumX(int a, int b, int c, int k){ int x = Integer.MAX_VALUE; if (k <= c) return 0; int h = k - c; int l = 0; // Binary search to find the value of x while (l <= h) { int m = (l + h) / 2; if ((a * m * m) + (b * m) > (k - c)) { x = Math.min(x, m); h = m - 1; } else if ((a * m * m) + (b * m) < (k - c)) l = m + 1; else return m; } // Return the answer return x;} // Driver codepublic static void main(String[] args){ int a = 3, b = 2, c = 4, k = 15; System.out.println(MinimumX(a, b, c, k));}} // This code is contributed by Code_Mech.", "e": 2134, "s": 1317, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the minimum positive# integer satisfying the given equationdef MinimumX(a, b, c, k): x = 10**9 if (k <= c): return 0 h = k - c l = 0 # Binary search to find the value of x while (l <= h): m = (l + h) // 2 if ((a * m * m) + (b * m) > (k - c)): x = min(x, m) h = m - 1 elif ((a * m * m) + (b * m) < (k - c)): l = m + 1 else: return m # Return the answer return x # Driver codea, b, c, k = 3, 2, 4, 15print(MinimumX(a, b, c, k)) # This code is contributed by mohit kumar", "e": 2773, "s": 2134, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the minimum positive// integer satisfying the given equationstatic int MinimumX(int a, int b, int c, int k){ int x = int.MaxValue; if (k <= c) return 0; int h = k - c; int l = 0; // Binary search to find the value of x while (l <= h) { int m = (l + h) / 2; if ((a * m * m) + (b * m) > (k - c)) { x = Math.Min(x, m); h = m - 1; } else if ((a * m * m) + (b * m) < (k - c)) l = m + 1; else return m; } // Return the answer return x;} // Driver codepublic static void Main(){ int a = 3, b = 2, c = 4, k = 15; Console.Write(MinimumX(a, b, c, k));}} // This code is contributed by Akanksha Rai", "e": 3581, "s": 2773, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the minimum positive// integer satisfying the given equationfunction MinimumX($a, $b, $c, $k){ $x = PHP_INT_MAX; if ($k <= $c) return 0; $h = $k - $c; $l = 0; // Binary search to find the value of x while ($l <= $h) { $m = floor(($l + $h) / 2); if (($a * $m * $m) + ($b * $m) > ($k - $c)) { $x = min($x, $m); $h = $m - 1; } else if (($a * $m * $m) + ($b * $m) < ($k - $c)) $l = $m + 1; else return $m; } // Return the answer return $x;} // Driver code$a = 3; $b = 2; $c = 4; $k = 15; echo MinimumX($a, $b, $c, $k); // This code is contributed by Ryuga?>", "e": 4354, "s": 3581, "text": null }, { "code": "<script>// Javascript implementation of the approach // Function to return the minimum positive// integer satisfying the given equationfunction MinimumX(a,b,c,k){ let x = Number.MAX_VALUE; if (k <= c) return 0; let h = k - c; let l = 0; // Binary search to find the value of x while (l <= h) { let m = Math.floor((l + h) / 2); if ((a * m * m) + (b * m) > (k - c)) { x = Math.min(x, m); h = m - 1; } else if ((a * m * m) + (b * m) < (k - c)) l = m + 1; else return m; } // Return the answer return x;} // Driver codelet a = 3, b = 2, c = 4, k = 15;document.write(MinimumX(a, b, c, k)); // This code is contributed by patel2127</script>", "e": 5124, "s": 4354, "text": null }, { "code": null, "e": 5126, "s": 5124, "text": "2" }, { "code": null, "e": 5154, "s": 5128, "text": "Time Complexity : O(logN)" }, { "code": null, "e": 5177, "s": 5154, "text": "Auxiliary Space : O(1)" }, { "code": null, "e": 5192, "s": 5177, "text": "mohit kumar 29" }, { "code": null, "e": 5200, "s": 5192, "text": "ankthon" }, { "code": null, "e": 5210, "s": 5200, "text": "Code_Mech" }, { "code": null, "e": 5223, "s": 5210, "text": "Akanksha_Rai" }, { "code": null, "e": 5233, "s": 5223, "text": "patel2127" }, { "code": null, "e": 5245, "s": 5233, "text": "jayanth_mkv" }, { "code": null, "e": 5259, "s": 5245, "text": "Binary Search" }, { "code": null, "e": 5270, "s": 5259, "text": "Algorithms" }, { "code": null, "e": 5280, "s": 5270, "text": "Searching" }, { "code": null, "e": 5290, "s": 5280, "text": "Searching" }, { "code": null, "e": 5304, "s": 5290, "text": "Binary Search" }, { "code": null, "e": 5315, "s": 5304, "text": "Algorithms" }, { "code": null, "e": 5413, "s": 5315, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5451, "s": 5413, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 5519, "s": 5451, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 5546, "s": 5519, "text": "How to Start Learning DSA?" }, { "code": null, "e": 5589, "s": 5546, "text": "Complete Roadmap To Learn DSA From Scratch" }, { "code": null, "e": 5656, "s": 5589, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 5670, "s": 5656, "text": "Binary Search" }, { "code": null, "e": 5738, "s": 5670, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 5752, "s": 5738, "text": "Linear Search" }, { "code": null, "e": 5808, "s": 5752, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" } ]
Sort the matrix row-wise and column-wise
06 May, 2021 Given a n x n matrix. The problem is to sort the matrix row-wise and column wise.Examples: Input : mat[][] = { {4, 1, 3}, {9, 6, 8}, {5, 2, 7} } Output : 1 3 4 2 5 7 6 8 9 Input : mat[][] = { {12, 7, 1, 8}, {20, 9, 11, 2}, {15, 4, 5, 13}, {3, 18, 10, 6} } Output : 1 5 8 12 2 6 10 15 3 7 11 18 4 9 13 20 Approach: Following are the steps: Sort each row of the matrix.Get transpose of the matrix.Again sort each row of the matrix.Again get transpose of the matrix. Sort each row of the matrix. Get transpose of the matrix. Again sort each row of the matrix. Again get transpose of the matrix. Algorithm for sorting each row of matrix using C++ STL sort(): for (int i = 0 ; i < n; i++) sort(mat[i], mat[i] + n); Algorithm for getting transpose of the matrix: for (int i = 0; i < n; i++) { for (int j = i + 1; i < n; i++) { int temp = mat[i][j]; mat[i][j] = mat[j][i]; mat[j][i] = temp; } } C++ Java Python 3 C# PHP Javascript // C++ implementation to sort the matrix row-wise// and column-wise#include <bits/stdc++.h> using namespace std; #define MAX_SIZE 10 // function to sort each row of the matrixvoid sortByRow(int mat[MAX_SIZE][MAX_SIZE], int n){ for (int i = 0; i < n; i++) // sorting row number 'i' sort(mat[i], mat[i] + n);} // function to find transpose of the matrixvoid transpose(int mat[MAX_SIZE][MAX_SIZE], int n){ for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // swapping element at index (i, j) // by element at index (j, i) swap(mat[i][j], mat[j][i]);} // function to sort the matrix row-wise// and column-wisevoid sortMatRowAndColWise(int mat[MAX_SIZE][MAX_SIZE], int n){ // sort rows of mat[][] sortByRow(mat, n); // get transpose of mat[][] transpose(mat, n); // again sort rows of mat[][] sortByRow(mat, n); // again get transpose of mat[][] transpose(mat, n);} // function to print the matrixvoid printMat(int mat[MAX_SIZE][MAX_SIZE], int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << mat[i][j] << " "; cout << endl; }} // Driver program to test aboveint main(){ int mat[MAX_SIZE][MAX_SIZE] = { { 4, 1, 3 }, { 9, 6, 8 }, { 5, 2, 7 } }; int n = 3; cout << "Original Matrix:\n"; printMat(mat, n); sortMatRowAndColWise(mat, n); cout << "\nMatrix After Sorting:\n"; printMat(mat, n); return 0;} // Java implementation to sort the// matrix row-wise and column-wiseimport java.util.Arrays; class GFG{ static final int MAX_SIZE=10; // function to sort each row of the matrix static void sortByRow(int mat[][], int n) { for (int i = 0; i < n; i++) // sorting row number 'i' Arrays.sort(mat[i]); } // function to find transpose of the matrix static void transpose(int mat[][], int n) { for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { // swapping element at index (i, j) // by element at index (j, i) int temp=mat[i][j]; mat[i][j]=mat[j][i]; mat[j][i]=temp; } } // function to sort the matrix row-wise // and column-wise static void sortMatRowAndColWise(int mat[][],int n) { // sort rows of mat[][] sortByRow(mat, n); // get transpose of mat[][] transpose(mat, n); // again sort rows of mat[][] sortByRow(mat, n); // again get transpose of mat[][] transpose(mat, n); } // function to print the matrix static void printMat(int mat[][], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print(mat[i][j] + " "); System.out.println(); } } // Driver code public static void main (String[] args) { int mat[][] = { { 4, 1, 3 }, { 9, 6, 8 }, { 5, 2, 7 } }; int n = 3; System.out.print("Original Matrix:\n"); printMat(mat, n); sortMatRowAndColWise(mat, n); System.out.print("\nMatrix After Sorting:\n"); printMat(mat, n); }} // This code is contributed by Anant Agarwal. # Python 3 implementation to# sort the matrix row-wise# and column-wiseMAX_SIZE = 10 # function to sort each# row of the matrixdef sortByRow(mat, n): for i in range (n): # sorting row number 'i' for j in range(n-1): if mat[i][j] > mat[i][j + 1]: temp = mat[i][j] mat[i][j] = mat[i][j + 1] mat[i][j + 1] = temp # function to find# transpose of the matrixdef transpose(mat, n): for i in range (n): for j in range(i + 1, n): # swapping element at # index (i, j) by element # at index (j, i) t = mat[i][j] mat[i][j] = mat[j][i] mat[j][i] = t # function to sort# the matrix row-wise# and column-wisedef sortMatRowAndColWise(mat, n): # sort rows of mat[][] sortByRow(mat, n) # get transpose of mat[][] transpose(mat, n) # again sort rows of mat[][] sortByRow(mat, n) # again get transpose of mat[][] transpose(mat, n) # function to print the matrixdef printMat(mat, n): for i in range(n): for j in range(n): print(str(mat[i][j] ), end = " ") print(); # Driver Codemat = [[ 4, 1, 3 ], [ 9, 6, 8 ], [ 5, 2, 7 ]]n = 3 print("Original Matrix:")printMat(mat, n) sortMatRowAndColWise(mat, n) print("\nMatrix After Sorting:")printMat(mat, n) # This code is contributed# by ChitraNayal // C# implementation to sort the// matrix row-wise and column-wiseusing System; class GFG{ // function to sort each // row of the matrix static void sortByRow(int [,]mat, int n) { // sorting row number 'i' for (int i = 0; i < n ; i++) { for(int j = 0; j < n - 1; j++) { if(mat[i, j] > mat[i, j + 1]) { var temp = mat[i, j]; mat[i, j] = mat[i, j + 1]; mat[i, j + 1] = temp; } } } } // function to find transpose // of the matrix static void transpose(int [,]mat, int n) { for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { // swapping element at // index (i, j) by // element at index (j, i) var temp = mat[i, j]; mat[i, j] = mat[j, i]; mat[j, i] = temp; } } // function to sort // the matrix row-wise // and column-wise static void sortMatRowAndColWise(int [,]mat, int n) { // sort rows of mat[,] sortByRow(mat, n); // get transpose of mat[,] transpose(mat, n); // again sort rows of mat[,] sortByRow(mat, n); // again get transpose of mat[,] transpose(mat, n); } // function to print the matrix static void printMat(int [,]mat, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) Console.Write(mat[i, j] + " "); Console.Write("\n"); } } // Driver code public static void Main () { int [,]mat = {{4, 1, 3}, {9, 6, 8}, {5, 2, 7}}; int n = 3; Console.Write("Original Matrix:\n"); printMat(mat, n); sortMatRowAndColWise(mat, n); Console.Write("\nMatrix After Sorting:\n"); printMat(mat, n); }} // This code is contributed// by ChitraNayal <?php// PHP implementation to sort// the matrix row-wise and// column-wise$MAX_SIZE = 10; // function to sort each// row of the matrixfunction sortByRow(&$mat, $n){ for ($i = 0; $i < $n; $i++) // sorting row number 'i' sort($mat[$i]);} // function to find// transpose of the matrixfunction transpose(&$mat, $n){ for ($i = 0; $i < $n; $i++) { for ($j = $i + 1; $j < $n; $j++) { // swapping element at index (i, j) // by element at index (j, i) $t = $mat[$i][$j]; $mat[$i][$j] = $mat[$j][$i]; $mat[$j][$i] = $t; } }} // function to sort// the matrix row-wise// and column-wisefunction sortMatRowAndColWise(&$mat, $n){ // sort rows of mat[][] sortByRow($mat, $n); // get transpose of mat[][] transpose($mat, $n); // again sort rows of mat[][] sortByRow($mat, $n); // again get transpose of mat[][] transpose($mat, $n);} // function to print the matrixfunction printMat(&$mat, $n){ for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) echo $mat[$i][$j] . " "; echo "\n"; }} // Driver Code$mat = array(array( 4, 1, 3 ), array( 9, 6, 8 ), array( 5, 2, 7 ));$n = 3; echo "Original Matrix:\n";printMat($mat, $n); sortMatRowAndColWise($mat, $n); echo "\nMatrix After Sorting:\n";printMat($mat, $n); // This code is contributed// by ChitraNayal?> <script>// Javascript implementation to sort the// matrix row-wise and column-wise let MAX_SIZE=10; // function to sort each row of the matrix function sortByRow(mat,n) { for (let i = 0; i < n; i++) // sorting row number 'i' mat[i].sort(function(a,b){return a-b;}); } // function to find transpose of the matrix function transpose(mat,n) { for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) { // swapping element at index (i, j) // by element at index (j, i) let temp=mat[i][j]; mat[i][j]=mat[j][i]; mat[j][i]=temp; } } // function to sort the matrix row-wise // and column-wise function sortMatRowAndColWise(mat,n) { // sort rows of mat[][] sortByRow(mat, n); // get transpose of mat[][] transpose(mat, n); // again sort rows of mat[][] sortByRow(mat, n); // again get transpose of mat[][] transpose(mat, n); } // function to print the matrix function printMat(mat,n) { for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) document.write(mat[i][j] + " "); document.write("<br>"); } } // Driver code let mat = [[ 4, 1, 3 ], [ 9, 6, 8 ], [ 5, 2, 7 ]]; let n = 3; document.write("Original Matrix:<br>"); printMat(mat, n); sortMatRowAndColWise(mat, n); document.write("\nMatrix After Sorting:<br>"); printMat(mat, n); // This code is contributed by avanitrachhadiya2155</script> Output: Original Matrix: 4 1 3 9 6 8 5 2 7 Matrix After Sorting: 1 3 4 2 5 7 6 8 9 Time Complexity: O(n2log2n). Auxiliary Space: O(1). ukasp avanitrachhadiya2155 Matrix Sorting Sorting Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 May, 2021" }, { "code": null, "e": 147, "s": 54, "text": "Given a n x n matrix. The problem is to sort the matrix row-wise and column wise.Examples: " }, { "code": null, "e": 507, "s": 147, "text": "Input : mat[][] = { {4, 1, 3},\n {9, 6, 8},\n {5, 2, 7} }\nOutput : 1 3 4\n 2 5 7\n 6 8 9\n\nInput : mat[][] = { {12, 7, 1, 8},\n {20, 9, 11, 2},\n {15, 4, 5, 13},\n {3, 18, 10, 6} } \nOutput : 1 5 8 12\n 2 6 10 15\n 3 7 11 18\n 4 9 13 20" }, { "code": null, "e": 545, "s": 509, "text": "Approach: Following are the steps: " }, { "code": null, "e": 670, "s": 545, "text": "Sort each row of the matrix.Get transpose of the matrix.Again sort each row of the matrix.Again get transpose of the matrix." }, { "code": null, "e": 699, "s": 670, "text": "Sort each row of the matrix." }, { "code": null, "e": 728, "s": 699, "text": "Get transpose of the matrix." }, { "code": null, "e": 763, "s": 728, "text": "Again sort each row of the matrix." }, { "code": null, "e": 798, "s": 763, "text": "Again get transpose of the matrix." }, { "code": null, "e": 863, "s": 798, "text": "Algorithm for sorting each row of matrix using C++ STL sort(): " }, { "code": null, "e": 922, "s": 863, "text": "for (int i = 0 ; i < n; i++)\n sort(mat[i], mat[i] + n);" }, { "code": null, "e": 971, "s": 922, "text": "Algorithm for getting transpose of the matrix: " }, { "code": null, "e": 1134, "s": 971, "text": "for (int i = 0; i < n; i++) {\n for (int j = i + 1; i < n; i++) {\n int temp = mat[i][j];\n mat[i][j] = mat[j][i];\n mat[j][i] = temp;\n }\n}" }, { "code": null, "e": 1140, "s": 1136, "text": "C++" }, { "code": null, "e": 1145, "s": 1140, "text": "Java" }, { "code": null, "e": 1154, "s": 1145, "text": "Python 3" }, { "code": null, "e": 1157, "s": 1154, "text": "C#" }, { "code": null, "e": 1161, "s": 1157, "text": "PHP" }, { "code": null, "e": 1172, "s": 1161, "text": "Javascript" }, { "code": "// C++ implementation to sort the matrix row-wise// and column-wise#include <bits/stdc++.h> using namespace std; #define MAX_SIZE 10 // function to sort each row of the matrixvoid sortByRow(int mat[MAX_SIZE][MAX_SIZE], int n){ for (int i = 0; i < n; i++) // sorting row number 'i' sort(mat[i], mat[i] + n);} // function to find transpose of the matrixvoid transpose(int mat[MAX_SIZE][MAX_SIZE], int n){ for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // swapping element at index (i, j) // by element at index (j, i) swap(mat[i][j], mat[j][i]);} // function to sort the matrix row-wise// and column-wisevoid sortMatRowAndColWise(int mat[MAX_SIZE][MAX_SIZE], int n){ // sort rows of mat[][] sortByRow(mat, n); // get transpose of mat[][] transpose(mat, n); // again sort rows of mat[][] sortByRow(mat, n); // again get transpose of mat[][] transpose(mat, n);} // function to print the matrixvoid printMat(int mat[MAX_SIZE][MAX_SIZE], int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << mat[i][j] << \" \"; cout << endl; }} // Driver program to test aboveint main(){ int mat[MAX_SIZE][MAX_SIZE] = { { 4, 1, 3 }, { 9, 6, 8 }, { 5, 2, 7 } }; int n = 3; cout << \"Original Matrix:\\n\"; printMat(mat, n); sortMatRowAndColWise(mat, n); cout << \"\\nMatrix After Sorting:\\n\"; printMat(mat, n); return 0;}", "e": 2745, "s": 1172, "text": null }, { "code": "// Java implementation to sort the// matrix row-wise and column-wiseimport java.util.Arrays; class GFG{ static final int MAX_SIZE=10; // function to sort each row of the matrix static void sortByRow(int mat[][], int n) { for (int i = 0; i < n; i++) // sorting row number 'i' Arrays.sort(mat[i]); } // function to find transpose of the matrix static void transpose(int mat[][], int n) { for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { // swapping element at index (i, j) // by element at index (j, i) int temp=mat[i][j]; mat[i][j]=mat[j][i]; mat[j][i]=temp; } } // function to sort the matrix row-wise // and column-wise static void sortMatRowAndColWise(int mat[][],int n) { // sort rows of mat[][] sortByRow(mat, n); // get transpose of mat[][] transpose(mat, n); // again sort rows of mat[][] sortByRow(mat, n); // again get transpose of mat[][] transpose(mat, n); } // function to print the matrix static void printMat(int mat[][], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) System.out.print(mat[i][j] + \" \"); System.out.println(); } } // Driver code public static void main (String[] args) { int mat[][] = { { 4, 1, 3 }, { 9, 6, 8 }, { 5, 2, 7 } }; int n = 3; System.out.print(\"Original Matrix:\\n\"); printMat(mat, n); sortMatRowAndColWise(mat, n); System.out.print(\"\\nMatrix After Sorting:\\n\"); printMat(mat, n); }} // This code is contributed by Anant Agarwal.", "e": 4628, "s": 2745, "text": null }, { "code": "# Python 3 implementation to# sort the matrix row-wise# and column-wiseMAX_SIZE = 10 # function to sort each# row of the matrixdef sortByRow(mat, n): for i in range (n): # sorting row number 'i' for j in range(n-1): if mat[i][j] > mat[i][j + 1]: temp = mat[i][j] mat[i][j] = mat[i][j + 1] mat[i][j + 1] = temp # function to find# transpose of the matrixdef transpose(mat, n): for i in range (n): for j in range(i + 1, n): # swapping element at # index (i, j) by element # at index (j, i) t = mat[i][j] mat[i][j] = mat[j][i] mat[j][i] = t # function to sort# the matrix row-wise# and column-wisedef sortMatRowAndColWise(mat, n): # sort rows of mat[][] sortByRow(mat, n) # get transpose of mat[][] transpose(mat, n) # again sort rows of mat[][] sortByRow(mat, n) # again get transpose of mat[][] transpose(mat, n) # function to print the matrixdef printMat(mat, n): for i in range(n): for j in range(n): print(str(mat[i][j] ), end = \" \") print(); # Driver Codemat = [[ 4, 1, 3 ], [ 9, 6, 8 ], [ 5, 2, 7 ]]n = 3 print(\"Original Matrix:\")printMat(mat, n) sortMatRowAndColWise(mat, n) print(\"\\nMatrix After Sorting:\")printMat(mat, n) # This code is contributed# by ChitraNayal", "e": 6039, "s": 4628, "text": null }, { "code": "// C# implementation to sort the// matrix row-wise and column-wiseusing System; class GFG{ // function to sort each // row of the matrix static void sortByRow(int [,]mat, int n) { // sorting row number 'i' for (int i = 0; i < n ; i++) { for(int j = 0; j < n - 1; j++) { if(mat[i, j] > mat[i, j + 1]) { var temp = mat[i, j]; mat[i, j] = mat[i, j + 1]; mat[i, j + 1] = temp; } } } } // function to find transpose // of the matrix static void transpose(int [,]mat, int n) { for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { // swapping element at // index (i, j) by // element at index (j, i) var temp = mat[i, j]; mat[i, j] = mat[j, i]; mat[j, i] = temp; } } // function to sort // the matrix row-wise // and column-wise static void sortMatRowAndColWise(int [,]mat, int n) { // sort rows of mat[,] sortByRow(mat, n); // get transpose of mat[,] transpose(mat, n); // again sort rows of mat[,] sortByRow(mat, n); // again get transpose of mat[,] transpose(mat, n); } // function to print the matrix static void printMat(int [,]mat, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) Console.Write(mat[i, j] + \" \"); Console.Write(\"\\n\"); } } // Driver code public static void Main () { int [,]mat = {{4, 1, 3}, {9, 6, 8}, {5, 2, 7}}; int n = 3; Console.Write(\"Original Matrix:\\n\"); printMat(mat, n); sortMatRowAndColWise(mat, n); Console.Write(\"\\nMatrix After Sorting:\\n\"); printMat(mat, n); }} // This code is contributed// by ChitraNayal", "e": 8294, "s": 6039, "text": null }, { "code": "<?php// PHP implementation to sort// the matrix row-wise and// column-wise$MAX_SIZE = 10; // function to sort each// row of the matrixfunction sortByRow(&$mat, $n){ for ($i = 0; $i < $n; $i++) // sorting row number 'i' sort($mat[$i]);} // function to find// transpose of the matrixfunction transpose(&$mat, $n){ for ($i = 0; $i < $n; $i++) { for ($j = $i + 1; $j < $n; $j++) { // swapping element at index (i, j) // by element at index (j, i) $t = $mat[$i][$j]; $mat[$i][$j] = $mat[$j][$i]; $mat[$j][$i] = $t; } }} // function to sort// the matrix row-wise// and column-wisefunction sortMatRowAndColWise(&$mat, $n){ // sort rows of mat[][] sortByRow($mat, $n); // get transpose of mat[][] transpose($mat, $n); // again sort rows of mat[][] sortByRow($mat, $n); // again get transpose of mat[][] transpose($mat, $n);} // function to print the matrixfunction printMat(&$mat, $n){ for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) echo $mat[$i][$j] . \" \"; echo \"\\n\"; }} // Driver Code$mat = array(array( 4, 1, 3 ), array( 9, 6, 8 ), array( 5, 2, 7 ));$n = 3; echo \"Original Matrix:\\n\";printMat($mat, $n); sortMatRowAndColWise($mat, $n); echo \"\\nMatrix After Sorting:\\n\";printMat($mat, $n); // This code is contributed// by ChitraNayal?>", "e": 9736, "s": 8294, "text": null }, { "code": "<script>// Javascript implementation to sort the// matrix row-wise and column-wise let MAX_SIZE=10; // function to sort each row of the matrix function sortByRow(mat,n) { for (let i = 0; i < n; i++) // sorting row number 'i' mat[i].sort(function(a,b){return a-b;}); } // function to find transpose of the matrix function transpose(mat,n) { for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) { // swapping element at index (i, j) // by element at index (j, i) let temp=mat[i][j]; mat[i][j]=mat[j][i]; mat[j][i]=temp; } } // function to sort the matrix row-wise // and column-wise function sortMatRowAndColWise(mat,n) { // sort rows of mat[][] sortByRow(mat, n); // get transpose of mat[][] transpose(mat, n); // again sort rows of mat[][] sortByRow(mat, n); // again get transpose of mat[][] transpose(mat, n); } // function to print the matrix function printMat(mat,n) { for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) document.write(mat[i][j] + \" \"); document.write(\"<br>\"); } } // Driver code let mat = [[ 4, 1, 3 ], [ 9, 6, 8 ], [ 5, 2, 7 ]]; let n = 3; document.write(\"Original Matrix:<br>\"); printMat(mat, n); sortMatRowAndColWise(mat, n); document.write(\"\\nMatrix After Sorting:<br>\"); printMat(mat, n); // This code is contributed by avanitrachhadiya2155</script>", "e": 11456, "s": 9736, "text": null }, { "code": null, "e": 11466, "s": 11456, "text": "Output: " }, { "code": null, "e": 11542, "s": 11466, "text": "Original Matrix:\n4 1 3\n9 6 8\n5 2 7\n\nMatrix After Sorting:\n1 3 4\n2 5 7\n6 8 9" }, { "code": null, "e": 11595, "s": 11542, "text": "Time Complexity: O(n2log2n). Auxiliary Space: O(1). " }, { "code": null, "e": 11601, "s": 11595, "text": "ukasp" }, { "code": null, "e": 11622, "s": 11601, "text": "avanitrachhadiya2155" }, { "code": null, "e": 11629, "s": 11622, "text": "Matrix" }, { "code": null, "e": 11637, "s": 11629, "text": "Sorting" }, { "code": null, "e": 11645, "s": 11637, "text": "Sorting" }, { "code": null, "e": 11652, "s": 11645, "text": "Matrix" } ]
Python - geometry method in Tkinter
Python has capability to create GUI applications using the Tkinter library. The library provides many methods useful for GUI applications. The geometry method is a fundamental one which decides the size, position and some other attributes of the screen layout we are going to create. In the below program we create a window of size 22x200 pixels using the geometry method. Then we add a button to it and decide button position in the window using the side and pady options. from tkinter import * base = Tk() base.geometry('200x200') stud = Button(base, text = 'Tutorialspoint', font =('Courier',14, 'bold')) stud.pack(side = TOP, pady = 6) mainloop() Running the above code gives us the following result: In this example we create a canvas with a clickable link which will enable us to visit a URL. Again we use the geometry method to create the canvas of the required size. import webbrowser from tkinter import* def Uniform_Resource_Locator(): url=webbrowser.open_new("http://tutorialspoint.com") main=Tk() main.geometry("300x250") stud=Button(main, text="visit Tutorialspoint", font=('Courier',15,'bold'), command=Uniform_Resource_Locator)stud.pack(side = RIGHT, pady = 6) main.mainloop() Running the above code gives us the following result
[ { "code": null, "e": 1471, "s": 1187, "text": "Python has capability to create GUI applications using the Tkinter library. The library provides many methods useful for GUI applications. The geometry method is a fundamental one which decides the size, position and some other attributes of the screen layout we are going to create." }, { "code": null, "e": 1661, "s": 1471, "text": "In the below program we create a window of size 22x200 pixels using the geometry method. Then we add a button to it and decide button position in the window using the side and pady options." }, { "code": null, "e": 1838, "s": 1661, "text": "from tkinter import *\nbase = Tk()\nbase.geometry('200x200')\nstud = Button(base, text = 'Tutorialspoint', font =('Courier',14, 'bold'))\nstud.pack(side = TOP, pady = 6)\nmainloop()" }, { "code": null, "e": 1892, "s": 1838, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 2062, "s": 1892, "text": "In this example we create a canvas with a clickable link which will enable us to visit a URL. Again we use the geometry method to create the canvas of the required size." }, { "code": null, "e": 2382, "s": 2062, "text": "import webbrowser\nfrom tkinter import*\ndef Uniform_Resource_Locator():\n url=webbrowser.open_new(\"http://tutorialspoint.com\")\nmain=Tk()\nmain.geometry(\"300x250\")\nstud=Button(main, text=\"visit Tutorialspoint\", font=('Courier',15,'bold'), command=Uniform_Resource_Locator)stud.pack(side = RIGHT, pady = 6)\nmain.mainloop()" }, { "code": null, "e": 2435, "s": 2382, "text": "Running the above code gives us the following result" } ]
ML | Momentum-based Gradient Optimizer introduction
18 Nov, 2021 Gradient Descent is an optimization technique used in Machine Learning frameworks to train different models. The training process consists of an objective function (or the error function), which determines the error a Machine Learning model has on a given dataset. While training, the parameters of this algorithm are initialized to random values. As the algorithm iterates, the parameters are updated such that we reach closer and closer to the optimal value of the function.However, Adaptive Optimization Algorithms are gaining popularity due to their ability to converge swiftly. All these algorithms, in contrast to the conventional Gradient Descent, use statistics from the previous iterations to robustify the process of convergence. An Adaptive Optimization Algorithm uses exponentially weighted averages of gradients over previous iterations to stabilize the convergence, resulting in quicker optimization. For example, in most real-world applications of Deep Neural Networks, the training is carried out on noisy data. It is, therefore, necessary to reduce the effect of noise when the data are fed in batches during Optimization. This problem can be tackled using Exponentially Weighted Averages (or Exponentially Weighted Moving Averages). In order to approximate the trends in a noisy dataset of size N: , we maintain a set of parameters . As we iterate through all the values in the dataset, we calculate the parameters as below: On iteration t: Get next This algorithm averages the value of over its values from previous iterations. This averaging ensures that only the trend is retained and the noise is averaged out. This method is used as a strategy in momentum-based gradient descent to make it robust against noise in data samples, resulting in faster training.As an example, if you were to optimize a function on the parameter , the following pseudo-code illustrates the algorithm: On iteration t: On the current batch, compute The HyperParameters for this Optimization Algorithm are , called the Learning Rate and, , similar to acceleration in mechanics.Following is an implementation of Momentum-based Gradient Descent on a function : Python3 import math # HyperParameters of the optimization algorithmalpha = 0.01beta = 0.9 # Objective functiondef obj_func(x): return x * x - 4 * x + 4 # Gradient of the objective functiondef grad(x): return 2 * x - 4 # Parameter of the objective functionx = 0 # Number of iterationsiterations = 0 v = 0 while (1): iterations += 1 v = beta * v + (1 - beta) * grad(x) x_prev = x x = x - alpha * v print("Value of objective function on iteration", iterations, "is", x) if x_prev == x: print("Done optimizing the objective function. ") break punamsingh628700 Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Nov, 2021" }, { "code": null, "e": 795, "s": 54, "text": "Gradient Descent is an optimization technique used in Machine Learning frameworks to train different models. The training process consists of an objective function (or the error function), which determines the error a Machine Learning model has on a given dataset. While training, the parameters of this algorithm are initialized to random values. As the algorithm iterates, the parameters are updated such that we reach closer and closer to the optimal value of the function.However, Adaptive Optimization Algorithms are gaining popularity due to their ability to converge swiftly. All these algorithms, in contrast to the conventional Gradient Descent, use statistics from the previous iterations to robustify the process of convergence. " }, { "code": null, "e": 1306, "s": 795, "text": "An Adaptive Optimization Algorithm uses exponentially weighted averages of gradients over previous iterations to stabilize the convergence, resulting in quicker optimization. For example, in most real-world applications of Deep Neural Networks, the training is carried out on noisy data. It is, therefore, necessary to reduce the effect of noise when the data are fed in batches during Optimization. This problem can be tackled using Exponentially Weighted Averages (or Exponentially Weighted Moving Averages)." }, { "code": null, "e": 1499, "s": 1306, "text": "In order to approximate the trends in a noisy dataset of size N: , we maintain a set of parameters . As we iterate through all the values in the dataset, we calculate the parameters as below: " }, { "code": null, "e": 1530, "s": 1499, "text": "On iteration t:\n Get next \n" }, { "code": null, "e": 1966, "s": 1530, "text": "This algorithm averages the value of over its values from previous iterations. This averaging ensures that only the trend is retained and the noise is averaged out. This method is used as a strategy in momentum-based gradient descent to make it robust against noise in data samples, resulting in faster training.As an example, if you were to optimize a function on the parameter , the following pseudo-code illustrates the algorithm: " }, { "code": null, "e": 2019, "s": 1966, "text": "On iteration t:\n On the current batch, compute \n\n" }, { "code": null, "e": 2229, "s": 2019, "text": "The HyperParameters for this Optimization Algorithm are , called the Learning Rate and, , similar to acceleration in mechanics.Following is an implementation of Momentum-based Gradient Descent on a function : " }, { "code": null, "e": 2237, "s": 2229, "text": "Python3" }, { "code": "import math # HyperParameters of the optimization algorithmalpha = 0.01beta = 0.9 # Objective functiondef obj_func(x): return x * x - 4 * x + 4 # Gradient of the objective functiondef grad(x): return 2 * x - 4 # Parameter of the objective functionx = 0 # Number of iterationsiterations = 0 v = 0 while (1): iterations += 1 v = beta * v + (1 - beta) * grad(x) x_prev = x x = x - alpha * v print(\"Value of objective function on iteration\", iterations, \"is\", x) if x_prev == x: print(\"Done optimizing the objective function. \") break", "e": 2834, "s": 2237, "text": null }, { "code": null, "e": 2851, "s": 2834, "text": "punamsingh628700" }, { "code": null, "e": 2868, "s": 2851, "text": "Machine Learning" }, { "code": null, "e": 2885, "s": 2868, "text": "Machine Learning" } ]
Python | Print all string combination from given numbers
16 Jan, 2019 Given an integer N as input, the task is to print the all the string combination from it in lexicographical order. Examples: Input : 191 Output : aia sa Explanation: The Possible String digit are 1, 9 and 1 --> aia 19 and 1 --> sa Input : 1119 Output : aaai aas aki kai ks Approach: Get the String and find all its combination list in the given order. Find the list whose integers lies in the range of 0 to 25. Convert the integers to the alphabets. Sort it in lexicographical order. # Python program to print all string# combination from given numbers # Function to find the combinationdef Number_to_String(String): # length of string length = len(String) # temporary lists temp1 =[] temp2 =[] # alphabets Sequence alphabet ="abcdefghijklmnopqrstuvwxyz" # Power variable power = 2**(length-1) for i in range(0, power): # temporary String sub = "" Shift = i x = 0 sub += String[x] x += 1 for j in range(length - 1): if Shift&1: sub+=" " Shift = Shift>>1 sub += String[x] x += 1 temp1.append(list(map(int, sub.split()))) # Integer to String for index in temp1: substring ="" for j in index: if j > 0 and j <= 26: substring += alphabet[j-1] if len(substring) == len(index): temp2.append(substring) # lexicographical order sorting print(*sorted(temp2), sep =" ") # Driver CodeNumber_to_String("191")Number_to_String("1991")Number_to_String("1532")Number_to_String("1191") aia sa aiia sia aecb ocb aaia asa kia Python Python Programs Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jan, 2019" }, { "code": null, "e": 143, "s": 28, "text": "Given an integer N as input, the task is to print the all the string combination from it in lexicographical order." }, { "code": null, "e": 153, "s": 143, "text": "Examples:" }, { "code": null, "e": 306, "s": 153, "text": "Input : 191\nOutput : aia sa\nExplanation: \nThe Possible String digit are \n1, 9 and 1 --> aia\n19 and 1 --> sa\n\nInput : 1119\nOutput : aaai aas aki kai ks\n" }, { "code": null, "e": 316, "s": 306, "text": "Approach:" }, { "code": null, "e": 385, "s": 316, "text": "Get the String and find all its combination list in the given order." }, { "code": null, "e": 444, "s": 385, "text": "Find the list whose integers lies in the range of 0 to 25." }, { "code": null, "e": 483, "s": 444, "text": "Convert the integers to the alphabets." }, { "code": null, "e": 517, "s": 483, "text": "Sort it in lexicographical order." }, { "code": "# Python program to print all string# combination from given numbers # Function to find the combinationdef Number_to_String(String): # length of string length = len(String) # temporary lists temp1 =[] temp2 =[] # alphabets Sequence alphabet =\"abcdefghijklmnopqrstuvwxyz\" # Power variable power = 2**(length-1) for i in range(0, power): # temporary String sub = \"\" Shift = i x = 0 sub += String[x] x += 1 for j in range(length - 1): if Shift&1: sub+=\" \" Shift = Shift>>1 sub += String[x] x += 1 temp1.append(list(map(int, sub.split()))) # Integer to String for index in temp1: substring =\"\" for j in index: if j > 0 and j <= 26: substring += alphabet[j-1] if len(substring) == len(index): temp2.append(substring) # lexicographical order sorting print(*sorted(temp2), sep =\" \") # Driver CodeNumber_to_String(\"191\")Number_to_String(\"1991\")Number_to_String(\"1532\")Number_to_String(\"1191\")", "e": 1693, "s": 517, "text": null }, { "code": null, "e": 1732, "s": 1693, "text": "aia sa\naiia sia\naecb ocb\naaia asa kia\n" }, { "code": null, "e": 1739, "s": 1732, "text": "Python" }, { "code": null, "e": 1755, "s": 1739, "text": "Python Programs" }, { "code": null, "e": 1763, "s": 1755, "text": "Strings" }, { "code": null, "e": 1771, "s": 1763, "text": "Strings" }, { "code": null, "e": 1869, "s": 1771, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1901, "s": 1869, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1928, "s": 1901, "text": "Python Classes and Objects" }, { "code": null, "e": 1959, "s": 1928, "text": "Python | os.path.join() method" }, { "code": null, "e": 1982, "s": 1959, "text": "Introduction To PYTHON" }, { "code": null, "e": 2003, "s": 1982, "text": "Python OOPs Concepts" }, { "code": null, "e": 2025, "s": 2003, "text": "Defaultdict in Python" }, { "code": null, "e": 2064, "s": 2025, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2102, "s": 2064, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2151, "s": 2102, "text": "Python | Convert string dictionary to dictionary" } ]
How to Convert Hex String to Hex Number in C#?
Firstly, set the Hex String − string str = "7D"; Now, use the Convert.ToSByte() method to convert the Hex string to Hex number − Console.WriteLine(Convert.ToSByte(str, 16)); Let us see the complete code − Live Demo using System; namespace Demo { public class Program { public static void Main(string[] args) { string str = "7D"; Console.WriteLine(Convert.ToSByte(str, 16)); } } } 125 Another way of converting Hex String to Hex Number − Live Demo using System; namespace Demo { public class Program { public static void Main(string[] args) { string str = "7D"; Console.WriteLine(Convert.ToInt32(str, 16)); } } } 125
[ { "code": null, "e": 1092, "s": 1062, "text": "Firstly, set the Hex String −" }, { "code": null, "e": 1111, "s": 1092, "text": "string str = \"7D\";" }, { "code": null, "e": 1191, "s": 1111, "text": "Now, use the Convert.ToSByte() method to convert the Hex string to Hex number −" }, { "code": null, "e": 1236, "s": 1191, "text": "Console.WriteLine(Convert.ToSByte(str, 16));" }, { "code": null, "e": 1267, "s": 1236, "text": "Let us see the complete code −" }, { "code": null, "e": 1278, "s": 1267, "text": " Live Demo" }, { "code": null, "e": 1480, "s": 1278, "text": "using System;\n\nnamespace Demo {\n public class Program {\n public static void Main(string[] args) {\n string str = \"7D\";\n Console.WriteLine(Convert.ToSByte(str, 16));\n }\n }\n}" }, { "code": null, "e": 1484, "s": 1480, "text": "125" }, { "code": null, "e": 1537, "s": 1484, "text": "Another way of converting Hex String to Hex Number −" }, { "code": null, "e": 1548, "s": 1537, "text": " Live Demo" }, { "code": null, "e": 1750, "s": 1548, "text": "using System;\n\nnamespace Demo {\n public class Program {\n public static void Main(string[] args) {\n string str = \"7D\";\n Console.WriteLine(Convert.ToInt32(str, 16));\n }\n }\n}" }, { "code": null, "e": 1754, "s": 1750, "text": "125" } ]
Arduino - for loop
A for loop executes statements a predetermined number of times. The control expression for the loop is initialized, tested and manipulated entirely within the for loop parentheses. It is easy to debug the looping behavior of the structure as it is independent of the activity inside the loop. Each for loop has up to three expressions, which determine its operation. The following example shows general for loop syntax. Notice that the three expressions in the for loop argument parentheses are separated with semicolons. for ( initialize; control; increment or decrement) { // statement block } for(counter = 2;counter <= 9;counter++) { //statements block will executed 10 times } 65 Lectures 6.5 hours Amit Rana 43 Lectures 3 hours Amit Rana 20 Lectures 2 hours Ashraf Said 19 Lectures 1.5 hours Ashraf Said 11 Lectures 47 mins Ashraf Said 9 Lectures 41 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 3163, "s": 2870, "text": "A for loop executes statements a predetermined number of times. The control expression for the loop is initialized, tested and manipulated entirely within the for loop parentheses. It is easy to debug the looping behavior of the structure as it is independent of the activity inside the loop." }, { "code": null, "e": 3392, "s": 3163, "text": "Each for loop has up to three expressions, which determine its operation. The following example shows general for loop syntax. Notice that the three expressions in the for loop argument parentheses are separated with semicolons." }, { "code": null, "e": 3470, "s": 3392, "text": "for ( initialize; control; increment or decrement) {\n // statement block\n}\n" }, { "code": null, "e": 3559, "s": 3470, "text": "for(counter = 2;counter <= 9;counter++) {\n //statements block will executed 10 times\n}" }, { "code": null, "e": 3594, "s": 3559, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3605, "s": 3594, "text": " Amit Rana" }, { "code": null, "e": 3638, "s": 3605, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 3649, "s": 3638, "text": " Amit Rana" }, { "code": null, "e": 3682, "s": 3649, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 3695, "s": 3682, "text": " Ashraf Said" }, { "code": null, "e": 3730, "s": 3695, "text": "\n 19 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3743, "s": 3730, "text": " Ashraf Said" }, { "code": null, "e": 3775, "s": 3743, "text": "\n 11 Lectures \n 47 mins\n" }, { "code": null, "e": 3788, "s": 3775, "text": " Ashraf Said" }, { "code": null, "e": 3819, "s": 3788, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 3832, "s": 3819, "text": " Ashraf Said" }, { "code": null, "e": 3839, "s": 3832, "text": " Print" }, { "code": null, "e": 3850, "s": 3839, "text": " Add Notes" } ]
Python program to delete a new node from the beginning of the doubly linked list
When it is required to delete a node from the beginning of a doubly linked list, a ‘Node’ class needs to be created. In this class, there are three attributes, the data that is present in the node, the access to the next node of the linked list, and the access to the previous node of the linked list. Below is a demonstration for the same − Live Demo class Node: def __init__(self, my_data): self.prev = None self.data = my_data self.next = None class double_list: def __init__(self): self.head = None self.tail = None def add_data(self, my_data): new_node = Node(my_data) if(self.head == None): self.head = self.tail = new_node; self.head.previous = None; self.tail.next = None; else: self.tail.next = new_node; new_node.previous = self.tail; self.tail = new_node; self.tail.next = None; def print_it(self): curr = self.head if (self.head == None): print("The list is empty") return print("The nodes in the doubly linked list are :") while curr != None: print(curr.data) curr = curr.next def delete_from_beginning(self): if(self.head == None): return; else: if(self.head != self.tail): self.head = self.head.next; self.head.previous = None; else: self.head = self.tail = None; my_instance = double_list() print("Elements are being added to the doubly linked list") my_instance.add_data(10) my_instance.add_data(24) my_instance.add_data(54) my_instance.add_data(77) my_instance.add_data(92) my_instance.print_it() while(my_instance.head != None): my_instance.delete_from_beginning(); print("The list after deleting the element from the beginning is : "); my_instance.print_it(); Elements are being added to the doubly linked list The nodes in the doubly linked list are : 10 24 54 77 92 The list after deleting the element from the beginning is : The nodes in the doubly linked list are : 24 54 77 92 The list after deleting the element from the beginning is : The nodes in the doubly linked list are : 54 77 92 The list after deleting the element from the beginning is : The nodes in the doubly linked list are : 77 92 The list after deleting the element from the beginning is : The nodes in the doubly linked list are : 92 The list after deleting the element from the beginning is : The list is empty The ‘Node’ class is created. Another class with required attributes is created. A method named ‘add_data’ is defined, that is used to add data to the doubly linked list. Another method named ‘print_it’ is defined, that displays the nodes of the circular linked list. Another method named ‘delete_from_beginning’ is defined, that deletes the node from the beginning, i.e the ‘head’ node and makes the next node as the head node in the circular linked list. An object of the ‘double_list’ class is created, and the methods are called on it to delete a node from the beginning of the doubly linked list. An ‘init’ method is defined, that the root, head, and tail nodes of the doubly linked list to None. The list is iterated over, and every node from the beginning is deleted until its empty. This is displayed on the console using the ‘print_it’ method.
[ { "code": null, "e": 1364, "s": 1062, "text": "When it is required to delete a node from the beginning of a doubly linked list, a ‘Node’ class needs to be created. In this class, there are three attributes, the data that is present in the node, the access to the next node of the linked list, and the access to the previous node of the linked list." }, { "code": null, "e": 1404, "s": 1364, "text": "Below is a demonstration for the same −" }, { "code": null, "e": 1415, "s": 1404, "text": " Live Demo" }, { "code": null, "e": 2904, "s": 1415, "text": "class Node:\n def __init__(self, my_data):\n self.prev = None\n self.data = my_data\n self.next = None\nclass double_list:\n def __init__(self):\n self.head = None\n self.tail = None\n def add_data(self, my_data):\n new_node = Node(my_data)\n if(self.head == None):\n self.head = self.tail = new_node;\n self.head.previous = None;\n self.tail.next = None;\n else:\n self.tail.next = new_node;\n new_node.previous = self.tail;\n self.tail = new_node;\n self.tail.next = None;\n def print_it(self):\n curr = self.head\n if (self.head == None):\n print(\"The list is empty\")\n return\n print(\"The nodes in the doubly linked list are :\")\n while curr != None:\n print(curr.data)\n curr = curr.next\n def delete_from_beginning(self):\n if(self.head == None):\n return;\n else:\n if(self.head != self.tail):\n self.head = self.head.next;\n self.head.previous = None;\n else:\n self.head = self.tail = None;\nmy_instance = double_list()\nprint(\"Elements are being added to the doubly linked list\")\nmy_instance.add_data(10)\nmy_instance.add_data(24)\nmy_instance.add_data(54)\nmy_instance.add_data(77)\nmy_instance.add_data(92)\nmy_instance.print_it()\nwhile(my_instance.head != None):\nmy_instance.delete_from_beginning();\nprint(\"The list after deleting the element from the beginning is : \");\nmy_instance.print_it();" }, { "code": null, "e": 3528, "s": 2904, "text": "Elements are being added to the doubly linked list\nThe nodes in the doubly linked list are :\n10\n24\n54\n77\n92\nThe list after deleting the element from the beginning is :\nThe nodes in the doubly linked list are :\n24\n54\n77\n92\nThe list after deleting the element from the beginning is :\nThe nodes in the doubly linked list are :\n54\n77\n92\nThe list after deleting the element from the beginning is :\nThe nodes in the doubly linked list are :\n77\n92\nThe list after deleting the element from the beginning is :\nThe nodes in the doubly linked list are :\n92\nThe list after deleting the element from the beginning is :\nThe list is empty" }, { "code": null, "e": 3557, "s": 3528, "text": "The ‘Node’ class is created." }, { "code": null, "e": 3608, "s": 3557, "text": "Another class with required attributes is created." }, { "code": null, "e": 3698, "s": 3608, "text": "A method named ‘add_data’ is defined, that is used to add data to the doubly linked list." }, { "code": null, "e": 3795, "s": 3698, "text": "Another method named ‘print_it’ is defined, that displays the nodes of the circular linked list." }, { "code": null, "e": 3984, "s": 3795, "text": "Another method named ‘delete_from_beginning’ is defined, that deletes the node from the beginning, i.e the ‘head’ node and makes the next node as the head node in the circular linked list." }, { "code": null, "e": 4129, "s": 3984, "text": "An object of the ‘double_list’ class is created, and the methods are called on it to delete a node from the beginning of the doubly linked list." }, { "code": null, "e": 4229, "s": 4129, "text": "An ‘init’ method is defined, that the root, head, and tail nodes of the doubly linked list to None." }, { "code": null, "e": 4318, "s": 4229, "text": "The list is iterated over, and every node from the beginning is deleted until its empty." }, { "code": null, "e": 4380, "s": 4318, "text": "This is displayed on the console using the ‘print_it’ method." } ]
Implementation of Deque using doubly linked list - GeeksforGeeks
14 Jan, 2021 Deque or Double Ended Queue is a generalized version of Queue data structure that allows insert and delete at both ends. In previous post Implementation of Deque using circular array has been discussed. Now in this post we see how we implement Deque using Doubly Linked List. Mainly the following four basic operations are performed on queue : insertFront() : Adds an item at the front of Deque. insertRear() : Adds an item at the rear of Deque. deleteFront() : Deletes an item from front of Deque. deleteRear() : Deletes an item from rear of Deque. In addition to above operations, following operations are also supported : getFront() : Gets the front item from queue. getRear() : Gets the last item from queue. isEmpty() : Checks whether Deque is empty or not. size() : Gets number of elements in Deque. erase() : Deletes all the elements from Deque. Doubly Linked List Representation of Deque : For implementing deque, we need to keep track of two pointers, front and rear. We enqueue (push) an item at the rear or the front end of deque and dequeue(pop) an item from both rear and front end.Working : Declare two pointers front and rear of type Node, where Node represents the structure of a node of a doubly linked list. Initialize both of them with value NULL.Insertion at Front end : 1. Allocate space for a newNode of doubly linked list. 2. IF newNode == NULL, then 3. print "Overflow" 4. ELSE 5. IF front == NULL, then 6. rear = front = newNode 7. ELSE 8. newNode->next = front 9. front->prev = newNode 10. front = newNode Insertion at Rear end : 1. Allocate space for a newNode of doubly linked list. 2. IF newNode == NULL, then 3. print "Overflow" 4. ELSE 5. IF rear == NULL, then 6. front = rear = newNode 7. ELSE 8. newNode->prev = rear 9. rear->next = newNode 10. rear = newNode Deletion from Front end : 1. IF front == NULL 2. print "Underflow" 3. ELSE 4. Initialize temp = front 5. front = front->next 6. IF front == NULL 7. rear = NULL 8. ELSE 9. front->prev = NULL 10 Deallocate space for temp Deletion from Rear end : 1. IF front == NULL 2. print "Underflow" 3. ELSE 4. Initialize temp = rear 5. rear = rear->prev 6. IF rear == NULL 7. front = NULL 8. ELSE 9. rear->next = NULL 10 Deallocate space for temp CPP Java // C++ implementation of Deque using// doubly linked list#include <bits/stdc++.h> using namespace std; // Node of a doubly linked liststruct Node{ int data; Node *prev, *next; // Function to get a new node static Node* getnode(int data) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; newNode->prev = newNode->next = NULL; return newNode; }}; // A structure to represent a dequeclass Deque{ Node* front; Node* rear; int Size; public: Deque() { front = rear = NULL; Size = 0; } // Operations on Deque void insertFront(int data); void insertRear(int data); void deleteFront(); void deleteRear(); int getFront(); int getRear(); int size(); bool isEmpty(); void erase();}; // Function to check whether deque// is empty or notbool Deque::isEmpty(){ return (front == NULL);} // Function to return the number of// elements in the dequeint Deque::size(){ return Size;} // Function to insert an element// at the front endvoid Deque::insertFront(int data){ Node* newNode = Node::getnode(data); // If true then new element cannot be added // and it is an 'Overflow' condition if (newNode == NULL) cout << "OverFlow\n"; else { // If deque is empty if (front == NULL) rear = front = newNode; // Inserts node at the front end else { newNode->next = front; front->prev = newNode; front = newNode; } // Increments count of elements by 1 Size++; }} // Function to insert an element// at the rear endvoid Deque::insertRear(int data){ Node* newNode = Node::getnode(data); // If true then new element cannot be added // and it is an 'Overflow' condition if (newNode == NULL) cout << "OverFlow\n"; else { // If deque is empty if (rear == NULL) front = rear = newNode; // Inserts node at the rear end else { newNode->prev = rear; rear->next = newNode; rear = newNode; } Size++; }} // Function to delete the element// from the front endvoid Deque::deleteFront(){ // If deque is empty then // 'Underflow' condition if (isEmpty()) cout << "UnderFlow\n"; // Deletes the node from the front end and makes // the adjustment in the links else { Node* temp = front; front = front->next; // If only one element was present if (front == NULL) rear = NULL; else front->prev = NULL; free(temp); // Decrements count of elements by 1 Size--; }} // Function to delete the element// from the rear endvoid Deque::deleteRear(){ // If deque is empty then // 'Underflow' condition if (isEmpty()) cout << "UnderFlow\n"; // Deletes the node from the rear end and makes // the adjustment in the links else { Node* temp = rear; rear = rear->prev; // If only one element was present if (rear == NULL) front = NULL; else rear->next = NULL; free(temp); // Decrements count of elements by 1 Size--; }} // Function to return the element// at the front endint Deque::getFront(){ // If deque is empty, then returns // garbage value if (isEmpty()) return -1; return front->data;} // Function to return the element// at the rear endint Deque::getRear(){ // If deque is empty, then returns // garbage value if (isEmpty()) return -1; return rear->data;} // Function to delete all the elements// from Dequevoid Deque::erase(){ rear = NULL; while (front != NULL) { Node* temp = front; front = front->next; free(temp); } Size = 0;} // Driver program to test aboveint main(){ Deque dq; cout << "Insert element '5' at rear end\n"; dq.insertRear(5); cout << "Insert element '10' at rear end\n"; dq.insertRear(10); cout << "Rear end element: " << dq.getRear() << endl; dq.deleteRear(); cout << "After deleting rear element new rear" << " is: " << dq.getRear() << endl; cout << "Inserting element '15' at front end \n"; dq.insertFront(15); cout << "Front end element: " << dq.getFront() << endl; cout << "Number of elements in Deque: " << dq.size() << endl; dq.deleteFront(); cout << "After deleting front element new " << "front is: " << dq.getFront() << endl; return 0;} // Java implementation of Deque using// doubly linked listimport java.util.*;class GFG{ // Node of a doubly linked list static class Node { int data; Node prev, next; // Function to get a new node static Node getnode(int data) { Node newNode = new Node(); newNode.data = data; newNode.prev = newNode.next = null; return newNode; } }; // A structure to represent a deque static class Deque { Node front; Node rear; int Size; Deque() { front = rear = null; Size = 0; } // Function to check whether deque // is empty or not boolean isEmpty() { return (front == null); } // Function to return the number of // elements in the deque int size() { return Size; } // Function to insert an element // at the front end void insertFront(int data) { Node newNode = Node.getnode(data); // If true then new element cannot be added // and it is an 'Overflow' condition if (newNode == null) System.out.print("OverFlow\n"); else { // If deque is empty if (front == null) rear = front = newNode; // Inserts node at the front end else { newNode.next = front; front.prev = newNode; front = newNode; } // Increments count of elements by 1 Size++; } } // Function to insert an element // at the rear end void insertRear(int data) { Node newNode = Node.getnode(data); // If true then new element cannot be added // and it is an 'Overflow' condition if (newNode == null) System.out.print("OverFlow\n"); else { // If deque is empty if (rear == null) front = rear = newNode; // Inserts node at the rear end else { newNode.prev = rear; rear.next = newNode; rear = newNode; } Size++; } } // Function to delete the element // from the front end void deleteFront() { // If deque is empty then // 'Underflow' condition if (isEmpty()) System.out.print("UnderFlow\n"); // Deletes the node from the front end and makes // the adjustment in the links else { Node temp = front; front = front.next; // If only one element was present if (front == null) rear = null; else front.prev = null; // Decrements count of elements by 1 Size--; } } // Function to delete the element // from the rear end void deleteRear() { // If deque is empty then // 'Underflow' condition if (isEmpty()) System.out.print("UnderFlow\n"); // Deletes the node from the rear end and makes // the adjustment in the links else { Node temp = rear; rear = rear.prev; // If only one element was present if (rear == null) front = null; else rear.next = null; // Decrements count of elements by 1 Size--; } } // Function to return the element // at the front end int getFront() { // If deque is empty, then returns // garbage value if (isEmpty()) return -1; return front.data; } // Function to return the element // at the rear end int getRear() { // If deque is empty, then returns // garbage value if (isEmpty()) return -1; return rear.data; } // Function to delete all the elements // from Deque void erase() { rear = null; while (front != null) { Node temp = front; front = front.next; } Size = 0; } } // Driver program to test above public static void main(String[] args) { Deque dq = new Deque(); System.out.print( "Insert element '5' at rear end\n"); dq.insertRear(5); System.out.print( "Insert element '10' at rear end\n"); dq.insertRear(10); System.out.print("Rear end element: " + dq.getRear() + "\n"); dq.deleteRear(); System.out.print( "After deleting rear element new rear" + " is: " + dq.getRear() + "\n"); System.out.print( "Inserting element '15' at front end \n"); dq.insertFront(15); System.out.print( "Front end element: " + dq.getFront() + "\n"); System.out.print("Number of elements in Deque: " + dq.size() + "\n"); dq.deleteFront(); System.out.print("After deleting front element new " + "front is: " + dq.getFront() + "\n"); }} // This code is contributed by gauravrajput1 Output : Insert element '5' at rear end Insert element '10' at rear end Rear end element: 10 After deleting rear element new rear is: 5 Inserting element '15' at front end Front end element: 15 Number of elements in Deque: 2 After deleting front element new front is: 5 Time Complexity : Time complexity of operations like insertFront(), insertRear(), deleteFront(), deleteRear()is O(1). Time Complexity of erase() is O(n). Akanksha_Rai GauravRajput1 deque Linked List Queue Linked List Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments LinkedList in Java Doubly Linked List | Set 1 (Introduction and Insertion) Linked List vs Array Delete a Linked List node at a given position Implementing a Linked List in Java using Class Breadth First Search or BFS for a Graph Level Order Binary Tree Traversal Queue in Python Queue Interface In Java Priority Queue | Set 1 (Introduction)
[ { "code": null, "e": 25150, "s": 25122, "text": "\n14 Jan, 2021" }, { "code": null, "e": 25427, "s": 25150, "text": "Deque or Double Ended Queue is a generalized version of Queue data structure that allows insert and delete at both ends. In previous post Implementation of Deque using circular array has been discussed. Now in this post we see how we implement Deque using Doubly Linked List. " }, { "code": null, "e": 25497, "s": 25427, "text": "Mainly the following four basic operations are performed on queue : " }, { "code": null, "e": 25705, "s": 25497, "text": "insertFront() : Adds an item at the front of Deque.\ninsertRear() : Adds an item at the rear of Deque.\ndeleteFront() : Deletes an item from front of Deque.\ndeleteRear() : Deletes an item from rear of Deque." }, { "code": null, "e": 25782, "s": 25705, "text": "In addition to above operations, following operations are also supported : " }, { "code": null, "e": 26019, "s": 25782, "text": "getFront() : Gets the front item from queue.\ngetRear() : Gets the last item from queue.\nisEmpty() : Checks whether Deque is empty or not.\nsize() : Gets number of elements in Deque.\nerase() : Deletes all the elements from Deque." }, { "code": null, "e": 26463, "s": 26023, "text": "Doubly Linked List Representation of Deque : For implementing deque, we need to keep track of two pointers, front and rear. We enqueue (push) an item at the rear or the front end of deque and dequeue(pop) an item from both rear and front end.Working : Declare two pointers front and rear of type Node, where Node represents the structure of a node of a doubly linked list. Initialize both of them with value NULL.Insertion at Front end : " }, { "code": null, "e": 26746, "s": 26463, "text": "1. Allocate space for a newNode of doubly linked list.\n2. IF newNode == NULL, then\n3. print \"Overflow\"\n4. ELSE\n5. IF front == NULL, then\n6. rear = front = newNode\n7. ELSE\n8. newNode->next = front\n9. front->prev = newNode\n10. front = newNode " }, { "code": null, "e": 26772, "s": 26746, "text": "Insertion at Rear end : " }, { "code": null, "e": 27051, "s": 26772, "text": "1. Allocate space for a newNode of doubly linked list.\n2. IF newNode == NULL, then\n3. print \"Overflow\"\n4. ELSE\n5. IF rear == NULL, then\n6. front = rear = newNode\n7. ELSE\n8. newNode->prev = rear\n9. rear->next = newNode\n10. rear = newNode " }, { "code": null, "e": 27079, "s": 27051, "text": "Deletion from Front end : " }, { "code": null, "e": 27312, "s": 27079, "text": "1. IF front == NULL\n2. print \"Underflow\"\n3. ELSE\n4. Initialize temp = front\n5. front = front->next\n6. IF front == NULL\n7. rear = NULL\n8. ELSE\n9. front->prev = NULL\n10 Deallocate space for temp" }, { "code": null, "e": 27339, "s": 27312, "text": "Deletion from Rear end : " }, { "code": null, "e": 27568, "s": 27339, "text": "1. IF front == NULL\n2. print \"Underflow\"\n3. ELSE\n4. Initialize temp = rear\n5. rear = rear->prev\n6. IF rear == NULL\n7. front = NULL\n8. ELSE\n9. rear->next = NULL\n10 Deallocate space for temp" }, { "code": null, "e": 27574, "s": 27570, "text": "CPP" }, { "code": null, "e": 27579, "s": 27574, "text": "Java" }, { "code": "// C++ implementation of Deque using// doubly linked list#include <bits/stdc++.h> using namespace std; // Node of a doubly linked liststruct Node{ int data; Node *prev, *next; // Function to get a new node static Node* getnode(int data) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; newNode->prev = newNode->next = NULL; return newNode; }}; // A structure to represent a dequeclass Deque{ Node* front; Node* rear; int Size; public: Deque() { front = rear = NULL; Size = 0; } // Operations on Deque void insertFront(int data); void insertRear(int data); void deleteFront(); void deleteRear(); int getFront(); int getRear(); int size(); bool isEmpty(); void erase();}; // Function to check whether deque// is empty or notbool Deque::isEmpty(){ return (front == NULL);} // Function to return the number of// elements in the dequeint Deque::size(){ return Size;} // Function to insert an element// at the front endvoid Deque::insertFront(int data){ Node* newNode = Node::getnode(data); // If true then new element cannot be added // and it is an 'Overflow' condition if (newNode == NULL) cout << \"OverFlow\\n\"; else { // If deque is empty if (front == NULL) rear = front = newNode; // Inserts node at the front end else { newNode->next = front; front->prev = newNode; front = newNode; } // Increments count of elements by 1 Size++; }} // Function to insert an element// at the rear endvoid Deque::insertRear(int data){ Node* newNode = Node::getnode(data); // If true then new element cannot be added // and it is an 'Overflow' condition if (newNode == NULL) cout << \"OverFlow\\n\"; else { // If deque is empty if (rear == NULL) front = rear = newNode; // Inserts node at the rear end else { newNode->prev = rear; rear->next = newNode; rear = newNode; } Size++; }} // Function to delete the element// from the front endvoid Deque::deleteFront(){ // If deque is empty then // 'Underflow' condition if (isEmpty()) cout << \"UnderFlow\\n\"; // Deletes the node from the front end and makes // the adjustment in the links else { Node* temp = front; front = front->next; // If only one element was present if (front == NULL) rear = NULL; else front->prev = NULL; free(temp); // Decrements count of elements by 1 Size--; }} // Function to delete the element// from the rear endvoid Deque::deleteRear(){ // If deque is empty then // 'Underflow' condition if (isEmpty()) cout << \"UnderFlow\\n\"; // Deletes the node from the rear end and makes // the adjustment in the links else { Node* temp = rear; rear = rear->prev; // If only one element was present if (rear == NULL) front = NULL; else rear->next = NULL; free(temp); // Decrements count of elements by 1 Size--; }} // Function to return the element// at the front endint Deque::getFront(){ // If deque is empty, then returns // garbage value if (isEmpty()) return -1; return front->data;} // Function to return the element// at the rear endint Deque::getRear(){ // If deque is empty, then returns // garbage value if (isEmpty()) return -1; return rear->data;} // Function to delete all the elements// from Dequevoid Deque::erase(){ rear = NULL; while (front != NULL) { Node* temp = front; front = front->next; free(temp); } Size = 0;} // Driver program to test aboveint main(){ Deque dq; cout << \"Insert element '5' at rear end\\n\"; dq.insertRear(5); cout << \"Insert element '10' at rear end\\n\"; dq.insertRear(10); cout << \"Rear end element: \" << dq.getRear() << endl; dq.deleteRear(); cout << \"After deleting rear element new rear\" << \" is: \" << dq.getRear() << endl; cout << \"Inserting element '15' at front end \\n\"; dq.insertFront(15); cout << \"Front end element: \" << dq.getFront() << endl; cout << \"Number of elements in Deque: \" << dq.size() << endl; dq.deleteFront(); cout << \"After deleting front element new \" << \"front is: \" << dq.getFront() << endl; return 0;}", "e": 32162, "s": 27579, "text": null }, { "code": "// Java implementation of Deque using// doubly linked listimport java.util.*;class GFG{ // Node of a doubly linked list static class Node { int data; Node prev, next; // Function to get a new node static Node getnode(int data) { Node newNode = new Node(); newNode.data = data; newNode.prev = newNode.next = null; return newNode; } }; // A structure to represent a deque static class Deque { Node front; Node rear; int Size; Deque() { front = rear = null; Size = 0; } // Function to check whether deque // is empty or not boolean isEmpty() { return (front == null); } // Function to return the number of // elements in the deque int size() { return Size; } // Function to insert an element // at the front end void insertFront(int data) { Node newNode = Node.getnode(data); // If true then new element cannot be added // and it is an 'Overflow' condition if (newNode == null) System.out.print(\"OverFlow\\n\"); else { // If deque is empty if (front == null) rear = front = newNode; // Inserts node at the front end else { newNode.next = front; front.prev = newNode; front = newNode; } // Increments count of elements by 1 Size++; } } // Function to insert an element // at the rear end void insertRear(int data) { Node newNode = Node.getnode(data); // If true then new element cannot be added // and it is an 'Overflow' condition if (newNode == null) System.out.print(\"OverFlow\\n\"); else { // If deque is empty if (rear == null) front = rear = newNode; // Inserts node at the rear end else { newNode.prev = rear; rear.next = newNode; rear = newNode; } Size++; } } // Function to delete the element // from the front end void deleteFront() { // If deque is empty then // 'Underflow' condition if (isEmpty()) System.out.print(\"UnderFlow\\n\"); // Deletes the node from the front end and makes // the adjustment in the links else { Node temp = front; front = front.next; // If only one element was present if (front == null) rear = null; else front.prev = null; // Decrements count of elements by 1 Size--; } } // Function to delete the element // from the rear end void deleteRear() { // If deque is empty then // 'Underflow' condition if (isEmpty()) System.out.print(\"UnderFlow\\n\"); // Deletes the node from the rear end and makes // the adjustment in the links else { Node temp = rear; rear = rear.prev; // If only one element was present if (rear == null) front = null; else rear.next = null; // Decrements count of elements by 1 Size--; } } // Function to return the element // at the front end int getFront() { // If deque is empty, then returns // garbage value if (isEmpty()) return -1; return front.data; } // Function to return the element // at the rear end int getRear() { // If deque is empty, then returns // garbage value if (isEmpty()) return -1; return rear.data; } // Function to delete all the elements // from Deque void erase() { rear = null; while (front != null) { Node temp = front; front = front.next; } Size = 0; } } // Driver program to test above public static void main(String[] args) { Deque dq = new Deque(); System.out.print( \"Insert element '5' at rear end\\n\"); dq.insertRear(5); System.out.print( \"Insert element '10' at rear end\\n\"); dq.insertRear(10); System.out.print(\"Rear end element: \" + dq.getRear() + \"\\n\"); dq.deleteRear(); System.out.print( \"After deleting rear element new rear\" + \" is: \" + dq.getRear() + \"\\n\"); System.out.print( \"Inserting element '15' at front end \\n\"); dq.insertFront(15); System.out.print( \"Front end element: \" + dq.getFront() + \"\\n\"); System.out.print(\"Number of elements in Deque: \" + dq.size() + \"\\n\"); dq.deleteFront(); System.out.print(\"After deleting front element new \" + \"front is: \" + dq.getFront() + \"\\n\"); }} // This code is contributed by gauravrajput1", "e": 36808, "s": 32162, "text": null }, { "code": null, "e": 36819, "s": 36808, "text": "Output : " }, { "code": null, "e": 37080, "s": 36819, "text": "Insert element '5' at rear end\nInsert element '10' at rear end\nRear end element: 10\nAfter deleting rear element new rear is: 5\nInserting element '15' at front end\nFront end element: 15\nNumber of elements in Deque: 2\nAfter deleting front element new front is: 5" }, { "code": null, "e": 37235, "s": 37080, "text": "Time Complexity : Time complexity of operations like insertFront(), insertRear(), deleteFront(), deleteRear()is O(1). Time Complexity of erase() is O(n). " }, { "code": null, "e": 37248, "s": 37235, "text": "Akanksha_Rai" }, { "code": null, "e": 37262, "s": 37248, "text": "GauravRajput1" }, { "code": null, "e": 37268, "s": 37262, "text": "deque" }, { "code": null, "e": 37280, "s": 37268, "text": "Linked List" }, { "code": null, "e": 37286, "s": 37280, "text": "Queue" }, { "code": null, "e": 37298, "s": 37286, "text": "Linked List" }, { "code": null, "e": 37304, "s": 37298, "text": "Queue" }, { "code": null, "e": 37402, "s": 37304, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37411, "s": 37402, "text": "Comments" }, { "code": null, "e": 37424, "s": 37411, "text": "Old Comments" }, { "code": null, "e": 37443, "s": 37424, "text": "LinkedList in Java" }, { "code": null, "e": 37499, "s": 37443, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 37520, "s": 37499, "text": "Linked List vs Array" }, { "code": null, "e": 37566, "s": 37520, "text": "Delete a Linked List node at a given position" }, { "code": null, "e": 37613, "s": 37566, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 37653, "s": 37613, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 37687, "s": 37653, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 37703, "s": 37687, "text": "Queue in Python" }, { "code": null, "e": 37727, "s": 37703, "text": "Queue Interface In Java" } ]
\dot - Tex Command
\dot - Used to draw dot accent over the argument. { \dot #1 } \dot command draws dot accent over the argument. \dot x x ̇ \dot x x ̇ \dot x 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8036, "s": 7986, "text": "\\dot - Used to draw dot accent over the argument." }, { "code": null, "e": 8048, "s": 8036, "text": "{ \\dot #1 }" }, { "code": null, "e": 8097, "s": 8048, "text": "\\dot command draws dot accent over the argument." }, { "code": null, "e": 8113, "s": 8097, "text": "\n\\dot x\n\nx ̇\n\n\n" }, { "code": null, "e": 8127, "s": 8113, "text": "\\dot x\n\nx ̇\n\n" }, { "code": null, "e": 8134, "s": 8127, "text": "\\dot x" }, { "code": null, "e": 8166, "s": 8134, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8179, "s": 8166, "text": " Ashraf Said" }, { "code": null, "e": 8212, "s": 8179, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8225, "s": 8212, "text": " Ashraf Said" }, { "code": null, "e": 8257, "s": 8225, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8293, "s": 8257, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8328, "s": 8293, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8345, "s": 8328, "text": " Mohammad Nauman" }, { "code": null, "e": 8378, "s": 8345, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8392, "s": 8378, "text": " Daniel Stern" }, { "code": null, "e": 8424, "s": 8392, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 8439, "s": 8424, "text": " Nishant Kumar" }, { "code": null, "e": 8446, "s": 8439, "text": " Print" }, { "code": null, "e": 8457, "s": 8446, "text": " Add Notes" } ]
How to set alternate table row color using CSS? - GeeksforGeeks
30 Jul, 2021 The :nth-child() selector in CSS is used to match the elements based on their position in a group of siblings. It matches every element that is the nth-child. Syntax: :nth-child(number) { // CSS Property } Where number is the argument that represents the pattern for matching elements. It can be odd, even or in a functional notation. odd: It represents the elements whose position is odd in a series: 1, 3, 5, etc.Syntax: element:nth-child(even) even: It represents the elements whose position is even in a series: 2, 4, 6, etc.Syntax: element:nth-child(odd) Example 1: It sets the color to alternate even rows in a table. html <!DOCTYPE html><html> <head> <!-- CSS style to set alternate table row using color --> <style> table { border-collapse: collapse; width: 100%; } th, td { text-align: left; padding: 8px; } tr:nth-child(even) { background-color: Lightgreen; } </style></head> <body> <table> <tr> <th>Name</th> <th>Designation</th> <th>Salary</th> </tr> <tr> <td>Steve</td> <td>Manager</td> <td>1,00,000</td> </tr> <tr> <td>SURAJ</td> <td>Assistant Manager</td> <td>50,000</td> </tr> <tr> <td>Khushboo</td> <td>Analysist</td> <td>65,000</td> </tr> <tr> <td>Kartik</td> <td>Worker</td> <td>20,000</td> </tr> <tr> <td>Saksham</td> <td>Worker</td> <td>20,000</td> </tr> </table></body> </html> Output: Example 2: It sets the color to alternate odd rows in a table. html <!DOCTYPE html><html> <head> <title> Set alternate row in table </title> <style> table { border-collapse: collapse; width: 100%; } th, td { text-align: left; padding: 8px; } tr:nth-child(odd) { background-color: Lightgreen; } </style></head> <body> <table> <tr> <th>Name</th> <th>Designation</th> <th>Salary</th> </tr> <tr> <td>Steve</td> <td>Manager</td> <td>1, 00, 000</td> </tr> <tr> <td>SURAJ</td> <td>Assistant Manager</td> <td>50, 000</td> </tr> <tr> <td>Khushboo</td> <td>Analysist</td> <td>65, 000</td> </tr> <tr> <td>Kartik</td> <td>Worker</td> <td>20, 000</td> </tr> <tr> <td>Saksham</td> <td>Worker</td> <td>20, 000</td> </tr> </table></body> <html> Output: Supported Browser: Google Chrome 4.0 Internet Explorer 9.0 Firefox 3.5 Opera 9.6 Safari 3.2 CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. ysachin2314 CSS-Misc Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Create a Responsive Navbar using ReactJS Form validation using jQuery How to apply style to parent if it has child with CSS? How to auto-resize an image to fit a div container using CSS? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 24960, "s": 24932, "text": "\n30 Jul, 2021" }, { "code": null, "e": 25129, "s": 24960, "text": "The :nth-child() selector in CSS is used to match the elements based on their position in a group of siblings. It matches every element that is the nth-child. Syntax: " }, { "code": null, "e": 25172, "s": 25129, "text": ":nth-child(number) {\n // CSS Property\n}" }, { "code": null, "e": 25303, "s": 25172, "text": "Where number is the argument that represents the pattern for matching elements. It can be odd, even or in a functional notation. " }, { "code": null, "e": 25392, "s": 25303, "text": "odd: It represents the elements whose position is odd in a series: 1, 3, 5, etc.Syntax: " }, { "code": null, "e": 25416, "s": 25392, "text": "element:nth-child(even)" }, { "code": null, "e": 25507, "s": 25416, "text": "even: It represents the elements whose position is even in a series: 2, 4, 6, etc.Syntax: " }, { "code": null, "e": 25530, "s": 25507, "text": "element:nth-child(odd)" }, { "code": null, "e": 25596, "s": 25530, "text": "Example 1: It sets the color to alternate even rows in a table. " }, { "code": null, "e": 25601, "s": 25596, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <!-- CSS style to set alternate table row using color --> <style> table { border-collapse: collapse; width: 100%; } th, td { text-align: left; padding: 8px; } tr:nth-child(even) { background-color: Lightgreen; } </style></head> <body> <table> <tr> <th>Name</th> <th>Designation</th> <th>Salary</th> </tr> <tr> <td>Steve</td> <td>Manager</td> <td>1,00,000</td> </tr> <tr> <td>SURAJ</td> <td>Assistant Manager</td> <td>50,000</td> </tr> <tr> <td>Khushboo</td> <td>Analysist</td> <td>65,000</td> </tr> <tr> <td>Kartik</td> <td>Worker</td> <td>20,000</td> </tr> <tr> <td>Saksham</td> <td>Worker</td> <td>20,000</td> </tr> </table></body> </html>", "e": 26761, "s": 25601, "text": null }, { "code": null, "e": 26770, "s": 26761, "text": "Output: " }, { "code": null, "e": 26834, "s": 26770, "text": "Example 2: It sets the color to alternate odd rows in a table. " }, { "code": null, "e": 26839, "s": 26834, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> Set alternate row in table </title> <style> table { border-collapse: collapse; width: 100%; } th, td { text-align: left; padding: 8px; } tr:nth-child(odd) { background-color: Lightgreen; } </style></head> <body> <table> <tr> <th>Name</th> <th>Designation</th> <th>Salary</th> </tr> <tr> <td>Steve</td> <td>Manager</td> <td>1, 00, 000</td> </tr> <tr> <td>SURAJ</td> <td>Assistant Manager</td> <td>50, 000</td> </tr> <tr> <td>Khushboo</td> <td>Analysist</td> <td>65, 000</td> </tr> <tr> <td>Kartik</td> <td>Worker</td> <td>20, 000</td> </tr> <tr> <td>Saksham</td> <td>Worker</td> <td>20, 000</td> </tr> </table></body> <html>", "e": 27991, "s": 26839, "text": null }, { "code": null, "e": 28001, "s": 27991, "text": "Output: " }, { "code": null, "e": 28020, "s": 28001, "text": "Supported Browser:" }, { "code": null, "e": 28038, "s": 28020, "text": "Google Chrome 4.0" }, { "code": null, "e": 28060, "s": 28038, "text": "Internet Explorer 9.0" }, { "code": null, "e": 28072, "s": 28060, "text": "Firefox 3.5" }, { "code": null, "e": 28082, "s": 28072, "text": "Opera 9.6" }, { "code": null, "e": 28094, "s": 28082, "text": "Safari 3.2 " }, { "code": null, "e": 28280, "s": 28094, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 28292, "s": 28280, "text": "ysachin2314" }, { "code": null, "e": 28301, "s": 28292, "text": "CSS-Misc" }, { "code": null, "e": 28308, "s": 28301, "text": "Picked" }, { "code": null, "e": 28312, "s": 28308, "text": "CSS" }, { "code": null, "e": 28329, "s": 28312, "text": "Web Technologies" }, { "code": null, "e": 28427, "s": 28329, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28436, "s": 28427, "text": "Comments" }, { "code": null, "e": 28449, "s": 28436, "text": "Old Comments" }, { "code": null, "e": 28486, "s": 28449, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28527, "s": 28486, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 28556, "s": 28527, "text": "Form validation using jQuery" }, { "code": null, "e": 28611, "s": 28556, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 28673, "s": 28611, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 28715, "s": 28673, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28748, "s": 28715, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28791, "s": 28748, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28836, "s": 28791, "text": "Convert a string to an integer in JavaScript" } ]
Checkbox-inline Bootstrap class
Use .checkbox-inline class to a series of checkboxes for controls to appear on the same line. You can try to run the following code to implement the .checkbox-inline class Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Forms</title> <meta name = "viewport" content = "width=device-width, initial-scale = 1"> <link rel = "stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> </head> <body> <label for = "name">Best IDE (You can select more than one)</label> <div> <label class = "checkbox-inline"> <input type = "checkbox" id = "inlineCheckbox1" value = "option1"> NetBeans IDE </label> <label class = "checkbox-inline"> <input type = "checkbox" id = "inlineCheckbox2" value = "option2"> Eclipse IDE </label> </div> </body> </html>
[ { "code": null, "e": 1156, "s": 1062, "text": "Use .checkbox-inline class to a series of checkboxes for controls to appear on the same line." }, { "code": null, "e": 1234, "s": 1156, "text": "You can try to run the following code to implement the .checkbox-inline class" }, { "code": null, "e": 1244, "s": 1234, "text": "Live Demo" }, { "code": null, "e": 2151, "s": 1244, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Forms</title>\n <meta name = \"viewport\" content = \"width=device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <label for = \"name\">Best IDE (You can select more than one)</label>\n <div>\n <label class = \"checkbox-inline\">\n <input type = \"checkbox\" id = \"inlineCheckbox1\" value = \"option1\"> NetBeans IDE\n </label>\n <label class = \"checkbox-inline\">\n <input type = \"checkbox\" id = \"inlineCheckbox2\" value = \"option2\"> Eclipse IDE\n </label>\n </div>\n </body>\n</html>" } ]
How to find the Current Context id of the Thread in C#?
To create a new thread. Thread thread = Thread.CurrentThread; thread.Name = "My new Thread”; To get the current context id, use the ContextID property. Thread.CurrentContext.ContextID Let us see the complete code − Live Demo using System; using System.Threading; namespace Demo { class MyClass { static void Main(string[] args) { Thread thread = Thread.CurrentThread; thread.Name = "My new Thread"; Console.WriteLine("Thread Name = {0}", thread.Name); Console.WriteLine("current Context id: {0}", Thread.CurrentContext.ContextID); Console.ReadKey(); } } } Thread Name = My new Thread current Context id: 0
[ { "code": null, "e": 1086, "s": 1062, "text": "To create a new thread." }, { "code": null, "e": 1155, "s": 1086, "text": "Thread thread = Thread.CurrentThread;\nthread.Name = \"My new Thread”;" }, { "code": null, "e": 1214, "s": 1155, "text": "To get the current context id, use the ContextID property." }, { "code": null, "e": 1246, "s": 1214, "text": "Thread.CurrentContext.ContextID" }, { "code": null, "e": 1277, "s": 1246, "text": "Let us see the complete code −" }, { "code": null, "e": 1288, "s": 1277, "text": " Live Demo" }, { "code": null, "e": 1682, "s": 1288, "text": "using System;\nusing System.Threading;\nnamespace Demo {\n class MyClass {\n static void Main(string[] args) {\n Thread thread = Thread.CurrentThread;\n thread.Name = \"My new Thread\";\n Console.WriteLine(\"Thread Name = {0}\", thread.Name);\n Console.WriteLine(\"current Context id: {0}\", Thread.CurrentContext.ContextID);\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 1732, "s": 1682, "text": "Thread Name = My new Thread\ncurrent Context id: 0" } ]
Forecasts in Snowflake: Facebook Prophet on Cloud Run with SQL | by Felipe Hoffa | Towards Data Science
The goal for this post is to build a function you could use within Snowflake to forecast time series. A great open source tool for this is Facebook Prophet, and we just need a way to use it within our Snowflake environment. This is easy, with Snowflake’s ability to run external functions — hence we only need to host an instance of Prophet and add the necessary plumbing to end up with a prophetize(timeseries) function within Snowflake. Let’s start with a demo, any time series in Snowflake will do: For example, the temperature around New York City in the Newark airport since 2018: select date, tempfrom noaa_gsodwhere country_fips='US'and station = 'NEWARK LIBERTY INTERNATIONAL AP';-- TODO: Show how to get NOAA GSOD from Knoema in a future post. Then we can call our function prophetize() (see below how to create it) by aggregating the previous time series into an array with dates and values: select prophetize(array_construct( array_agg(temp::float) within group(order by date) , array_agg(date::date) within group(order by date))::string) strfrom table(result_scan(last_query_id(-1))); And that’s it. What we get back is an array with predictions. An easy way to visualize these results is to combine the values of the previous two queries: select date, temp::float avg_temp , 0 forecast, 0 fore_min, 0 fore_maxfrom table(result_scan(last_query_id(-2)))union allselect x.value[0]::date, 0, x.value[1]::int forecast, x.value[2]::int fore_min, x.value[3]::int fore_maxfrom table(result_scan(last_query_id(-1))) a, table(flatten(a.$1)) x; Interesting notes on the above: Prophet was able to easily detect seasonal patterns and predict future values. A lot of how Prophet works is tunable, but what you get out of the box works too. On Snowflake I used last_query_id(-1) and last_query_id(-2) to combine the results of the previous two queries. It’s a nifty feature. Now let’s check the details on how to connect a function in the Snowflake SQL world prophetize() to Facebook Prophet running on Cloud Run. The requirements.txt to build this container are straightforward: flask==1.1.4requests==2.25.1gunicorn==20.1.0pandas==1.2.4pystan==2.19.1.1 # <3.0fbprophet==0.7.1 As the Dockerfile: FROM python:3.8# Allow statements and log messages to immediately appear in the Cloud Run logsENV PYTHONUNBUFFERED TrueCOPY requirements.txt .RUN pip install -r requirements.txtENV APP_HOME /appWORKDIR $APP_HOMECOPY main.py ./CMD exec gunicorn --bind :$PORT --workers 1 --threads 1 --timeout 0 main:app And this is main.py, a basic web server that parses incoming arrays into a dataframe that Prophet uses to forecast an arbitrary number of periods. Then it returns a serialized array with a forecast and uncertainty intervals that Snowflake will receive: import jsonimport loggingimport osfrom fbprophet import Prophetfrom flask import Flask, requestimport pandas as pdlog = logging.getLogger()app = Flask(__name__)def forecast(df: pd.DataFrame, periods=365) -> pd.DataFrame: df["ds"] = pd.to_datetime(df["ds"]) model = Prophet() model.fit(df) future_df = model.make_future_dataframe( periods=periods, include_history=False) return model.predict(future_df)[["ds", "yhat", "yhat_lower", "yhat_upper"]]@app.route("/", methods=["POST"])def index(): payload = request.get_json() logging.info(payload) # https://docs.snowflake.com/en/sql-reference/external-functions-data-format.html rows = payload["data"] return_value = [] for row in rows: row_number = row[0] function_input = json.loads(row[1]) df = pd.DataFrame({'ds': function_input[1], 'y': function_input[0]}) fc = forecast(df) fc['ds'] = fc['ds'].dt.strftime('%Y-%m-%d') row_to_return = [row_number, fc.to_numpy().tolist()] return_value.append(row_to_return) json_compatible_string_to_return = json.dumps({"data": return_value}) return (json_compatible_string_to_return)if __name__ == "__main__": app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080))) If we want to build and run this container on Google Cloud run, we need to run: gcloud builds submit --config cloudbuild.yaml;gcloud run deploy --image gcr.io/fhoffa/prophetize --platform managed Building the image on Cloud Build is slow the first time, as it takes time to compile Prophet — but this cloudbuild.yaml makes it fast with an image cache on further builds: steps:- name: 'gcr.io/cloud-builders/docker' entrypoint: 'bash' args: - '-c' - | docker pull gcr.io/fhoffa/prophetize:latest || exit 0- name: 'gcr.io/cloud-builders/docker' args: [ 'build', '--cache-from', 'gcr.io/fhoffa/prophetize:latest', '-t', 'gcr.io/fhoffa/prophetize:latest', '.' ]images: ['gcr.io/fhoffa/prophetize:latest'] One of the main goals I had behind this project was to celebrate that Snowflake now supports external functions for GCP. Hence my choice to deploy on Cloud Run. Now, to run external functions through GCP, we need to set up a connection from Snowflake to Google API Gateway, and from API Gateway to Cloud Run. First we need a gateway.yaml for API Gateway to know that it will act as a proxy to the service we deployed on Cloud Run: swagger: '2.0'info: title: API Gateway config for Snowflake external function. description: This configuration file connects the API Gateway resource to the remote service (Cloud Run). version: 1.0.0schemes: - httpsproduces: - application/jsonpaths: /test: post: summary: Prophetize operationId: prophetize x-google-backend: address: https://prophetize-zqnzinxyeq-wl.a.run.app/ protocol: h2 responses: '200': description: <DESCRIPTION> schema: type: string Then you can follow the GCP docs to create an API Gateway with this configuration. Oh, and make sure to replace the values above with your own service URLs. This is how I connected the dots on Snowflake, to create an integration with API Gateway: use role accountadmin;use schema temp.public;create or replace api integration prophet_test api_provider = google_api_gateway google_audience = 'test1-3s4aecfho43ih.apigateway.fhoffa.cloud.goog' api_allowed_prefixes = ('https://prophetize-4r3ddv95.wl.gateway.dev') enabled = true; describe integration prophet_test;create or replace external function prophetize(x string) returns variant-- IMMUTABLE api_integration = prophet_test as 'https://prophetize-4r3ddv95.wl.gateway.dev/test' ;grant usage on function prophetize(string) to role sysadmin; And that’s all you need, now you can call the just minted prophetize() as in any other query in Snowflake: select prophetize('[[41,43,62,43],["2019-12-30","2020-01-06","2020-01-13","2020-01-20"]]'); Which gives results like: [ [ "2020-01-21", 51.3641167654911, 40.85673826625397, 61.745184538148166 ], [ "2020-01-22", 51.72223221323965, 41.87259513681375, 61.29144225035811 ], [ "2020-01-23", 52.0803476609882, 41.66374622035821, 61.55883149200517 ], [...]] You might have noticed many URLs in my configs above — now that you’ve seen them, you might want to start calling my functions from your accounts. That would be fine, but I’d rather protect them. Snowflake makes this easy. Once you create the integration above, a service account for GCP will be automatically provisioned. You can get its value with describe integration prophet_test — and then use that service account to update the gateway.yaml so no one else can call it: swagger: '2.0'info: title: API Gateway config for Snowflake external function. description: This configuration file connects the API Gateway resource to the remote service (Cloud Function). version: 1.0.0securityDefinitions: snowflakeAccess01: authorizationUrl: "" flow: "implicit" type: "oauth2" x-google-issuer: "[email protected]" x-google-jwks_uri: "https://www.googleapis.com/robot/v1/metadata/x509/[email protected]"schemes: - httpsproduces: - application/jsonpaths: /test: post: summary: Prophetize. operationId: prophetize security: - snowflakeAccess01: [] x-google-backend: address: https://prophetize-zqnzinxyeq-wl.a.run.app/ protocol: h2 responses: '200': description: <DESCRIPTION> schema: type: string Then follow these Snowflake docs to update your GCP API Gateway with the above secured config. Note that this GCP service account is provisioned by Snowflake regardless of what cloud you are using to host your Snowflake account. In this case I ran this whole demo on Snowflake on AWS, and it was able to call the GCP services effortlessly. Meanwhile in Cloud Run, make sure to stop allowing unauthenticated invocations. With this only calls authorized through the API Gateway will be served: Facebook Prophet is a versatile tool with many levers and ways to tune: Prophet is a procedure for forecasting time series data based on an additive model where non-linear trends are fit with yearly, weekly, and daily seasonality, plus holiday effects. It works best with time series that have strong seasonal effects and several seasons of historical data. Prophet is robust to missing data and shifts in the trend, and typically handles outliers well. Read more from: “Seven Tips for Forecasting Cloud Costs (with FB’s Prophet)” from Gad Benram. “Building a serverless, containerized batch prediction model using Google Cloud Run, Pub/Sub, Cloud Storage and Terraform” by Sebastian Telsemeyer. Cloud Run costs and features, by Ahmet Alp Balkan Try this out with a Snowflake free trial account — you only need an email address to get started. I shall set up a GitHub project with all these files (and update here when done) Knoema already has the valuation of multiple crypto coins in the Snowflake Marketplace, thus building a time series forecast with Prophet is straightforward: -- define the time seriesselect "Value" value, "Date" datefrom KNOEMA_FINANCE_DATA_ATLAS.FINANCE.CMCCD2019 where "Cryptocurrency Name" = 'Bitcoin (btc)' and "Measure" = 'PriceUSD' and date > '2017-01-01'order by "Date";-- prophetizeselect prophetize(array_construct( array_agg(value::float) within group(order by date) , array_agg(date::date) within group(order by date))::string) strfrom table(result_scan(last_query_id(-1)));-- prepare the vizselect date, value, 0 forecast, 0 fore_min, 0 fore_maxfrom table(result_scan(last_query_id(-2)))union allselect x.value[0]::date, 0, x.value[1]::int forecast, x.value[2]::int fore_min, x.value[3]::int fore_maxfrom table(result_scan(last_query_id(-1))) a, table(flatten(a.$1)) x; The more you play with Prophet, the more you’ll see that the forecast will depend heavily on what values you feed it, and how you tune it. In this case, the forecasts varied widely depending on what starting date I used for the time series — starting in 2016 meant Prophet would observe a more complex pattern that feeding it data starting in 2018, and so forth. Best part for me? I can pull all this off without leaving my comfy Snowflake SQL web UI: I’m Felipe Hoffa, Data Cloud Advocate for Snowflake. Thanks for joining me on this adventure. You can follow me on Twitter and LinkedIn, and check reddit.com/r/snowflake for the most interesting Snowflake news.
[ { "code": null, "e": 611, "s": 172, "text": "The goal for this post is to build a function you could use within Snowflake to forecast time series. A great open source tool for this is Facebook Prophet, and we just need a way to use it within our Snowflake environment. This is easy, with Snowflake’s ability to run external functions — hence we only need to host an instance of Prophet and add the necessary plumbing to end up with a prophetize(timeseries) function within Snowflake." }, { "code": null, "e": 758, "s": 611, "text": "Let’s start with a demo, any time series in Snowflake will do: For example, the temperature around New York City in the Newark airport since 2018:" }, { "code": null, "e": 925, "s": 758, "text": "select date, tempfrom noaa_gsodwhere country_fips='US'and station = 'NEWARK LIBERTY INTERNATIONAL AP';-- TODO: Show how to get NOAA GSOD from Knoema in a future post." }, { "code": null, "e": 1074, "s": 925, "text": "Then we can call our function prophetize() (see below how to create it) by aggregating the previous time series into an array with dates and values:" }, { "code": null, "e": 1303, "s": 1074, "text": "select prophetize(array_construct( array_agg(temp::float) within group(order by date) , array_agg(date::date) within group(order by date))::string) strfrom table(result_scan(last_query_id(-1)));" }, { "code": null, "e": 1458, "s": 1303, "text": "And that’s it. What we get back is an array with predictions. An easy way to visualize these results is to combine the values of the previous two queries:" }, { "code": null, "e": 1756, "s": 1458, "text": "select date, temp::float avg_temp , 0 forecast, 0 fore_min, 0 fore_maxfrom table(result_scan(last_query_id(-2)))union allselect x.value[0]::date, 0, x.value[1]::int forecast, x.value[2]::int fore_min, x.value[3]::int fore_maxfrom table(result_scan(last_query_id(-1))) a, table(flatten(a.$1)) x;" }, { "code": null, "e": 1788, "s": 1756, "text": "Interesting notes on the above:" }, { "code": null, "e": 1867, "s": 1788, "text": "Prophet was able to easily detect seasonal patterns and predict future values." }, { "code": null, "e": 1949, "s": 1867, "text": "A lot of how Prophet works is tunable, but what you get out of the box works too." }, { "code": null, "e": 2083, "s": 1949, "text": "On Snowflake I used last_query_id(-1) and last_query_id(-2) to combine the results of the previous two queries. It’s a nifty feature." }, { "code": null, "e": 2222, "s": 2083, "text": "Now let’s check the details on how to connect a function in the Snowflake SQL world prophetize() to Facebook Prophet running on Cloud Run." }, { "code": null, "e": 2288, "s": 2222, "text": "The requirements.txt to build this container are straightforward:" }, { "code": null, "e": 2386, "s": 2288, "text": "flask==1.1.4requests==2.25.1gunicorn==20.1.0pandas==1.2.4pystan==2.19.1.1 # <3.0fbprophet==0.7.1" }, { "code": null, "e": 2405, "s": 2386, "text": "As the Dockerfile:" }, { "code": null, "e": 2708, "s": 2405, "text": "FROM python:3.8# Allow statements and log messages to immediately appear in the Cloud Run logsENV PYTHONUNBUFFERED TrueCOPY requirements.txt .RUN pip install -r requirements.txtENV APP_HOME /appWORKDIR $APP_HOMECOPY main.py ./CMD exec gunicorn --bind :$PORT --workers 1 --threads 1 --timeout 0 main:app" }, { "code": null, "e": 2961, "s": 2708, "text": "And this is main.py, a basic web server that parses incoming arrays into a dataframe that Prophet uses to forecast an arbitrary number of periods. Then it returns a serialized array with a forecast and uncertainty intervals that Snowflake will receive:" }, { "code": null, "e": 4228, "s": 2961, "text": "import jsonimport loggingimport osfrom fbprophet import Prophetfrom flask import Flask, requestimport pandas as pdlog = logging.getLogger()app = Flask(__name__)def forecast(df: pd.DataFrame, periods=365) -> pd.DataFrame: df[\"ds\"] = pd.to_datetime(df[\"ds\"]) model = Prophet() model.fit(df) future_df = model.make_future_dataframe( periods=periods, include_history=False) return model.predict(future_df)[[\"ds\", \"yhat\", \"yhat_lower\", \"yhat_upper\"]]@app.route(\"/\", methods=[\"POST\"])def index(): payload = request.get_json() logging.info(payload) # https://docs.snowflake.com/en/sql-reference/external-functions-data-format.html rows = payload[\"data\"] return_value = [] for row in rows: row_number = row[0] function_input = json.loads(row[1]) df = pd.DataFrame({'ds': function_input[1], 'y': function_input[0]}) fc = forecast(df) fc['ds'] = fc['ds'].dt.strftime('%Y-%m-%d') row_to_return = [row_number, fc.to_numpy().tolist()] return_value.append(row_to_return) json_compatible_string_to_return = json.dumps({\"data\": return_value}) return (json_compatible_string_to_return)if __name__ == \"__main__\": app.run(debug=True, host=\"0.0.0.0\", port=int(os.environ.get(\"PORT\", 8080)))" }, { "code": null, "e": 4308, "s": 4228, "text": "If we want to build and run this container on Google Cloud run, we need to run:" }, { "code": null, "e": 4424, "s": 4308, "text": "gcloud builds submit --config cloudbuild.yaml;gcloud run deploy --image gcr.io/fhoffa/prophetize --platform managed" }, { "code": null, "e": 4598, "s": 4424, "text": "Building the image on Cloud Build is slow the first time, as it takes time to compile Prophet — but this cloudbuild.yaml makes it fast with an image cache on further builds:" }, { "code": null, "e": 4980, "s": 4598, "text": "steps:- name: 'gcr.io/cloud-builders/docker' entrypoint: 'bash' args: - '-c' - | docker pull gcr.io/fhoffa/prophetize:latest || exit 0- name: 'gcr.io/cloud-builders/docker' args: [ 'build', '--cache-from', 'gcr.io/fhoffa/prophetize:latest', '-t', 'gcr.io/fhoffa/prophetize:latest', '.' ]images: ['gcr.io/fhoffa/prophetize:latest']" }, { "code": null, "e": 5141, "s": 4980, "text": "One of the main goals I had behind this project was to celebrate that Snowflake now supports external functions for GCP. Hence my choice to deploy on Cloud Run." }, { "code": null, "e": 5289, "s": 5141, "text": "Now, to run external functions through GCP, we need to set up a connection from Snowflake to Google API Gateway, and from API Gateway to Cloud Run." }, { "code": null, "e": 5411, "s": 5289, "text": "First we need a gateway.yaml for API Gateway to know that it will act as a proxy to the service we deployed on Cloud Run:" }, { "code": null, "e": 5948, "s": 5411, "text": "swagger: '2.0'info: title: API Gateway config for Snowflake external function. description: This configuration file connects the API Gateway resource to the remote service (Cloud Run). version: 1.0.0schemes: - httpsproduces: - application/jsonpaths: /test: post: summary: Prophetize operationId: prophetize x-google-backend: address: https://prophetize-zqnzinxyeq-wl.a.run.app/ protocol: h2 responses: '200': description: <DESCRIPTION> schema: type: string" }, { "code": null, "e": 6105, "s": 5948, "text": "Then you can follow the GCP docs to create an API Gateway with this configuration. Oh, and make sure to replace the values above with your own service URLs." }, { "code": null, "e": 6195, "s": 6105, "text": "This is how I connected the dots on Snowflake, to create an integration with API Gateway:" }, { "code": null, "e": 6765, "s": 6195, "text": "use role accountadmin;use schema temp.public;create or replace api integration prophet_test api_provider = google_api_gateway google_audience = 'test1-3s4aecfho43ih.apigateway.fhoffa.cloud.goog' api_allowed_prefixes = ('https://prophetize-4r3ddv95.wl.gateway.dev') enabled = true; describe integration prophet_test;create or replace external function prophetize(x string) returns variant-- IMMUTABLE api_integration = prophet_test as 'https://prophetize-4r3ddv95.wl.gateway.dev/test' ;grant usage on function prophetize(string) to role sysadmin;" }, { "code": null, "e": 6872, "s": 6765, "text": "And that’s all you need, now you can call the just minted prophetize() as in any other query in Snowflake:" }, { "code": null, "e": 6964, "s": 6872, "text": "select prophetize('[[41,43,62,43],[\"2019-12-30\",\"2020-01-06\",\"2020-01-13\",\"2020-01-20\"]]');" }, { "code": null, "e": 6990, "s": 6964, "text": "Which gives results like:" }, { "code": null, "e": 7265, "s": 6990, "text": "[ [ \"2020-01-21\", 51.3641167654911, 40.85673826625397, 61.745184538148166 ], [ \"2020-01-22\", 51.72223221323965, 41.87259513681375, 61.29144225035811 ], [ \"2020-01-23\", 52.0803476609882, 41.66374622035821, 61.55883149200517 ], [...]]" }, { "code": null, "e": 7461, "s": 7265, "text": "You might have noticed many URLs in my configs above — now that you’ve seen them, you might want to start calling my functions from your accounts. That would be fine, but I’d rather protect them." }, { "code": null, "e": 7740, "s": 7461, "text": "Snowflake makes this easy. Once you create the integration above, a service account for GCP will be automatically provisioned. You can get its value with describe integration prophet_test — and then use that service account to update the gateway.yaml so no one else can call it:" }, { "code": null, "e": 8629, "s": 7740, "text": "swagger: '2.0'info: title: API Gateway config for Snowflake external function. description: This configuration file connects the API Gateway resource to the remote service (Cloud Function). version: 1.0.0securityDefinitions: snowflakeAccess01: authorizationUrl: \"\" flow: \"implicit\" type: \"oauth2\" x-google-issuer: \"[email protected]\" x-google-jwks_uri: \"https://www.googleapis.com/robot/v1/metadata/x509/[email protected]\"schemes: - httpsproduces: - application/jsonpaths: /test: post: summary: Prophetize. operationId: prophetize security: - snowflakeAccess01: [] x-google-backend: address: https://prophetize-zqnzinxyeq-wl.a.run.app/ protocol: h2 responses: '200': description: <DESCRIPTION> schema: type: string" }, { "code": null, "e": 8724, "s": 8629, "text": "Then follow these Snowflake docs to update your GCP API Gateway with the above secured config." }, { "code": null, "e": 8969, "s": 8724, "text": "Note that this GCP service account is provisioned by Snowflake regardless of what cloud you are using to host your Snowflake account. In this case I ran this whole demo on Snowflake on AWS, and it was able to call the GCP services effortlessly." }, { "code": null, "e": 9121, "s": 8969, "text": "Meanwhile in Cloud Run, make sure to stop allowing unauthenticated invocations. With this only calls authorized through the API Gateway will be served:" }, { "code": null, "e": 9193, "s": 9121, "text": "Facebook Prophet is a versatile tool with many levers and ways to tune:" }, { "code": null, "e": 9575, "s": 9193, "text": "Prophet is a procedure for forecasting time series data based on an additive model where non-linear trends are fit with yearly, weekly, and daily seasonality, plus holiday effects. It works best with time series that have strong seasonal effects and several seasons of historical data. Prophet is robust to missing data and shifts in the trend, and typically handles outliers well." }, { "code": null, "e": 9591, "s": 9575, "text": "Read more from:" }, { "code": null, "e": 9669, "s": 9591, "text": "“Seven Tips for Forecasting Cloud Costs (with FB’s Prophet)” from Gad Benram." }, { "code": null, "e": 9817, "s": 9669, "text": "“Building a serverless, containerized batch prediction model using Google Cloud Run, Pub/Sub, Cloud Storage and Terraform” by Sebastian Telsemeyer." }, { "code": null, "e": 9867, "s": 9817, "text": "Cloud Run costs and features, by Ahmet Alp Balkan" }, { "code": null, "e": 9965, "s": 9867, "text": "Try this out with a Snowflake free trial account — you only need an email address to get started." }, { "code": null, "e": 10046, "s": 9965, "text": "I shall set up a GitHub project with all these files (and update here when done)" }, { "code": null, "e": 10204, "s": 10046, "text": "Knoema already has the valuation of multiple crypto coins in the Snowflake Marketplace, thus building a time series forecast with Prophet is straightforward:" }, { "code": null, "e": 10942, "s": 10204, "text": "-- define the time seriesselect \"Value\" value, \"Date\" datefrom KNOEMA_FINANCE_DATA_ATLAS.FINANCE.CMCCD2019 where \"Cryptocurrency Name\" = 'Bitcoin (btc)' and \"Measure\" = 'PriceUSD' and date > '2017-01-01'order by \"Date\";-- prophetizeselect prophetize(array_construct( array_agg(value::float) within group(order by date) , array_agg(date::date) within group(order by date))::string) strfrom table(result_scan(last_query_id(-1)));-- prepare the vizselect date, value, 0 forecast, 0 fore_min, 0 fore_maxfrom table(result_scan(last_query_id(-2)))union allselect x.value[0]::date, 0, x.value[1]::int forecast, x.value[2]::int fore_min, x.value[3]::int fore_maxfrom table(result_scan(last_query_id(-1))) a, table(flatten(a.$1)) x;" }, { "code": null, "e": 11305, "s": 10942, "text": "The more you play with Prophet, the more you’ll see that the forecast will depend heavily on what values you feed it, and how you tune it. In this case, the forecasts varied widely depending on what starting date I used for the time series — starting in 2016 meant Prophet would observe a more complex pattern that feeding it data starting in 2018, and so forth." }, { "code": null, "e": 11394, "s": 11305, "text": "Best part for me? I can pull all this off without leaving my comfy Snowflake SQL web UI:" } ]
Using Genetic Algorithms to Optimize GANs | by Victor Sim | Towards Data Science
GANs are one of the most computationally intensive models to train, as it is the equivalent of training two neural networks at the same time. For my lousy portable computer, training a GAN until convergence is very difficult. I have written a generic genetic algorithm, that can be adapted to many different problems. I adapted this genetic algorithm to train GANs, generate handwritten digits. Genetic Algorithms are a type of learning algorithm, that uses the idea that crossing over the weights of two good neural networks, would result in a better neural network. The reason that genetic algorithms are so effective is because there is no direct optimization algorithm, allowing for the possibility to have extremely varied results. Additionally, they often come up with very interesting solutions that often give valuable insight into the problem. A set of random weights are generated. This is the neural network of the first agent. A set of tests are performed on the agent. The agent receives a score based on the tests. Repeat this several times to create a population.Select the top 10% of the population to be available to crossover. Two random parents are chosen from the top 10% and their weights are crossover. Every time a crossover occurs, there is a small chance of mutation: That is a random value that is in neither of the parent’s weights. This process slowly optimizes the agent’s performance, as the agents slowly adapt to the environment. Advantages: Computationally not intensive There are no linear algebra calculations to be done. The only machine learning calculations necessary are forward passes through the neural networks. Because of this, the system requirements are very broad, as compared to Deep Neural Networks. Adaptable One could adapt and insert many different tests and ways to manipulate the flexible nature of genetic algorithms. One could create a GAN within a Genetic algorithm, by making the agents propagate Generator networks, and the tests being the discriminators. This is a critical benefit, that persuades me that the use of genetic algorithm will be more widespread in the future. Understandable For normal neural networks, the learning patterns of the algorithm are enigmatic at best. For genetic algorithms it is easy to understand why some things come about: For example, when a genetic algorithm is given the Tic-Tac-Toe environment, certain recognizable strategies slowly develop. This is a large benefit, as the use of machine learning is to use technology to help us gain insight on important matters. Disadvantages: Takes a long period of time Unlucky crossovers and Mutations could result in a negative effect on the program’s accuracy, and therefore make the program slower to converge or reach a certain loss threshold. Now that you have a reasonably comprehensive understanding of genetic algorithms, and its strengths and its limitations, I am now able to show you the program: import randomimport numpy as npfrom IPython.display import clear_outputfrom keras.layers import Reshapefrom keras.layers import Flattenfrom keras.layers import Conv2Dfrom keras.layers import Conv2DTransposefrom keras.layers import LeakyReLUfrom keras.layers import Dropout,Densefrom keras.optimizers import Adamfrom keras.models import Sequentialfrom keras.datasets.mnist import load_data(trainX, trainy), (testX, testy) = load_data() Keras is needed for the discriminator, but the neural networks in the genetic algorithm are created by the code below, in which it is built with numpy as its basis. class g enetic_algorithm: def execute(pop_size,generations,threshold,network): class Agent: def __init__(self,network): This is the creation of the class “genetic_algorithm” that holds all the functions that concerns the genetic algorithm and how it is supposed to function. The main function is the execute function, that takes pop_size,generations,threshold,network as parameters. pop_size is the size of the generated population, generations is the term for epochs, threshold is the loss value that you are satisfied with. X and y are for applications of genetic algorithms for labelled data. You can remove all instances of X and y for problems with no data or unlabelled data. Network is the network structure of the neural network. class neural_network: def __init__(self,network): self.weights = [] self.activations = [] for layer in network: if layer[0] != None: input_size = layer[0] else: input_size = network[network.index(layer)-1][1] output_size = layer[1] activation = layer[2] self.weights.append(np.random.randn(input_size,output_size)) self.activations.append(activation) def propagate(self,data): input_data = data for i in range(len(self.weights)): z = np.dot(input_data,self.weights[i]) a = self.activations[i](z) input_data = a yhat = a return yhat self.neural_network = neural_network(network) self.fitness = 0 This script describes the initialization of the weights and the propagation of the network for each agent’s neural network. def generate_agents(population, network): return [Agent(network) for _ in range(population)] This function creates the first population of agents that will be tested. def fitness(agents): for agent in agents: dataset_len = 100 fake = [] real = [] y = [] for i in range(dataset_len//2): fake.append(agent.neural_network.propagate(np.random.randn(latent_size)).reshape(28,28)) y.append(0) real.append(random.choice(trainX)) y.append(1) X = fake+real X = np.array(X).astype('uint8').reshape(len(X),28,28,1) y = np.array(y).astype('uint8') model.fit(X,y,verbose = 0) fake = [] real = [] y = [] for i in range(dataset_len//2): fake.append(agent.neural_network.propagate(np.random.randn(latent_size)).reshape(28,28)) y.append(0) real.append(random.choice(trainX)) y.append(1) X = fake+real X = np.array(X).astype('uint8').reshape(len(X),28,28,1) y = np.array(y).astype('uint8') agent.fitness = model.evaluate(X,y,verbose = 0)[1]*100 return agents The fitness function is the unique part of this genetic algorithm: A discriminator-type neural network will be defined later. This model will be trained based on the MNIST dataset loaded earlier. The model is in the form of a convolutional network to return binary results back. def selection(agents): agents = sorted(agents, key=lambda agent: agent.fitness, reverse=False) print('\n'.join(map(str, agents))) agents = agents[:int(0.2 * len(agents))] return agents This function mimics the theory of selection in evolution: The best survive while the others are left to die. In this case, their data is forgotten and is not used again. def unflatten(flattened,shapes): newarray = [] index = 0 for shape in shapes: size = np.product(shape) newarray.append(flattened[index : index + size].reshape(shape)) index += size return newarray To execute the crossover and mutation functions, the weights need to be flattened and unflattened into the original shapes. def crossover(agents,network,pop_size): offspring = [] for _ in range((pop_size - len(agents)) // 2): parent1 = random.choice(agents) parent2 = random.choice(agents) child1 = Agent(network) child2 = Agent(network) shapes = [a.shape for a in parent1.neural_network.weights] genes1 = np.concatenate([a.flatten() for a in parent1.neural_network.weights]) genes2 = np.concatenate([a.flatten() for a in parent2.neural_network.weights]) split = random.ragendint(0,len(genes1)-1)child1_genes = np.asrray(genes1[0:split].tolist() + genes2[split:].tolist()) child2_genes = np.array(genes1[0:split].tolist() + genes2[split:].tolist()) child1.neural_network.weights = unflatten(child1_genes,shapes) child2.neural_network.weights = unflatten(child2_genes,shapes) offspring.append(child1) offspring.append(child2) agents.extend(offspring) return agents The crossover function is one of the most complicated functions in the program. It generates two new “children” agents, whose weights that are replaced as a crossover of wo randomly generated parents. This is the process of creating the weights: Flatten the weights of the parentsGenerate two splitting pointsUse the splitting points as indices to set the weights of the two children agents Flatten the weights of the parents Generate two splitting points Use the splitting points as indices to set the weights of the two children agents This is the full process of the crossover of agents. def mutation(agents): for agent in agents: if random.uniform(0.0, 1.0) <= 0.1: weights = agent.neural_network.weights shapes = [a.shape for a in weights]flattened = np.concatenate([a.flatten() for a in weights]) randint = random.randint(0,len(flattened)-1) flattened[randint] = np.random.randn()newarray = [a ] indeweights = 0 for shape in shapes: size = np.product(shape) newarray.append(flattened[indeweights : indeweights + size].reshape(shape)) indeweights += size agent.neural_network.weights = newarray return agents This is the mutation function. The flattening is the same as the crossover function. Instead of splitting the points, a random point is chosen, to be replaced with a random value. for i in range(generations): print('Generation',str(i),':') agents = generate_agents(pop_size,network) agents = fitness(agents) agents = selection(agents) agents = crossover(agents,network,pop_size) agents = mutation(agents) agents = fitness(agents) if any(agent.fitness < threshold for agent in agents): print('Threshold met at generation '+str(i)+' !') if i % 100: clear_output() return agents[0] This is the last part of the execute function, that executes all the functions that have been defined. image_size = 28latent_size = 100model = Sequential()model.add(Conv2D(64, (3,3), strides=(2, 2), padding='same', input_shape=(image_size,image_size,1)))model.add(LeakyReLU(alpha=0.2))model.add(Dropout(0.4))model.add(Conv2D(64, (3,3), strides=(2, 2), padding='same'))model.add(LeakyReLU(alpha=0.2))model.add(Dropout(0.4))model.add(Flatten())model.add(Dense(1, activation='sigmoid'))opt = Adam(lr=0.0002, beta_1=0.5)model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])network = [[latent_size,100,sigmoid],[None,image_size**2,sigmoid]]ga = genetic_algorithmagent = ga.execute(1000,1000,90,network)(trainX, trainy), (testX, testy) = load_data()weights = agent.neural_network.weights This is the discriminator convolutional network that I talked about earlier. Image_size is the size of the MNIST image, and latent_size is to make sure This executes the whole genetic algorithm. For the network variable, each nested list holds the input neuron numbers, the output neuron numbers and the activation functions. The execute function returns the best agent. Obviously the genetic algorithm will not converge as fast as the gradient-based algorithm, but the computational work is spread over a longer period of time, making it less intensive on the computer! If you want to see more of my content, click this link.
[ { "code": null, "e": 566, "s": 171, "text": "GANs are one of the most computationally intensive models to train, as it is the equivalent of training two neural networks at the same time. For my lousy portable computer, training a GAN until convergence is very difficult. I have written a generic genetic algorithm, that can be adapted to many different problems. I adapted this genetic algorithm to train GANs, generate handwritten digits." }, { "code": null, "e": 739, "s": 566, "text": "Genetic Algorithms are a type of learning algorithm, that uses the idea that crossing over the weights of two good neural networks, would result in a better neural network." }, { "code": null, "e": 1024, "s": 739, "text": "The reason that genetic algorithms are so effective is because there is no direct optimization algorithm, allowing for the possibility to have extremely varied results. Additionally, they often come up with very interesting solutions that often give valuable insight into the problem." }, { "code": null, "e": 1531, "s": 1024, "text": "A set of random weights are generated. This is the neural network of the first agent. A set of tests are performed on the agent. The agent receives a score based on the tests. Repeat this several times to create a population.Select the top 10% of the population to be available to crossover. Two random parents are chosen from the top 10% and their weights are crossover. Every time a crossover occurs, there is a small chance of mutation: That is a random value that is in neither of the parent’s weights." }, { "code": null, "e": 1633, "s": 1531, "text": "This process slowly optimizes the agent’s performance, as the agents slowly adapt to the environment." }, { "code": null, "e": 1645, "s": 1633, "text": "Advantages:" }, { "code": null, "e": 1675, "s": 1645, "text": "Computationally not intensive" }, { "code": null, "e": 1919, "s": 1675, "text": "There are no linear algebra calculations to be done. The only machine learning calculations necessary are forward passes through the neural networks. Because of this, the system requirements are very broad, as compared to Deep Neural Networks." }, { "code": null, "e": 1929, "s": 1919, "text": "Adaptable" }, { "code": null, "e": 2304, "s": 1929, "text": "One could adapt and insert many different tests and ways to manipulate the flexible nature of genetic algorithms. One could create a GAN within a Genetic algorithm, by making the agents propagate Generator networks, and the tests being the discriminators. This is a critical benefit, that persuades me that the use of genetic algorithm will be more widespread in the future." }, { "code": null, "e": 2319, "s": 2304, "text": "Understandable" }, { "code": null, "e": 2732, "s": 2319, "text": "For normal neural networks, the learning patterns of the algorithm are enigmatic at best. For genetic algorithms it is easy to understand why some things come about: For example, when a genetic algorithm is given the Tic-Tac-Toe environment, certain recognizable strategies slowly develop. This is a large benefit, as the use of machine learning is to use technology to help us gain insight on important matters." }, { "code": null, "e": 2747, "s": 2732, "text": "Disadvantages:" }, { "code": null, "e": 2775, "s": 2747, "text": "Takes a long period of time" }, { "code": null, "e": 2954, "s": 2775, "text": "Unlucky crossovers and Mutations could result in a negative effect on the program’s accuracy, and therefore make the program slower to converge or reach a certain loss threshold." }, { "code": null, "e": 3114, "s": 2954, "text": "Now that you have a reasonably comprehensive understanding of genetic algorithms, and its strengths and its limitations, I am now able to show you the program:" }, { "code": null, "e": 3549, "s": 3114, "text": "import randomimport numpy as npfrom IPython.display import clear_outputfrom keras.layers import Reshapefrom keras.layers import Flattenfrom keras.layers import Conv2Dfrom keras.layers import Conv2DTransposefrom keras.layers import LeakyReLUfrom keras.layers import Dropout,Densefrom keras.optimizers import Adamfrom keras.models import Sequentialfrom keras.datasets.mnist import load_data(trainX, trainy), (testX, testy) = load_data()" }, { "code": null, "e": 3714, "s": 3549, "text": "Keras is needed for the discriminator, but the neural networks in the genetic algorithm are created by the code below, in which it is built with numpy as its basis." }, { "code": null, "e": 3863, "s": 3714, "text": "class g enetic_algorithm: def execute(pop_size,generations,threshold,network): class Agent: def __init__(self,network):" }, { "code": null, "e": 4481, "s": 3863, "text": "This is the creation of the class “genetic_algorithm” that holds all the functions that concerns the genetic algorithm and how it is supposed to function. The main function is the execute function, that takes pop_size,generations,threshold,network as parameters. pop_size is the size of the generated population, generations is the term for epochs, threshold is the loss value that you are satisfied with. X and y are for applications of genetic algorithms for labelled data. You can remove all instances of X and y for problems with no data or unlabelled data. Network is the network structure of the neural network." }, { "code": null, "e": 5610, "s": 4481, "text": "class neural_network: def __init__(self,network): self.weights = [] self.activations = [] for layer in network: if layer[0] != None: input_size = layer[0] else: input_size = network[network.index(layer)-1][1] output_size = layer[1] activation = layer[2] self.weights.append(np.random.randn(input_size,output_size)) self.activations.append(activation) def propagate(self,data): input_data = data for i in range(len(self.weights)): z = np.dot(input_data,self.weights[i]) a = self.activations[i](z) input_data = a yhat = a return yhat self.neural_network = neural_network(network) self.fitness = 0" }, { "code": null, "e": 5734, "s": 5610, "text": "This script describes the initialization of the weights and the propagation of the network for each agent’s neural network." }, { "code": null, "e": 5838, "s": 5734, "text": "def generate_agents(population, network): return [Agent(network) for _ in range(population)]" }, { "code": null, "e": 5912, "s": 5838, "text": "This function creates the first population of agents that will be tested." }, { "code": null, "e": 7131, "s": 5912, "text": "def fitness(agents): for agent in agents: dataset_len = 100 fake = [] real = [] y = [] for i in range(dataset_len//2): fake.append(agent.neural_network.propagate(np.random.randn(latent_size)).reshape(28,28)) y.append(0) real.append(random.choice(trainX)) y.append(1) X = fake+real X = np.array(X).astype('uint8').reshape(len(X),28,28,1) y = np.array(y).astype('uint8') model.fit(X,y,verbose = 0) fake = [] real = [] y = [] for i in range(dataset_len//2): fake.append(agent.neural_network.propagate(np.random.randn(latent_size)).reshape(28,28)) y.append(0) real.append(random.choice(trainX)) y.append(1) X = fake+real X = np.array(X).astype('uint8').reshape(len(X),28,28,1) y = np.array(y).astype('uint8') agent.fitness = model.evaluate(X,y,verbose = 0)[1]*100 return agents" }, { "code": null, "e": 7198, "s": 7131, "text": "The fitness function is the unique part of this genetic algorithm:" }, { "code": null, "e": 7410, "s": 7198, "text": "A discriminator-type neural network will be defined later. This model will be trained based on the MNIST dataset loaded earlier. The model is in the form of a convolutional network to return binary results back." }, { "code": null, "e": 7639, "s": 7410, "text": "def selection(agents): agents = sorted(agents, key=lambda agent: agent.fitness, reverse=False) print('\\n'.join(map(str, agents))) agents = agents[:int(0.2 * len(agents))] return agents" }, { "code": null, "e": 7810, "s": 7639, "text": "This function mimics the theory of selection in evolution: The best survive while the others are left to die. In this case, their data is forgotten and is not used again." }, { "code": null, "e": 8096, "s": 7810, "text": "def unflatten(flattened,shapes): newarray = [] index = 0 for shape in shapes: size = np.product(shape) newarray.append(flattened[index : index + size].reshape(shape)) index += size return newarray" }, { "code": null, "e": 8220, "s": 8096, "text": "To execute the crossover and mutation functions, the weights need to be flattened and unflattened into the original shapes." }, { "code": null, "e": 9379, "s": 8220, "text": "def crossover(agents,network,pop_size): offspring = [] for _ in range((pop_size - len(agents)) // 2): parent1 = random.choice(agents) parent2 = random.choice(agents) child1 = Agent(network) child2 = Agent(network) shapes = [a.shape for a in parent1.neural_network.weights] genes1 = np.concatenate([a.flatten() for a in parent1.neural_network.weights]) genes2 = np.concatenate([a.flatten() for a in parent2.neural_network.weights]) split = random.ragendint(0,len(genes1)-1)child1_genes = np.asrray(genes1[0:split].tolist() + genes2[split:].tolist()) child2_genes = np.array(genes1[0:split].tolist() + genes2[split:].tolist()) child1.neural_network.weights = unflatten(child1_genes,shapes) child2.neural_network.weights = unflatten(child2_genes,shapes) offspring.append(child1) offspring.append(child2) agents.extend(offspring) return agents" }, { "code": null, "e": 9625, "s": 9379, "text": "The crossover function is one of the most complicated functions in the program. It generates two new “children” agents, whose weights that are replaced as a crossover of wo randomly generated parents. This is the process of creating the weights:" }, { "code": null, "e": 9770, "s": 9625, "text": "Flatten the weights of the parentsGenerate two splitting pointsUse the splitting points as indices to set the weights of the two children agents" }, { "code": null, "e": 9805, "s": 9770, "text": "Flatten the weights of the parents" }, { "code": null, "e": 9835, "s": 9805, "text": "Generate two splitting points" }, { "code": null, "e": 9917, "s": 9835, "text": "Use the splitting points as indices to set the weights of the two children agents" }, { "code": null, "e": 9970, "s": 9917, "text": "This is the full process of the crossover of agents." }, { "code": null, "e": 10732, "s": 9970, "text": "def mutation(agents): for agent in agents: if random.uniform(0.0, 1.0) <= 0.1: weights = agent.neural_network.weights shapes = [a.shape for a in weights]flattened = np.concatenate([a.flatten() for a in weights]) randint = random.randint(0,len(flattened)-1) flattened[randint] = np.random.randn()newarray = [a ] indeweights = 0 for shape in shapes: size = np.product(shape) newarray.append(flattened[indeweights : indeweights + size].reshape(shape)) indeweights += size agent.neural_network.weights = newarray return agents" }, { "code": null, "e": 10912, "s": 10732, "text": "This is the mutation function. The flattening is the same as the crossover function. Instead of splitting the points, a random point is chosen, to be replaced with a random value." }, { "code": null, "e": 11491, "s": 10912, "text": "for i in range(generations): print('Generation',str(i),':') agents = generate_agents(pop_size,network) agents = fitness(agents) agents = selection(agents) agents = crossover(agents,network,pop_size) agents = mutation(agents) agents = fitness(agents) if any(agent.fitness < threshold for agent in agents): print('Threshold met at generation '+str(i)+' !') if i % 100: clear_output() return agents[0]" }, { "code": null, "e": 11594, "s": 11491, "text": "This is the last part of the execute function, that executes all the functions that have been defined." }, { "code": null, "e": 12298, "s": 11594, "text": "image_size = 28latent_size = 100model = Sequential()model.add(Conv2D(64, (3,3), strides=(2, 2), padding='same', input_shape=(image_size,image_size,1)))model.add(LeakyReLU(alpha=0.2))model.add(Dropout(0.4))model.add(Conv2D(64, (3,3), strides=(2, 2), padding='same'))model.add(LeakyReLU(alpha=0.2))model.add(Dropout(0.4))model.add(Flatten())model.add(Dense(1, activation='sigmoid'))opt = Adam(lr=0.0002, beta_1=0.5)model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])network = [[latent_size,100,sigmoid],[None,image_size**2,sigmoid]]ga = genetic_algorithmagent = ga.execute(1000,1000,90,network)(trainX, trainy), (testX, testy) = load_data()weights = agent.neural_network.weights" }, { "code": null, "e": 12450, "s": 12298, "text": "This is the discriminator convolutional network that I talked about earlier. Image_size is the size of the MNIST image, and latent_size is to make sure" }, { "code": null, "e": 12669, "s": 12450, "text": "This executes the whole genetic algorithm. For the network variable, each nested list holds the input neuron numbers, the output neuron numbers and the activation functions. The execute function returns the best agent." }, { "code": null, "e": 12869, "s": 12669, "text": "Obviously the genetic algorithm will not converge as fast as the gradient-based algorithm, but the computational work is spread over a longer period of time, making it less intensive on the computer!" } ]
WSDL - Elements
WSDL breaks down web services into three specific, identifiable elements that can be combined or reused once defined. The three major elements of WSDL that can be defined separately are − Types Operations Binding A WSDL document has various elements, but they are contained within these three main elements, which can be developed as separate documents and then they can be combined or reused to form complete WSDL files. A WSDL document contains the following elements − Definition − It is the root element of all WSDL documents. It defines the name of the web service, declares multiple namespaces used throughout the remainder of the document, and contains all the service elements described here. Definition − It is the root element of all WSDL documents. It defines the name of the web service, declares multiple namespaces used throughout the remainder of the document, and contains all the service elements described here. Data types − The data types to be used in the messages are in the form of XML schemas. Data types − The data types to be used in the messages are in the form of XML schemas. Message − It is an abstract definition of the data, in the form of a message presented either as an entire document or as arguments to be mapped to a method invocation. Message − It is an abstract definition of the data, in the form of a message presented either as an entire document or as arguments to be mapped to a method invocation. Operation − It is the abstract definition of the operation for a message, such as naming a method, message queue, or business process, that will accept and process the message. Operation − It is the abstract definition of the operation for a message, such as naming a method, message queue, or business process, that will accept and process the message. Port type − It is an abstract set of operations mapped to one or more end-points, defining the collection of operations for a binding; the collection of operations, as it is abstract, can be mapped to multiple transports through various bindings. Port type − It is an abstract set of operations mapped to one or more end-points, defining the collection of operations for a binding; the collection of operations, as it is abstract, can be mapped to multiple transports through various bindings. Binding − It is the concrete protocol and data formats for the operations and messages defined for a particular port type. Binding − It is the concrete protocol and data formats for the operations and messages defined for a particular port type. Port − It is a combination of a binding and a network address, providing the target address of the service communication. Port − It is a combination of a binding and a network address, providing the target address of the service communication. Service − It is a collection of related end-points encompassing the service definitions in the file; the services map the binding to the port and include any extensibility definitions. Service − It is a collection of related end-points encompassing the service definitions in the file; the services map the binding to the port and include any extensibility definitions. In addition to these major elements, the WSDL specification also defines the following utility elements − Documentation − This element is used to provide human-readable documentation and can be included inside any other WSDL element. Documentation − This element is used to provide human-readable documentation and can be included inside any other WSDL element. Import − This element is used to import other WSDL documents or XML Schemas. Import − This element is used to import other WSDL documents or XML Schemas. NOTE − WSDL parts are usually generated automatically using web services-aware tools. The main structure of a WSDL document looks like this − <definitions> <types> definition of types........ </types> <message> definition of a message.... </message> <portType> <operation> definition of a operation....... </operation> </portType> <binding> definition of a binding.... </binding> <service> definition of a service.... </service> </definitions> A WSDL document can also contain other elements, like extension elements and a service element that makes it possible to group together the definitions of several web services in one single WSDL document. Proceed further to analyze an example of WSDL Document. Print Add Notes Bookmark this page
[ { "code": null, "e": 1922, "s": 1804, "text": "WSDL breaks down web services into three specific, identifiable elements that can be combined or reused once defined." }, { "code": null, "e": 1992, "s": 1922, "text": "The three major elements of WSDL that can be defined separately are −" }, { "code": null, "e": 1998, "s": 1992, "text": "Types" }, { "code": null, "e": 2009, "s": 1998, "text": "Operations" }, { "code": null, "e": 2017, "s": 2009, "text": "Binding" }, { "code": null, "e": 2226, "s": 2017, "text": "A WSDL document has various elements, but they are contained within these three main elements, which can be developed as separate documents and then they can be combined or reused to form complete WSDL files." }, { "code": null, "e": 2276, "s": 2226, "text": "A WSDL document contains the following elements −" }, { "code": null, "e": 2505, "s": 2276, "text": "Definition − It is the root element of all WSDL documents. It defines the name of the web service, declares multiple namespaces used throughout the remainder of the document, and contains all the service elements described here." }, { "code": null, "e": 2734, "s": 2505, "text": "Definition − It is the root element of all WSDL documents. It defines the name of the web service, declares multiple namespaces used throughout the remainder of the document, and contains all the service elements described here." }, { "code": null, "e": 2821, "s": 2734, "text": "Data types − The data types to be used in the messages are in the form of XML schemas." }, { "code": null, "e": 2908, "s": 2821, "text": "Data types − The data types to be used in the messages are in the form of XML schemas." }, { "code": null, "e": 3077, "s": 2908, "text": "Message − It is an abstract definition of the data, in the form of a message presented either as an entire document or as arguments to be mapped to a method invocation." }, { "code": null, "e": 3246, "s": 3077, "text": "Message − It is an abstract definition of the data, in the form of a message presented either as an entire document or as arguments to be mapped to a method invocation." }, { "code": null, "e": 3423, "s": 3246, "text": "Operation − It is the abstract definition of the operation for a message, such as naming a method, message queue, or business process, that will accept and process the message." }, { "code": null, "e": 3600, "s": 3423, "text": "Operation − It is the abstract definition of the operation for a message, such as naming a method, message queue, or business process, that will accept and process the message." }, { "code": null, "e": 3847, "s": 3600, "text": "Port type − It is an abstract set of operations mapped to one or more end-points, defining the collection of operations for a binding; the collection of operations, as it is abstract, can be mapped to multiple transports through various bindings." }, { "code": null, "e": 4094, "s": 3847, "text": "Port type − It is an abstract set of operations mapped to one or more end-points, defining the collection of operations for a binding; the collection of operations, as it is abstract, can be mapped to multiple transports through various bindings." }, { "code": null, "e": 4217, "s": 4094, "text": "Binding − It is the concrete protocol and data formats for the operations and messages defined for a particular port type." }, { "code": null, "e": 4340, "s": 4217, "text": "Binding − It is the concrete protocol and data formats for the operations and messages defined for a particular port type." }, { "code": null, "e": 4462, "s": 4340, "text": "Port − It is a combination of a binding and a network address, providing the target address of the service communication." }, { "code": null, "e": 4584, "s": 4462, "text": "Port − It is a combination of a binding and a network address, providing the target address of the service communication." }, { "code": null, "e": 4769, "s": 4584, "text": "Service − It is a collection of related end-points encompassing the service definitions in the file; the services map the binding to the port and include any extensibility definitions." }, { "code": null, "e": 4954, "s": 4769, "text": "Service − It is a collection of related end-points encompassing the service definitions in the file; the services map the binding to the port and include any extensibility definitions." }, { "code": null, "e": 5060, "s": 4954, "text": "In addition to these major elements, the WSDL specification also defines the following utility elements −" }, { "code": null, "e": 5188, "s": 5060, "text": "Documentation − This element is used to provide human-readable documentation and can be included inside any other WSDL element." }, { "code": null, "e": 5316, "s": 5188, "text": "Documentation − This element is used to provide human-readable documentation and can be included inside any other WSDL element." }, { "code": null, "e": 5393, "s": 5316, "text": "Import − This element is used to import other WSDL documents or XML Schemas." }, { "code": null, "e": 5470, "s": 5393, "text": "Import − This element is used to import other WSDL documents or XML Schemas." }, { "code": null, "e": 5556, "s": 5470, "text": "NOTE − WSDL parts are usually generated automatically using web services-aware tools." }, { "code": null, "e": 5612, "s": 5556, "text": "The main structure of a WSDL document looks like this −" }, { "code": null, "e": 5995, "s": 5612, "text": "<definitions>\n <types>\n definition of types........\n </types>\n\n <message>\n definition of a message....\n </message>\n\n <portType>\n <operation>\n definition of a operation....... \n </operation>\n </portType>\n\n <binding>\n definition of a binding....\n </binding>\n\n <service>\n definition of a service....\n </service>\n</definitions>" }, { "code": null, "e": 6200, "s": 5995, "text": "A WSDL document can also contain other elements, like extension elements and a service element that makes it possible to group together the definitions of several web services in one single WSDL document." }, { "code": null, "e": 6256, "s": 6200, "text": "Proceed further to analyze an example of WSDL Document." }, { "code": null, "e": 6263, "s": 6256, "text": " Print" }, { "code": null, "e": 6274, "s": 6263, "text": " Add Notes" } ]
Count odd and even digits in a number in PL/SQL - GeeksforGeeks
11 Aug, 2021 Prerequisite – PL/SQL introduction In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.Given a number and task is to find the number of odd and even digits present in the number. Examples: Input: 123456 Output: Odd digits = 3 Even digits = 3 Input: 246 Output: Odd digits = 0 Even digits = 3 Approach is to take a number and one by one check its digits, if it is odd or even.Below is the required implementation: SQL --Odd and Even digits in a number--in PL/SQLDECLARE --num variable declared --num assign with a number num NUMBER := 123456; --len variable char declared len VARCHAR2(20); --cntvariable declared cnt1 NUMBER(5) := 0; cnt2 NUMBER(5) := 0;BEGIN --for loop go from 1 to length of the number FOR i IN 1..Length(num) LOOP len := Substr(num, i, 1); IF mod(len, 2) != 0 THEN cnt1 := cnt1 + 1; ELSE cnt2:=cnt2+1; END IF; END LOOP; --end loop dbms_output.Put_line('Odd Digits: ' || cnt1); dbms_output.Put_line('Even Digits: ' || cnt2); --display resultEND;--end program Output: Odd Digits: 3 Even Digits: 3 Akanksha_Rai clintra SQL-PL/SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SQL | Views Difference between DDL and DML in DBMS CTE in SQL SQL Interview Questions How to Update Multiple Columns in Single Update Statement in SQL? How to Alter Multiple Columns at Once in SQL Server? Difference between DELETE, DROP and TRUNCATE Difference between SQL and NoSQL MySQL | Group_CONCAT() Function What is Temporary Table in SQL?
[ { "code": null, "e": 24416, "s": 24388, "text": "\n11 Aug, 2021" }, { "code": null, "e": 24754, "s": 24416, "text": "Prerequisite – PL/SQL introduction In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.Given a number and task is to find the number of odd and even digits present in the number. " }, { "code": null, "e": 24766, "s": 24754, "text": "Examples: " }, { "code": null, "e": 24886, "s": 24766, "text": "Input: 123456\nOutput: Odd digits = 3\n Even digits = 3\n\nInput: 246\nOutput: Odd digits = 0\n Even digits = 3" }, { "code": null, "e": 25008, "s": 24886, "text": "Approach is to take a number and one by one check its digits, if it is odd or even.Below is the required implementation: " }, { "code": null, "e": 25012, "s": 25008, "text": "SQL" }, { "code": "--Odd and Even digits in a number--in PL/SQLDECLARE --num variable declared --num assign with a number num NUMBER := 123456; --len variable char declared len VARCHAR2(20); --cntvariable declared cnt1 NUMBER(5) := 0; cnt2 NUMBER(5) := 0;BEGIN --for loop go from 1 to length of the number FOR i IN 1..Length(num) LOOP len := Substr(num, i, 1); IF mod(len, 2) != 0 THEN cnt1 := cnt1 + 1; ELSE cnt2:=cnt2+1; END IF; END LOOP; --end loop dbms_output.Put_line('Odd Digits: ' || cnt1); dbms_output.Put_line('Even Digits: ' || cnt2); --display resultEND;--end program", "e": 25616, "s": 25012, "text": null }, { "code": null, "e": 25625, "s": 25616, "text": "Output: " }, { "code": null, "e": 25654, "s": 25625, "text": "Odd Digits: 3\nEven Digits: 3" }, { "code": null, "e": 25667, "s": 25654, "text": "Akanksha_Rai" }, { "code": null, "e": 25675, "s": 25667, "text": "clintra" }, { "code": null, "e": 25686, "s": 25675, "text": "SQL-PL/SQL" }, { "code": null, "e": 25690, "s": 25686, "text": "SQL" }, { "code": null, "e": 25694, "s": 25690, "text": "SQL" }, { "code": null, "e": 25792, "s": 25694, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25801, "s": 25792, "text": "Comments" }, { "code": null, "e": 25814, "s": 25801, "text": "Old Comments" }, { "code": null, "e": 25826, "s": 25814, "text": "SQL | Views" }, { "code": null, "e": 25865, "s": 25826, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 25876, "s": 25865, "text": "CTE in SQL" }, { "code": null, "e": 25900, "s": 25876, "text": "SQL Interview Questions" }, { "code": null, "e": 25966, "s": 25900, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 26019, "s": 25966, "text": "How to Alter Multiple Columns at Once in SQL Server?" }, { "code": null, "e": 26064, "s": 26019, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 26097, "s": 26064, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 26129, "s": 26097, "text": "MySQL | Group_CONCAT() Function" } ]
Case-insensitive Dictionary in C#
To compare, ignoring case, use the case-insensitive Dictionary. While declaring a Dictionary, set the following property to get case-insensitive Dictionary − StringComparer.OrdinalIgnoreCase Add the property like this − Dictionary <string, int> dict = new Dictionary <string, int> (StringComparer.OrdinalIgnoreCase); Here is the complete code − Live Demo using System; using System.Collections.Generic; public class Program { public static void Main() { Dictionary <string, int> dict = new Dictionary <string, int> (StringComparer.OrdinalIgnoreCase); dict.Add("cricket", 1); dict.Add("football", 2); foreach (var val in dict) { Console.WriteLine(val.ToString()); } // case insensitive dictionary i.e. "cricket" is equal to "CRICKET" Console.WriteLine(dict["cricket"]); Console.WriteLine(dict["CRICKET"]); } } [cricket, 1] [football, 2] 1 1
[ { "code": null, "e": 1126, "s": 1062, "text": "To compare, ignoring case, use the case-insensitive Dictionary." }, { "code": null, "e": 1220, "s": 1126, "text": "While declaring a Dictionary, set the following property to get case-insensitive Dictionary −" }, { "code": null, "e": 1253, "s": 1220, "text": "StringComparer.OrdinalIgnoreCase" }, { "code": null, "e": 1282, "s": 1253, "text": "Add the property like this −" }, { "code": null, "e": 1379, "s": 1282, "text": "Dictionary <string, int> dict = new Dictionary <string, int> (StringComparer.OrdinalIgnoreCase);" }, { "code": null, "e": 1407, "s": 1379, "text": "Here is the complete code −" }, { "code": null, "e": 1418, "s": 1407, "text": " Live Demo" }, { "code": null, "e": 1941, "s": 1418, "text": "using System;\nusing System.Collections.Generic;\npublic class Program {\n public static void Main() {\n Dictionary <string, int> dict = new Dictionary <string, int> (StringComparer.OrdinalIgnoreCase);\n dict.Add(\"cricket\", 1);\n dict.Add(\"football\", 2);\n foreach (var val in dict) {\n Console.WriteLine(val.ToString());\n }\n // case insensitive dictionary i.e. \"cricket\" is equal to \"CRICKET\"\n Console.WriteLine(dict[\"cricket\"]);\n Console.WriteLine(dict[\"CRICKET\"]);\n }\n}" }, { "code": null, "e": 1972, "s": 1941, "text": "[cricket, 1]\n[football, 2]\n1\n1" } ]
Analyzing selling price of used cars using Python - GeeksforGeeks
12 Dec, 2019 Now-a-days, with the technological advancement, Techniques like Machine Learning, etc are being used on a large scale in many organisations. These models usually work with a set of predefined data-points available in the form of datasets. These datasets contain the past/previous information on a specific domain. Organising these datapoints before it is fed to the model is very important. This is where we use Data Analysis. If the data fed to the machine learning model is not well organised, it gives out false or undesired output. This can cause major losses to the organisation. Hence making use of proper data analysis is very important. About Dataset: The data that we are going to use in this example is about cars. Specifically containing various information datapoints about the used cars, like their price, color, etc. Here we need to understand that simply collecting data isn’t enough. Raw data isn’t useful. Here data analysis plays a vital role in unlocking the information that we require and to gain new insights into this raw data. Consider this scenario, our friend, Otis, wants to sell his car. But he doesn’t know how much should he sell his car for! He wants to maximize the profit but he also wants it to be sold for a reasonable price for someone who would want to own it. So here, us, being a data scientist, we can help our friend Otis. Let’s think like data scientists and clearly define some of his problems: For example, is there data on the prices of other cars and their characteristics? What features of cars affect their prices? Colour? Brand? Does horsepower also affect the selling price, or perhaps, something else? As a data analyst or data scientist, these are some of the questions we can start thinking about. To answer these questions, we’re going to need some data. But this data is in raw form. Hence we need to analyze it first. The data is available in the form of .csv/.data format with us To download the file used in this example click here. The file provided is in the .data format. Follow the below process for converting a .data file to .csv file. Process to convert .data file to .csv: open MS ExcelGo to DATASelect From textCheck box tick on comas(only)Save as .csv to your desired location on your pc! open MS Excel Go to DATA Select From text Check box tick on comas(only) Save as .csv to your desired location on your pc! Modules needed: pandas: Pandas is an opensource library that allows you to perform data manipulation in Python. Pandas provide an easy way to create, manipulate and wrangle the data. numpy: Numpy is the fundamental package for scientific computing with Python. numpy can be used as an efficient multi-dimensional container of generic data. matplotlib: Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of formats. seaborn: Seaborn is a Python data-visualization library that is based on matplotlib. Seaborn provides a high-level interface for drawing attractive and informative statistical graphics. scipy: Scipy is a Python-based ecosystem of open-source software for mathematics, science, and engineering. Steps for installing these packages: If you are using anaconda- jupyter/ syder or any other third party softwares to write your python code, make sure to set the path to the “scripts folder” of that software in command prompt of your pc. Then type – pip install package-nameExample:pip install numpy pip install numpy Then after the installation is done. (Make sure you are connected to the internet!!) Open your IDE, then import those packages. To import, type – import package nameExample:import numpy import numpy Steps that are used in the following code (Short description): Import the packages Set the path to the data file(.csv file) Find if there are any null data or NaN data in our file. If any, remove them Perform various data cleaning and data visualisation operations on your data. These steps are illustrated beside each line of code in the form of comments for better understanding, as it would be better to see the code side by side than explaining it entirely here, would be meaningless. Obtain the result! Lets start analyzing the data. Step 1: Import the modules needed. # importing sectionimport pandas as pd import numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport scipy as sp Step 2: Let’s check the first five entries of dataset. # using the Csv filedf = pd.read_csv('output.csv') # Checking the first 5 entries of datasetdf.head() Output: Step 3: Defining headers for our dataset. headers = ["symboling", "normalized-losses", "make", "fuel-type", "aspiration","num-of-doors", "body-style","drive-wheels", "engine-location", "wheel-base","length", "width","height", "curb-weight", "engine-type","num-of-cylinders", "engine-size", "fuel-system","bore","stroke", "compression-ratio", "horsepower", "peak-rpm","city-mpg","highway-mpg","price"] df.columns=headersdf.head() Output: Step 4: Finding the missing value if any. data = df # Finding the missing valuesdata.isna().any() # Finding if missing values data.isnull().any() Output: Step 4: Converting mpg to L/100km and checking the data type of each column. # converting mpg to L / 100kmdata['city-mpg'] = 235 / df['city-mpg']data.rename(columns = {'city_mpg': "city-L / 100km"}, inplace = True) print(data.columns) # checking the data type of each columndata.dtypes Output: Step 5: Here, price is of object type(string), it should be int or float, so we need to change it data.price.unique() # Here it contains '?', so we Drop itdata = data[data.price != '?'] # checking it againdata.dtypes Output: Step 6: Normalizing values by using simple feature scaling method examples(do for the rest) and binning- grouping values data['length'] = data['length']/data['length'].max()data['width'] = data['width']/data['width'].max()data['height'] = data['height']/data['height'].max() # binning- grouping valuesbins = np.linspace(min(data['price']), max(data['price']), 4) group_names = ['Low', 'Medium', 'High']data['price-binned'] = pd.cut(data['price'], bins, labels = group_names, include_lowest = True) print(data['price-binned'])plt.hist(data['price-binned'])plt.show() Output: Step 7: Doing descriptive analysis of data categorical to numerical values. # categorical to numerical variablespd.get_dummies(data['fuel-type']).head() # descriptive analysis# NaN are skippeddata.describe() Output: Step 8: Plotting the data according to the price based on engine size. # examples of box plotplt.boxplot(data['price']) # by using seabornsns.boxplot(x ='drive-wheels', y ='price', data = data) # Predicting price based on engine size# Known on x and predictable on yplt.scatter(data['engine-size'], data['price'])plt.title('Scatterplot of Enginesize vs Price')plt.xlabel('Engine size')plt.ylabel('Price')plt.grid()plt.show() Output: Step 9: Grouping the data according to wheel, body-style and price. # Grouping Datatest = data[['drive-wheels', 'body-style', 'price']]data_grp = test.groupby(['drive-wheels', 'body-style'], as_index = False).mean() data_grp Output: Step 10: Using the pivot method and plotting the heatmap according to the data obtained by pivot method # pivot methoddata_pivot = data_grp.pivot(index = 'drive-wheels', columns = 'body-style')data_pivot # heatmap for visualizing dataplt.pcolor(data_pivot, cmap ='RdBu')plt.colorbar()plt.show() Output: Step 11: Obtaining the final result and showing it in the form of a graph. As the slope is increasing in a positive direction, it is a positive linear relationship. # Analysis of Variance- ANOVA# returns f-test and p-value# f-test = variance between sample group means divided by # variation within sample group# p-value = confidence degreedata_annova = data[['make', 'price']]grouped_annova = data_annova.groupby(['make'])annova_results_l = sp.stats.f_oneway( grouped_annova.get_group('honda')['price'], grouped_annova.get_group('subaru')['price'] )print(annova_results_l) # strong corealtion between a categorical variable# if annova test gives large f-test and small p-value # Correlation- measures dependency, not causationsns.regplot(x ='engine-size', y ='price', data = data)plt.ylim(0, ) Output: Python-matplotlib Python-numpy Python-pandas Python-scipy Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 30326, "s": 30298, "text": "\n12 Dec, 2019" }, { "code": null, "e": 30971, "s": 30326, "text": "Now-a-days, with the technological advancement, Techniques like Machine Learning, etc are being used on a large scale in many organisations. These models usually work with a set of predefined data-points available in the form of datasets. These datasets contain the past/previous information on a specific domain. Organising these datapoints before it is fed to the model is very important. This is where we use Data Analysis. If the data fed to the machine learning model is not well organised, it gives out false or undesired output. This can cause major losses to the organisation. Hence making use of proper data analysis is very important." }, { "code": null, "e": 30986, "s": 30971, "text": "About Dataset:" }, { "code": null, "e": 31377, "s": 30986, "text": "The data that we are going to use in this example is about cars. Specifically containing various information datapoints about the used cars, like their price, color, etc. Here we need to understand that simply collecting data isn’t enough. Raw data isn’t useful. Here data analysis plays a vital role in unlocking the information that we require and to gain new insights into this raw data." }, { "code": null, "e": 31690, "s": 31377, "text": "Consider this scenario, our friend, Otis, wants to sell his car. But he doesn’t know how much should he sell his car for! He wants to maximize the profit but he also wants it to be sold for a reasonable price for someone who would want to own it. So here, us, being a data scientist, we can help our friend Otis." }, { "code": null, "e": 31979, "s": 31690, "text": "Let’s think like data scientists and clearly define some of his problems: For example, is there data on the prices of other cars and their characteristics? What features of cars affect their prices? Colour? Brand? Does horsepower also affect the selling price, or perhaps, something else?" }, { "code": null, "e": 32263, "s": 31979, "text": "As a data analyst or data scientist, these are some of the questions we can start thinking about. To answer these questions, we’re going to need some data. But this data is in raw form. Hence we need to analyze it first. The data is available in the form of .csv/.data format with us" }, { "code": null, "e": 32426, "s": 32263, "text": "To download the file used in this example click here. The file provided is in the .data format. Follow the below process for converting a .data file to .csv file." }, { "code": null, "e": 32465, "s": 32426, "text": "Process to convert .data file to .csv:" }, { "code": null, "e": 32583, "s": 32465, "text": "open MS ExcelGo to DATASelect From textCheck box tick on comas(only)Save as .csv to your desired location on your pc!" }, { "code": null, "e": 32597, "s": 32583, "text": "open MS Excel" }, { "code": null, "e": 32608, "s": 32597, "text": "Go to DATA" }, { "code": null, "e": 32625, "s": 32608, "text": "Select From text" }, { "code": null, "e": 32655, "s": 32625, "text": "Check box tick on comas(only)" }, { "code": null, "e": 32705, "s": 32655, "text": "Save as .csv to your desired location on your pc!" }, { "code": null, "e": 32721, "s": 32705, "text": "Modules needed:" }, { "code": null, "e": 32888, "s": 32721, "text": "pandas: Pandas is an opensource library that allows you to perform data manipulation in Python. Pandas provide an easy way to create, manipulate and wrangle the data." }, { "code": null, "e": 33045, "s": 32888, "text": "numpy: Numpy is the fundamental package for scientific computing with Python. numpy can be used as an efficient multi-dimensional container of generic data." }, { "code": null, "e": 33168, "s": 33045, "text": "matplotlib: Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of formats." }, { "code": null, "e": 33354, "s": 33168, "text": "seaborn: Seaborn is a Python data-visualization library that is based on matplotlib. Seaborn provides a high-level interface for drawing attractive and informative statistical graphics." }, { "code": null, "e": 33462, "s": 33354, "text": "scipy: Scipy is a Python-based ecosystem of open-source software for mathematics, science, and engineering." }, { "code": null, "e": 33499, "s": 33462, "text": "Steps for installing these packages:" }, { "code": null, "e": 33700, "s": 33499, "text": "If you are using anaconda- jupyter/ syder or any other third party softwares to write your python code, make sure to set the path to the “scripts folder” of that software in command prompt of your pc." }, { "code": null, "e": 33763, "s": 33700, "text": "Then type – pip install package-nameExample:pip install numpy\n" }, { "code": null, "e": 33782, "s": 33763, "text": "pip install numpy\n" }, { "code": null, "e": 33969, "s": 33782, "text": "Then after the installation is done. (Make sure you are connected to the internet!!) Open your IDE, then import those packages. To import, type – import package nameExample:import numpy\n" }, { "code": null, "e": 33983, "s": 33969, "text": "import numpy\n" }, { "code": null, "e": 34046, "s": 33983, "text": "Steps that are used in the following code (Short description):" }, { "code": null, "e": 34066, "s": 34046, "text": "Import the packages" }, { "code": null, "e": 34107, "s": 34066, "text": "Set the path to the data file(.csv file)" }, { "code": null, "e": 34184, "s": 34107, "text": "Find if there are any null data or NaN data in our file. If any, remove them" }, { "code": null, "e": 34472, "s": 34184, "text": "Perform various data cleaning and data visualisation operations on your data. These steps are illustrated beside each line of code in the form of comments for better understanding, as it would be better to see the code side by side than explaining it entirely here, would be meaningless." }, { "code": null, "e": 34491, "s": 34472, "text": "Obtain the result!" }, { "code": null, "e": 34522, "s": 34491, "text": "Lets start analyzing the data." }, { "code": null, "e": 34557, "s": 34522, "text": "Step 1: Import the modules needed." }, { "code": "# importing sectionimport pandas as pd import numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport scipy as sp", "e": 34685, "s": 34557, "text": null }, { "code": null, "e": 34740, "s": 34685, "text": "Step 2: Let’s check the first five entries of dataset." }, { "code": "# using the Csv filedf = pd.read_csv('output.csv') # Checking the first 5 entries of datasetdf.head()", "e": 34844, "s": 34740, "text": null }, { "code": null, "e": 34852, "s": 34844, "text": "Output:" }, { "code": null, "e": 34894, "s": 34852, "text": "Step 3: Defining headers for our dataset." }, { "code": "headers = [\"symboling\", \"normalized-losses\", \"make\", \"fuel-type\", \"aspiration\",\"num-of-doors\", \"body-style\",\"drive-wheels\", \"engine-location\", \"wheel-base\",\"length\", \"width\",\"height\", \"curb-weight\", \"engine-type\",\"num-of-cylinders\", \"engine-size\", \"fuel-system\",\"bore\",\"stroke\", \"compression-ratio\", \"horsepower\", \"peak-rpm\",\"city-mpg\",\"highway-mpg\",\"price\"] df.columns=headersdf.head()", "e": 35344, "s": 34894, "text": null }, { "code": null, "e": 35352, "s": 35344, "text": "Output:" }, { "code": null, "e": 35394, "s": 35352, "text": "Step 4: Finding the missing value if any." }, { "code": "data = df # Finding the missing valuesdata.isna().any() # Finding if missing values data.isnull().any() ", "e": 35501, "s": 35394, "text": null }, { "code": null, "e": 35509, "s": 35501, "text": "Output:" }, { "code": null, "e": 35586, "s": 35509, "text": "Step 4: Converting mpg to L/100km and checking the data type of each column." }, { "code": "# converting mpg to L / 100kmdata['city-mpg'] = 235 / df['city-mpg']data.rename(columns = {'city_mpg': \"city-L / 100km\"}, inplace = True) print(data.columns) # checking the data type of each columndata.dtypes ", "e": 35798, "s": 35586, "text": null }, { "code": null, "e": 35806, "s": 35798, "text": "Output:" }, { "code": null, "e": 35904, "s": 35806, "text": "Step 5: Here, price is of object type(string), it should be int or float, so we need to change it" }, { "code": "data.price.unique() # Here it contains '?', so we Drop itdata = data[data.price != '?'] # checking it againdata.dtypes", "e": 36025, "s": 35904, "text": null }, { "code": null, "e": 36033, "s": 36025, "text": "Output:" }, { "code": null, "e": 36154, "s": 36033, "text": "Step 6: Normalizing values by using simple feature scaling method examples(do for the rest) and binning- grouping values" }, { "code": "data['length'] = data['length']/data['length'].max()data['width'] = data['width']/data['width'].max()data['height'] = data['height']/data['height'].max() # binning- grouping valuesbins = np.linspace(min(data['price']), max(data['price']), 4) group_names = ['Low', 'Medium', 'High']data['price-binned'] = pd.cut(data['price'], bins, labels = group_names, include_lowest = True) print(data['price-binned'])plt.hist(data['price-binned'])plt.show()", "e": 36661, "s": 36154, "text": null }, { "code": null, "e": 36669, "s": 36661, "text": "Output:" }, { "code": null, "e": 36745, "s": 36669, "text": "Step 7: Doing descriptive analysis of data categorical to numerical values." }, { "code": "# categorical to numerical variablespd.get_dummies(data['fuel-type']).head() # descriptive analysis# NaN are skippeddata.describe()", "e": 36878, "s": 36745, "text": null }, { "code": null, "e": 36886, "s": 36878, "text": "Output:" }, { "code": null, "e": 36957, "s": 36886, "text": "Step 8: Plotting the data according to the price based on engine size." }, { "code": "# examples of box plotplt.boxplot(data['price']) # by using seabornsns.boxplot(x ='drive-wheels', y ='price', data = data) # Predicting price based on engine size# Known on x and predictable on yplt.scatter(data['engine-size'], data['price'])plt.title('Scatterplot of Enginesize vs Price')plt.xlabel('Engine size')plt.ylabel('Price')plt.grid()plt.show()", "e": 37313, "s": 36957, "text": null }, { "code": null, "e": 37321, "s": 37313, "text": "Output:" }, { "code": null, "e": 37389, "s": 37321, "text": "Step 9: Grouping the data according to wheel, body-style and price." }, { "code": "# Grouping Datatest = data[['drive-wheels', 'body-style', 'price']]data_grp = test.groupby(['drive-wheels', 'body-style'], as_index = False).mean() data_grp", "e": 37572, "s": 37389, "text": null }, { "code": null, "e": 37580, "s": 37572, "text": "Output:" }, { "code": null, "e": 37684, "s": 37580, "text": "Step 10: Using the pivot method and plotting the heatmap according to the data obtained by pivot method" }, { "code": "# pivot methoddata_pivot = data_grp.pivot(index = 'drive-wheels', columns = 'body-style')data_pivot # heatmap for visualizing dataplt.pcolor(data_pivot, cmap ='RdBu')plt.colorbar()plt.show()", "e": 37903, "s": 37684, "text": null }, { "code": null, "e": 37911, "s": 37903, "text": "Output:" }, { "code": null, "e": 38076, "s": 37911, "text": "Step 11: Obtaining the final result and showing it in the form of a graph. As the slope is increasing in a positive direction, it is a positive linear relationship." }, { "code": "# Analysis of Variance- ANOVA# returns f-test and p-value# f-test = variance between sample group means divided by # variation within sample group# p-value = confidence degreedata_annova = data[['make', 'price']]grouped_annova = data_annova.groupby(['make'])annova_results_l = sp.stats.f_oneway( grouped_annova.get_group('honda')['price'], grouped_annova.get_group('subaru')['price'] )print(annova_results_l) # strong corealtion between a categorical variable# if annova test gives large f-test and small p-value # Correlation- measures dependency, not causationsns.regplot(x ='engine-size', y ='price', data = data)plt.ylim(0, )", "e": 38799, "s": 38076, "text": null }, { "code": null, "e": 38807, "s": 38799, "text": "Output:" }, { "code": null, "e": 38825, "s": 38807, "text": "Python-matplotlib" }, { "code": null, "e": 38838, "s": 38825, "text": "Python-numpy" }, { "code": null, "e": 38852, "s": 38838, "text": "Python-pandas" }, { "code": null, "e": 38865, "s": 38852, "text": "Python-scipy" }, { "code": null, "e": 38872, "s": 38865, "text": "Python" }, { "code": null, "e": 38891, "s": 38872, "text": "Technical Scripter" }, { "code": null, "e": 38989, "s": 38891, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38998, "s": 38989, "text": "Comments" }, { "code": null, "e": 39011, "s": 38998, "text": "Old Comments" }, { "code": null, "e": 39039, "s": 39011, "text": "Read JSON file using Python" }, { "code": null, "e": 39089, "s": 39039, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 39111, "s": 39089, "text": "Python map() function" }, { "code": null, "e": 39155, "s": 39111, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 39173, "s": 39155, "text": "Python Dictionary" }, { "code": null, "e": 39196, "s": 39173, "text": "Taking input in Python" }, { "code": null, "e": 39231, "s": 39196, "text": "Read a file line by line in Python" }, { "code": null, "e": 39253, "s": 39231, "text": "Enumerate() in Python" }, { "code": null, "e": 39285, "s": 39253, "text": "How to Install PIP on Windows ?" } ]
GATE | GATE CS 2019 | Question 24 - GeeksforGeeks
01 Oct, 2021 For Σ = {a, b}, let us consider the regular language L = {x ∣ x = a2 + 3k or x = b10 + 12k, k ≥ 0} Which one of the following can be a pumping length (the constant guaranteed by the pumping lemma) for L?(A) 3(B) 5(C) 9(D) 24Answer: (D)Explanation: According to Pumping lemma, there must be repeation (DFA then it repeats some states, and regular grammar repeats its nonterminal in derivation.) for all acceptable stings. Therefore, minimum Pumping Length should be 11, because string with length 10 (i.e., w = b10) does not repeat anything, but string with length 11 (i.e., w = b11) will repeat states. Therefore, pumping length for given language should greater than 10, which is 24. Option (D) is correct. YouTubeGeeksforGeeks GATE Computer Science16.3K subscribersGATE PYQ's on Grammars with Praddyumn Shukla | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:003:22 / 1:02:45•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=zAzS1PzU0NQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25649, "s": 25621, "text": "\n01 Oct, 2021" }, { "code": null, "e": 25702, "s": 25649, "text": "For Σ = {a, b}, let us consider the regular language" }, { "code": null, "e": 25749, "s": 25702, "text": "L = {x ∣ x = a2 + 3k or x = b10 + 12k, k ≥ 0} " }, { "code": null, "e": 26071, "s": 25749, "text": "Which one of the following can be a pumping length (the constant guaranteed by the pumping lemma) for L?(A) 3(B) 5(C) 9(D) 24Answer: (D)Explanation: According to Pumping lemma, there must be repeation (DFA then it repeats some states, and regular grammar repeats its nonterminal in derivation.) for all acceptable stings." }, { "code": null, "e": 26253, "s": 26071, "text": "Therefore, minimum Pumping Length should be 11, because string with length 10 (i.e., w = b10) does not repeat anything, but string with length 11 (i.e., w = b11) will repeat states." }, { "code": null, "e": 26335, "s": 26253, "text": "Therefore, pumping length for given language should greater than 10, which is 24." }, { "code": null, "e": 26358, "s": 26335, "text": "Option (D) is correct." }, { "code": null, "e": 27253, "s": 26358, "text": "YouTubeGeeksforGeeks GATE Computer Science16.3K subscribersGATE PYQ's on Grammars with Praddyumn Shukla | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:003:22 / 1:02:45•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=zAzS1PzU0NQ\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 27258, "s": 27253, "text": "GATE" }, { "code": null, "e": 27356, "s": 27258, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27390, "s": 27356, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 27424, "s": 27390, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 27458, "s": 27424, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 27491, "s": 27458, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 27527, "s": 27491, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 27561, "s": 27527, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 27597, "s": 27561, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 27631, "s": 27597, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 27665, "s": 27631, "text": "GATE | GATE-CS-2009 | Question 38" } ]
VBA - Minute Function
The Minute Function returns a number between 0 and 59 that represents the minute of the hour for the specified time stamp. Minute(time) Add a button and add the following function. Private Sub Constant_demo_Click() msgbox("Line 1: " & Minute("3:13:45 PM")) msgbox("Line 2: " & Minute("23:43:45")) msgbox("Line 3: " & Minute("2:20 PM")) End Sub When you execute the above function, it produces the following output. Line 1: 13 Line 2: 43 Line 3: 20 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": 2058, "s": 1935, "text": "The Minute Function returns a number between 0 and 59 that represents the minute of the hour for the specified time stamp." }, { "code": null, "e": 2073, "s": 2058, "text": "Minute(time) \n" }, { "code": null, "e": 2118, "s": 2073, "text": "Add a button and add the following function." }, { "code": null, "e": 2290, "s": 2118, "text": "Private Sub Constant_demo_Click()\n msgbox(\"Line 1: \" & Minute(\"3:13:45 PM\"))\n msgbox(\"Line 2: \" & Minute(\"23:43:45\"))\n msgbox(\"Line 3: \" & Minute(\"2:20 PM\"))\nEnd Sub" }, { "code": null, "e": 2361, "s": 2290, "text": "When you execute the above function, it produces the following output." }, { "code": null, "e": 2395, "s": 2361, "text": "Line 1: 13\nLine 2: 43\nLine 3: 20\n" }, { "code": null, "e": 2429, "s": 2395, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 2444, "s": 2429, "text": " Pavan Lalwani" }, { "code": null, "e": 2477, "s": 2444, "text": "\n 41 Lectures \n 3 hours \n" }, { "code": null, "e": 2492, "s": 2477, "text": " Arnold Higuit" }, { "code": null, "e": 2527, "s": 2492, "text": "\n 80 Lectures \n 5.5 hours \n" }, { "code": null, "e": 2545, "s": 2527, "text": " Prashant Panchal" }, { "code": null, "e": 2578, "s": 2545, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 2596, "s": 2578, "text": " Prashant Panchal" }, { "code": null, "e": 2629, "s": 2596, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 2644, "s": 2629, "text": " Arnold Higuit" }, { "code": null, "e": 2680, "s": 2644, "text": "\n 92 Lectures \n 10.5 hours \n" }, { "code": null, "e": 2708, "s": 2680, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 2715, "s": 2708, "text": " Print" }, { "code": null, "e": 2726, "s": 2715, "text": " Add Notes" } ]
Commonly Asked Data Structure Interview Questions | Set 1 - GeeksforGeeks
28 Jun, 2021 What is a Data Structure? A data structure is a way of organizing the data so that the data can be used efficiently. Different kinds of data structures are suited to different kinds of applications, and some are highly specialized to specific tasks. For example, B-trees are particularly well-suited for the implementation of databases, while compiler implementations usually use hash tables to look up identifiers. (Source: Wiki Page) What are linear and non-linear data Structures? Linear: A data structure is said to be linear if its elements form a sequence or a linear list. Examples: Array. Linked List, Stacks and Queues Non-Linear: A data structure is said to be non-linear if the traversal of nodes is nonlinear in nature. Example: Graph and Trees. What are the various operations that can be performed on different Data Structures? Insertion ? Add a new data item in the given collection of data items. Deletion ? Delete an existing data item from the given collection of data items. Traversal ? Access each data item exactly once so that it can be processed. Searching ? Find out the location of the data item if it exists in the given collection of data items. Sorting ? Arranging the data items in some order i.e. in ascending or descending order in case of numerical data and in dictionary order in case of alphanumeric data. How is an Array different from Linked List? The size of the arrays is fixed, Linked Lists are Dynamic in size. Inserting and deleting a new element in an array of elements is expensive, Whereas both insertion and deletion can easily be done in Linked Lists. Random access is not allowed in Linked Listed. Extra memory space for a pointer is required with each element of the Linked list. Arrays have better cache locality that can make a pretty big difference in performance. What is Stack and where it can be used? Stack is a linear data structure which the order LIFO(Last In First Out) or FILO(First In Last Out) for accessing elements. Basic operations of the stack are: Push, Pop, Peek Applications of Stack: Infix to Postfix Conversion using StackEvaluation of Postfix ExpressionReverse a String using StackImplement two stacks in an arrayCheck for balanced parentheses in an expression Infix to Postfix Conversion using Stack Evaluation of Postfix Expression Reverse a String using Stack Implement two stacks in an array Check for balanced parentheses in an expression What is a Queue, how it is different from the stack and how is it implemented? Queue is a linear structure that follows the order is First In First Out (FIFO) to access elements. Mainly the following are basic operations on queue: Enqueue, Dequeue, Front, Rear The difference between stacks and queues is in removing. In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added. Both Queues and Stacks can be implemented using Arrays and Linked Lists. What are Infix, prefix, Postfix notations? Infix notation: X + Y – Operators are written in-between their operands. This is the usual way we write expressions. An expression such as A * ( B + C ) / D Postfix notation (also known as “Reverse Polish notation”): X Y + Operators are written after their operands. The infix expression given above is equivalent to A B C + * D/ Prefix notation (also known as “Polish notation”): + X Y Operators are written before their operands. The expressions given above are equivalent to / A * + B C D Converting between these notations: Click here What is a Linked List and What are its types? A linked list is a linear data structure (like arrays) where each element is a separate object. Each element (that is node) of a list is comprising of two items – the data and a reference to the next node.Types of Linked List : Singly Linked List : In this type of linked list, every node stores address or reference of next node in list and the last node has next address or reference as NULL. For example 1->2->3->4->NULLDoubly Linked List : Here, here are two references associated with each node, One of the reference points to the next node and one to the previous node. Eg. NULL<-1<->2<->3->NULLCircular Linked List : Circular linked list is a linked list where all nodes are connected to form a circle. There is no NULL at the end. A circular linked list can be a singly circular linked list or doubly circular linked list. Eg. 1->2->3->1 [The next pointer of last node is pointing to the first] Singly Linked List : In this type of linked list, every node stores address or reference of next node in list and the last node has next address or reference as NULL. For example 1->2->3->4->NULL Doubly Linked List : Here, here are two references associated with each node, One of the reference points to the next node and one to the previous node. Eg. NULL<-1<->2<->3->NULL Circular Linked List : Circular linked list is a linked list where all nodes are connected to form a circle. There is no NULL at the end. A circular linked list can be a singly circular linked list or doubly circular linked list. Eg. 1->2->3->1 [The next pointer of last node is pointing to the first] Which data structures are used for BFS and DFS of a graph? Queue is used for BFS Stack is used for DFS. DFS can also be implemented using recursion (Note that recursion also uses function call stack). Can doubly linked be implemented using a single pointer variable in every node? Doubly linked list can be implemented using a single pointer. See XOR Linked List – A Memory Efficient Doubly Linked List How to implement a stack using queue? A stack can be implemented using two queues. Let stack to be implemented be ‘s’ and queues used to implement be ‘q1’ and ‘q2’. Stack ‘s’ can be implemented in two ways: Method 1 (By making push operation costly) Method 2 (By making pop operation costly) See Implement Stack using Queues How to implement a queue using stack? A queue can be implemented using two stacks. Let queue to be implemented be q and stacks used to implement q be stack1 and stack2. q can be implemented in two ways: Method 1 (By making enQueue operation costly) Method 2 (By making deQueue operation costly) See Implement Queue using Stacks Which Data Structure Should be used for implementing LRU cache? We use two data structures to implement an LRU Cache. Queue which is implemented using a doubly linked list. The maximum size of the queue will be equal to the total number of frames available (cache size). The most recently used pages will be near rear end and least recently pages will be near front end.A Hash with page number as key and address of the corresponding queue node as value. See How to implement LRU caching scheme? What data structures should be used? Queue which is implemented using a doubly linked list. The maximum size of the queue will be equal to the total number of frames available (cache size). The most recently used pages will be near rear end and least recently pages will be near front end. A Hash with page number as key and address of the corresponding queue node as value. See How to implement LRU caching scheme? What data structures should be used? How to check if a given Binary Tree is BST or not? If inorder traversal of a binary tree is sorted, then the binary tree is BST. The idea is to simply do inorder traversal and while traversing keep track of previous key value. If current key value is greater, then continue, else return false. See A program to check if a binary tree is BST or not for more details. Linked List Questions Linked List Insertion Linked List Deletion middle of a given linked list Nth node from the end of a Linked List Tree Traversal Questions Inorder Preorder and Postoder Traversals Level order traversal Height of Binary Tree Convert a DLL to Binary Tree in-place See In-place conversion of Sorted DLL to Balanced BST Convert Binary Tree to DLL in-place See Convert a given Binary Tree to Doubly Linked List | Set 1, Convert a given Binary Tree to Doubly Linked List | Set 2 Delete a given node in a singly linked list Given only a pointer to a node to be deleted in a singly linked list, how do you delete it? Reverse a Linked List Write a function to reverse a linked list Detect Loop in a Linked List Write a C function to detect loop in a linked list. Which data structure is used for dictionary and spell checker? Data Structure for Dictionary and Spell Checker? You may also like Practice Quizzes on Data Structures Last Minute Notes – DS Common Interview Puzzles Amazon’s most asked interview questions Microsoft’s most asked interview questions Accenture’s most asked Interview Questions Commonly Asked OOP Interview Questions Commonly Asked C++ Interview Questions, Commonly Asked C Programming Interview Questions | Set 1 Commonly Asked C Programming Interview Questions | Set 2 Commonly asked DBMS interview questions | Set 1 Commonly Asked Operating Systems Interview Questions | Set 1 Commonly Asked Data Structure Interview Questions Commonly Asked Algorithm Interview Questions Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above shashikantdurge ShashankeshUpadhyay albatrossbk interview-preparation placement preparation Articles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Mutex vs Semaphore Time Complexity and Space Complexity Understanding "extern" keyword in C How to write a Pseudo Code? SQL | Views Analysis of Algorithms | Set 2 (Worst, Average and Best Cases) SQL Interview Questions SQL | GROUP BY Little and Big Endian Mystery Recursive Practice Problems with Solutions
[ { "code": null, "e": 25082, "s": 25054, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25519, "s": 25082, "text": "What is a Data Structure? A data structure is a way of organizing the data so that the data can be used efficiently. Different kinds of data structures are suited to different kinds of applications, and some are highly specialized to specific tasks. For example, B-trees are particularly well-suited for the implementation of databases, while compiler implementations usually use hash tables to look up identifiers. (Source: Wiki Page) " }, { "code": null, "e": 25568, "s": 25519, "text": "What are linear and non-linear data Structures? " }, { "code": null, "e": 25712, "s": 25568, "text": "Linear: A data structure is said to be linear if its elements form a sequence or a linear list. Examples: Array. Linked List, Stacks and Queues" }, { "code": null, "e": 25842, "s": 25712, "text": "Non-Linear: A data structure is said to be non-linear if the traversal of nodes is nonlinear in nature. Example: Graph and Trees." }, { "code": null, "e": 25927, "s": 25842, "text": "What are the various operations that can be performed on different Data Structures? " }, { "code": null, "e": 25998, "s": 25927, "text": "Insertion ? Add a new data item in the given collection of data items." }, { "code": null, "e": 26079, "s": 25998, "text": "Deletion ? Delete an existing data item from the given collection of data items." }, { "code": null, "e": 26155, "s": 26079, "text": "Traversal ? Access each data item exactly once so that it can be processed." }, { "code": null, "e": 26258, "s": 26155, "text": "Searching ? Find out the location of the data item if it exists in the given collection of data items." }, { "code": null, "e": 26425, "s": 26258, "text": "Sorting ? Arranging the data items in some order i.e. in ascending or descending order in case of numerical data and in dictionary order in case of alphanumeric data." }, { "code": null, "e": 26470, "s": 26425, "text": "How is an Array different from Linked List? " }, { "code": null, "e": 26537, "s": 26470, "text": "The size of the arrays is fixed, Linked Lists are Dynamic in size." }, { "code": null, "e": 26684, "s": 26537, "text": "Inserting and deleting a new element in an array of elements is expensive, Whereas both insertion and deletion can easily be done in Linked Lists." }, { "code": null, "e": 26731, "s": 26684, "text": "Random access is not allowed in Linked Listed." }, { "code": null, "e": 26814, "s": 26731, "text": "Extra memory space for a pointer is required with each element of the Linked list." }, { "code": null, "e": 26902, "s": 26814, "text": "Arrays have better cache locality that can make a pretty big difference in performance." }, { "code": null, "e": 27118, "s": 26902, "text": "What is Stack and where it can be used? Stack is a linear data structure which the order LIFO(Last In First Out) or FILO(First In Last Out) for accessing elements. Basic operations of the stack are: Push, Pop, Peek " }, { "code": null, "e": 27142, "s": 27118, "text": "Applications of Stack: " }, { "code": null, "e": 27321, "s": 27142, "text": "Infix to Postfix Conversion using StackEvaluation of Postfix ExpressionReverse a String using StackImplement two stacks in an arrayCheck for balanced parentheses in an expression" }, { "code": null, "e": 27361, "s": 27321, "text": "Infix to Postfix Conversion using Stack" }, { "code": null, "e": 27394, "s": 27361, "text": "Evaluation of Postfix Expression" }, { "code": null, "e": 27423, "s": 27394, "text": "Reverse a String using Stack" }, { "code": null, "e": 27456, "s": 27423, "text": "Implement two stacks in an array" }, { "code": null, "e": 27504, "s": 27456, "text": "Check for balanced parentheses in an expression" }, { "code": null, "e": 28008, "s": 27504, "text": "What is a Queue, how it is different from the stack and how is it implemented? Queue is a linear structure that follows the order is First In First Out (FIFO) to access elements. Mainly the following are basic operations on queue: Enqueue, Dequeue, Front, Rear The difference between stacks and queues is in removing. In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added. Both Queues and Stacks can be implemented using Arrays and Linked Lists. " }, { "code": null, "e": 28053, "s": 28008, "text": " What are Infix, prefix, Postfix notations? " }, { "code": null, "e": 28192, "s": 28053, "text": "Infix notation: X + Y – Operators are written in-between their operands. This is the usual way we write expressions. An expression such as" }, { "code": null, "e": 28213, "s": 28192, "text": " A * ( B + C ) / D" }, { "code": null, "e": 28373, "s": 28213, "text": "Postfix notation (also known as “Reverse Polish notation”): X Y + Operators are written after their operands. The infix expression given above is equivalent to" }, { "code": null, "e": 28389, "s": 28373, "text": " A B C + * D/" }, { "code": null, "e": 28537, "s": 28389, "text": "Prefix notation (also known as “Polish notation”): + X Y Operators are written before their operands. The expressions given above are equivalent to" }, { "code": null, "e": 28554, "s": 28537, "text": " / A * + B C D" }, { "code": null, "e": 28602, "s": 28554, "text": "Converting between these notations: Click here " }, { "code": null, "e": 28649, "s": 28602, "text": "What is a Linked List and What are its types? " }, { "code": null, "e": 28878, "s": 28649, "text": "A linked list is a linear data structure (like arrays) where each element is a separate object. Each element (that is node) of a list is comprising of two items – the data and a reference to the next node.Types of Linked List : " }, { "code": null, "e": 29553, "s": 28878, "text": "Singly Linked List : In this type of linked list, every node stores address or reference of next node in list and the last node has next address or reference as NULL. For example 1->2->3->4->NULLDoubly Linked List : Here, here are two references associated with each node, One of the reference points to the next node and one to the previous node. Eg. NULL<-1<->2<->3->NULLCircular Linked List : Circular linked list is a linked list where all nodes are connected to form a circle. There is no NULL at the end. A circular linked list can be a singly circular linked list or doubly circular linked list. Eg. 1->2->3->1 [The next pointer of last node is pointing to the first]" }, { "code": null, "e": 29749, "s": 29553, "text": "Singly Linked List : In this type of linked list, every node stores address or reference of next node in list and the last node has next address or reference as NULL. For example 1->2->3->4->NULL" }, { "code": null, "e": 29928, "s": 29749, "text": "Doubly Linked List : Here, here are two references associated with each node, One of the reference points to the next node and one to the previous node. Eg. NULL<-1<->2<->3->NULL" }, { "code": null, "e": 30230, "s": 29928, "text": "Circular Linked List : Circular linked list is a linked list where all nodes are connected to form a circle. There is no NULL at the end. A circular linked list can be a singly circular linked list or doubly circular linked list. Eg. 1->2->3->1 [The next pointer of last node is pointing to the first]" }, { "code": null, "e": 30290, "s": 30230, "text": "Which data structures are used for BFS and DFS of a graph? " }, { "code": null, "e": 30312, "s": 30290, "text": "Queue is used for BFS" }, { "code": null, "e": 30432, "s": 30312, "text": "Stack is used for DFS. DFS can also be implemented using recursion (Note that recursion also uses function call stack)." }, { "code": null, "e": 30635, "s": 30432, "text": "Can doubly linked be implemented using a single pointer variable in every node? Doubly linked list can be implemented using a single pointer. See XOR Linked List – A Memory Efficient Doubly Linked List " }, { "code": null, "e": 30843, "s": 30635, "text": "How to implement a stack using queue? A stack can be implemented using two queues. Let stack to be implemented be ‘s’ and queues used to implement be ‘q1’ and ‘q2’. Stack ‘s’ can be implemented in two ways: " }, { "code": null, "e": 30886, "s": 30843, "text": "Method 1 (By making push operation costly)" }, { "code": null, "e": 30961, "s": 30886, "text": "Method 2 (By making pop operation costly) See Implement Stack using Queues" }, { "code": null, "e": 31165, "s": 30961, "text": "How to implement a queue using stack? A queue can be implemented using two stacks. Let queue to be implemented be q and stacks used to implement q be stack1 and stack2. q can be implemented in two ways: " }, { "code": null, "e": 31211, "s": 31165, "text": "Method 1 (By making enQueue operation costly)" }, { "code": null, "e": 31290, "s": 31211, "text": "Method 2 (By making deQueue operation costly) See Implement Queue using Stacks" }, { "code": null, "e": 31356, "s": 31290, "text": "Which Data Structure Should be used for implementing LRU cache? " }, { "code": null, "e": 31410, "s": 31356, "text": "We use two data structures to implement an LRU Cache." }, { "code": null, "e": 31825, "s": 31410, "text": "Queue which is implemented using a doubly linked list. The maximum size of the queue will be equal to the total number of frames available (cache size). The most recently used pages will be near rear end and least recently pages will be near front end.A Hash with page number as key and address of the corresponding queue node as value. See How to implement LRU caching scheme? What data structures should be used?" }, { "code": null, "e": 32078, "s": 31825, "text": "Queue which is implemented using a doubly linked list. The maximum size of the queue will be equal to the total number of frames available (cache size). The most recently used pages will be near rear end and least recently pages will be near front end." }, { "code": null, "e": 32241, "s": 32078, "text": "A Hash with page number as key and address of the corresponding queue node as value. See How to implement LRU caching scheme? What data structures should be used?" }, { "code": null, "e": 32608, "s": 32241, "text": "How to check if a given Binary Tree is BST or not? If inorder traversal of a binary tree is sorted, then the binary tree is BST. The idea is to simply do inorder traversal and while traversing keep track of previous key value. If current key value is greater, then continue, else return false. See A program to check if a binary tree is BST or not for more details. " }, { "code": null, "e": 32631, "s": 32608, "text": "Linked List Questions " }, { "code": null, "e": 32653, "s": 32631, "text": "Linked List Insertion" }, { "code": null, "e": 32674, "s": 32653, "text": "Linked List Deletion" }, { "code": null, "e": 32704, "s": 32674, "text": "middle of a given linked list" }, { "code": null, "e": 32743, "s": 32704, "text": "Nth node from the end of a Linked List" }, { "code": null, "e": 32769, "s": 32743, "text": "Tree Traversal Questions " }, { "code": null, "e": 32777, "s": 32769, "text": "Inorder" }, { "code": null, "e": 32810, "s": 32777, "text": "Preorder and Postoder Traversals" }, { "code": null, "e": 32832, "s": 32810, "text": "Level order traversal" }, { "code": null, "e": 32854, "s": 32832, "text": "Height of Binary Tree" }, { "code": null, "e": 32947, "s": 32854, "text": "Convert a DLL to Binary Tree in-place See In-place conversion of Sorted DLL to Balanced BST " }, { "code": null, "e": 33105, "s": 32947, "text": "Convert Binary Tree to DLL in-place See Convert a given Binary Tree to Doubly Linked List | Set 1, Convert a given Binary Tree to Doubly Linked List | Set 2 " }, { "code": null, "e": 33242, "s": 33105, "text": "Delete a given node in a singly linked list Given only a pointer to a node to be deleted in a singly linked list, how do you delete it? " }, { "code": null, "e": 33307, "s": 33242, "text": "Reverse a Linked List Write a function to reverse a linked list " }, { "code": null, "e": 33389, "s": 33307, "text": "Detect Loop in a Linked List Write a C function to detect loop in a linked list. " }, { "code": null, "e": 33502, "s": 33389, "text": "Which data structure is used for dictionary and spell checker? Data Structure for Dictionary and Spell Checker? " }, { "code": null, "e": 33521, "s": 33502, "text": "You may also like " }, { "code": null, "e": 33557, "s": 33521, "text": "Practice Quizzes on Data Structures" }, { "code": null, "e": 33580, "s": 33557, "text": "Last Minute Notes – DS" }, { "code": null, "e": 33605, "s": 33580, "text": "Common Interview Puzzles" }, { "code": null, "e": 33645, "s": 33605, "text": "Amazon’s most asked interview questions" }, { "code": null, "e": 33688, "s": 33645, "text": "Microsoft’s most asked interview questions" }, { "code": null, "e": 33731, "s": 33688, "text": "Accenture’s most asked Interview Questions" }, { "code": null, "e": 33770, "s": 33731, "text": "Commonly Asked OOP Interview Questions" }, { "code": null, "e": 33810, "s": 33770, "text": "Commonly Asked C++ Interview Questions," }, { "code": null, "e": 33867, "s": 33810, "text": "Commonly Asked C Programming Interview Questions | Set 1" }, { "code": null, "e": 33924, "s": 33867, "text": "Commonly Asked C Programming Interview Questions | Set 2" }, { "code": null, "e": 33972, "s": 33924, "text": "Commonly asked DBMS interview questions | Set 1" }, { "code": null, "e": 34033, "s": 33972, "text": "Commonly Asked Operating Systems Interview Questions | Set 1" }, { "code": null, "e": 34083, "s": 34033, "text": "Commonly Asked Data Structure Interview Questions" }, { "code": null, "e": 34128, "s": 34083, "text": "Commonly Asked Algorithm Interview Questions" }, { "code": null, "e": 34253, "s": 34128, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 34269, "s": 34253, "text": "shashikantdurge" }, { "code": null, "e": 34289, "s": 34269, "text": "ShashankeshUpadhyay" }, { "code": null, "e": 34301, "s": 34289, "text": "albatrossbk" }, { "code": null, "e": 34323, "s": 34301, "text": "interview-preparation" }, { "code": null, "e": 34345, "s": 34323, "text": "placement preparation" }, { "code": null, "e": 34354, "s": 34345, "text": "Articles" }, { "code": null, "e": 34452, "s": 34354, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34471, "s": 34452, "text": "Mutex vs Semaphore" }, { "code": null, "e": 34508, "s": 34471, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 34544, "s": 34508, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 34572, "s": 34544, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 34584, "s": 34572, "text": "SQL | Views" }, { "code": null, "e": 34647, "s": 34584, "text": "Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)" }, { "code": null, "e": 34671, "s": 34647, "text": "SQL Interview Questions" }, { "code": null, "e": 34686, "s": 34671, "text": "SQL | GROUP BY" }, { "code": null, "e": 34716, "s": 34686, "text": "Little and Big Endian Mystery" } ]
C++ | References | Question 6 - GeeksforGeeks
28 Jun, 2021 Which of the following is FALSE about references in C++(A) References cannot be NULL(B) A reference must be initialized when declared(C) Once a reference is created, it cannot be later made to reference another object; it cannot be reset.(D) References cannot refer to constant valueAnswer: (D)Explanation: We can create a constant reference that refers to a constant. For example, the following program compiles and runs fine. #include<iostream> using namespace std; int main() { const int x = 10; const int& ref = x; cout << ref; return 0; } Quiz of this Question C++-References References C Language C++ Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Multithreading in C Exception Handling in C++ 'this' pointer in C++ Arrow operator -> in C/C++ with Examples C++ | Exception Handling | Question 3 C++ | new and delete | Question 4 C++ | Inheritance | Question 7 C++ | Operator Overloading | Question 10 C++ | Inheritance | Question 1
[ { "code": null, "e": 24232, "s": 24204, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24660, "s": 24232, "text": "Which of the following is FALSE about references in C++(A) References cannot be NULL(B) A reference must be initialized when declared(C) Once a reference is created, it cannot be later made to reference another object; it cannot be reset.(D) References cannot refer to constant valueAnswer: (D)Explanation: We can create a constant reference that refers to a constant. For example, the following program compiles and runs fine." }, { "code": null, "e": 24786, "s": 24660, "text": "#include<iostream>\nusing namespace std;\n\nint main()\n{\n const int x = 10;\n const int& ref = x;\n\n cout << ref;\n return 0;\n}" }, { "code": null, "e": 24808, "s": 24786, "text": "Quiz of this Question" }, { "code": null, "e": 24823, "s": 24808, "text": "C++-References" }, { "code": null, "e": 24834, "s": 24823, "text": "References" }, { "code": null, "e": 24845, "s": 24834, "text": "C Language" }, { "code": null, "e": 24854, "s": 24845, "text": "C++ Quiz" }, { "code": null, "e": 24952, "s": 24854, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24990, "s": 24952, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 25010, "s": 24990, "text": "Multithreading in C" }, { "code": null, "e": 25036, "s": 25010, "text": "Exception Handling in C++" }, { "code": null, "e": 25058, "s": 25036, "text": "'this' pointer in C++" }, { "code": null, "e": 25099, "s": 25058, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 25137, "s": 25099, "text": "C++ | Exception Handling | Question 3" }, { "code": null, "e": 25171, "s": 25137, "text": "C++ | new and delete | Question 4" }, { "code": null, "e": 25202, "s": 25171, "text": "C++ | Inheritance | Question 7" }, { "code": null, "e": 25243, "s": 25202, "text": "C++ | Operator Overloading | Question 10" } ]
Java - The Vector Class
Vector implements a dynamic array. It is similar to ArrayList, but with two differences − Vector is synchronized. Vector is synchronized. Vector contains many legacy methods that are not part of the collections framework. Vector contains many legacy methods that are not part of the collections framework. Vector proves to be very useful if you don't know the size of the array in advance or you just need one that can change sizes over the lifetime of a program. Following is the list of constructors provided by the vector class. Vector( ) This constructor creates a default vector, which has an initial size of 10. Vector(int size) This constructor accepts an argument that equals to the required size, and creates a vector whose initial capacity is specified by size. Vector(int size, int incr) This constructor creates a vector whose initial capacity is specified by size and whose increment is specified by incr. The increment specifies the number of elements to allocate each time that a vector is resized upward. Vector(Collection c) This constructor creates a vector that contains the elements of collection c. Apart from the methods inherited from its parent classes, Vector defines the following methods − void add(int index, Object element) Inserts the specified element at the specified position in this Vector. boolean add(Object o) Appends the specified element to the end of this Vector. boolean addAll(Collection c) Appends all of the elements in the specified Collection to the end of this Vector, in the order that they are returned by the specified Collection's Iterator. boolean addAll(int index, Collection c) Inserts all of the elements in in the specified Collection into this Vector at the specified position. void addElement(Object obj) Adds the specified component to the end of this vector, increasing its size by one. int capacity() Returns the current capacity of this vector. void clear() Removes all of the elements from this vector. Object clone() Returns a clone of this vector. boolean contains(Object elem) Tests if the specified object is a component in this vector. boolean containsAll(Collection c) Returns true if this vector contains all of the elements in the specified Collection. void copyInto(Object[] anArray) Copies the components of this vector into the specified array. Object elementAt(int index) Returns the component at the specified index. Enumeration elements() Returns an enumeration of the components of this vector. void ensureCapacity(int minCapacity) Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument. boolean equals(Object o) Compares the specified Object with this vector for equality. Object firstElement() Returns the first component (the item at index 0) of this vector. Object get(int index) Returns the element at the specified position in this vector. int hashCode() Returns the hash code value for this vector. int indexOf(Object elem) Searches for the first occurence of the given argument, testing for equality using the equals method. int indexOf(Object elem, int index) Searches for the first occurence of the given argument, beginning the search at index, and testing for equality using the equals method. void insertElementAt(Object obj, int index) Inserts the specified object as a component in this vector at the specified index. boolean isEmpty() Tests if this vector has no components. Object lastElement() Returns the last component of the vector. int lastIndexOf(Object elem) Returns the index of the last occurrence of the specified object in this vector. int lastIndexOf(Object elem, int index) Searches backwards for the specified object, starting from the specified index, and returns an index to it. Object remove(int index) Removes the element at the specified position in this vector. boolean remove(Object o) Removes the first occurrence of the specified element in this vector, If the vector does not contain the element, it is unchanged. boolean removeAll(Collection c) Removes from this vector all of its elements that are contained in the specified Collection. void removeAllElements() Removes all components from this vector and sets its size to zero. boolean removeElement(Object obj) Removes the first (lowest-indexed) occurrence of the argument from this vector. void removeElementAt(int index) removeElementAt(int index). protected void removeRange(int fromIndex, int toIndex) Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive. boolean retainAll(Collection c) Retains only the elements in this vector that are contained in the specified Collection. Object set(int index, Object element) Replaces the element at the specified position in this vector with the specified element. void setElementAt(Object obj, int index) Sets the component at the specified index of this vector to be the specified object. void setSize(int newSize) Sets the size of this vector. int size() Returns the number of components in this vector. List subList(int fromIndex, int toIndex) Returns a view of the portion of this List between fromIndex, inclusive, and toIndex, exclusive. Object[] toArray() Returns an array containing all of the elements in this vector in the correct order. Object[] toArray(Object[] a) Returns an array containing all of the elements in this vector in the correct order; the runtime type of the returned array is that of the specified array. String toString() Returns a string representation of this vector, containing the String representation of each element. void trimToSize() Trims the capacity of this vector to be the vector's current size. The following program illustrates several of the methods supported by this collection − import java.util.*; public class VectorDemo { public static void main(String args[]) { // initial size is 3, increment is 2 Vector v = new Vector(3, 2); System.out.println("Initial size: " + v.size()); System.out.println("Initial capacity: " + v.capacity()); v.addElement(new Integer(1)); v.addElement(new Integer(2)); v.addElement(new Integer(3)); v.addElement(new Integer(4)); System.out.println("Capacity after four additions: " + v.capacity()); v.addElement(new Double(5.45)); System.out.println("Current capacity: " + v.capacity()); v.addElement(new Double(6.08)); v.addElement(new Integer(7)); System.out.println("Current capacity: " + v.capacity()); v.addElement(new Float(9.4)); v.addElement(new Integer(10)); System.out.println("Current capacity: " + v.capacity()); v.addElement(new Integer(11)); v.addElement(new Integer(12)); System.out.println("First element: " + (Integer)v.firstElement()); System.out.println("Last element: " + (Integer)v.lastElement()); if(v.contains(new Integer(3))) System.out.println("Vector contains 3."); // enumerate the elements in the vector. Enumeration vEnum = v.elements(); System.out.println("\nElements in vector:"); while(vEnum.hasMoreElements()) System.out.print(vEnum.nextElement() + " "); System.out.println(); } } This will produce the following result − Initial size: 0 Initial capacity: 3 Capacity after four additions: 5 Current capacity: 5 Current capacity: 7 Current capacity: 9 First element: 1 Last element: 12 Vector contains 3. Elements in vector: 1 2 3 4 5.45 6.08 7 9.4 10 11 12 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2467, "s": 2377, "text": "Vector implements a dynamic array. It is similar to ArrayList, but with two differences −" }, { "code": null, "e": 2491, "s": 2467, "text": "Vector is synchronized." }, { "code": null, "e": 2515, "s": 2491, "text": "Vector is synchronized." }, { "code": null, "e": 2599, "s": 2515, "text": "Vector contains many legacy methods that are not part of the collections framework." }, { "code": null, "e": 2683, "s": 2599, "text": "Vector contains many legacy methods that are not part of the collections framework." }, { "code": null, "e": 2841, "s": 2683, "text": "Vector proves to be very useful if you don't know the size of the array in advance or you just need one that can change sizes over the lifetime of a program." }, { "code": null, "e": 2909, "s": 2841, "text": "Following is the list of constructors provided by the vector class." }, { "code": null, "e": 2919, "s": 2909, "text": "Vector( )" }, { "code": null, "e": 2995, "s": 2919, "text": "This constructor creates a default vector, which has an initial size of 10." }, { "code": null, "e": 3012, "s": 2995, "text": "Vector(int size)" }, { "code": null, "e": 3149, "s": 3012, "text": "This constructor accepts an argument that equals to the required size, and creates a vector whose initial capacity is specified by size." }, { "code": null, "e": 3176, "s": 3149, "text": "Vector(int size, int incr)" }, { "code": null, "e": 3398, "s": 3176, "text": "This constructor creates a vector whose initial capacity is specified by size and whose increment is specified by incr. The increment specifies the number of elements to allocate each time that a vector is resized upward." }, { "code": null, "e": 3419, "s": 3398, "text": "Vector(Collection c)" }, { "code": null, "e": 3497, "s": 3419, "text": "This constructor creates a vector that contains the elements of collection c." }, { "code": null, "e": 3594, "s": 3497, "text": "Apart from the methods inherited from its parent classes, Vector defines the following methods −" }, { "code": null, "e": 3630, "s": 3594, "text": "void add(int index, Object element)" }, { "code": null, "e": 3702, "s": 3630, "text": "Inserts the specified element at the specified position in this Vector." }, { "code": null, "e": 3724, "s": 3702, "text": "boolean add(Object o)" }, { "code": null, "e": 3781, "s": 3724, "text": "Appends the specified element to the end of this Vector." }, { "code": null, "e": 3810, "s": 3781, "text": "boolean addAll(Collection c)" }, { "code": null, "e": 3969, "s": 3810, "text": "Appends all of the elements in the specified Collection to the end of this Vector, in the order that they are returned by the specified Collection's Iterator." }, { "code": null, "e": 4009, "s": 3969, "text": "boolean addAll(int index, Collection c)" }, { "code": null, "e": 4112, "s": 4009, "text": "Inserts all of the elements in in the specified Collection into this Vector at the specified position." }, { "code": null, "e": 4140, "s": 4112, "text": "void addElement(Object obj)" }, { "code": null, "e": 4224, "s": 4140, "text": "Adds the specified component to the end of this vector, increasing its size by one." }, { "code": null, "e": 4239, "s": 4224, "text": "int capacity()" }, { "code": null, "e": 4284, "s": 4239, "text": "Returns the current capacity of this vector." }, { "code": null, "e": 4297, "s": 4284, "text": "void clear()" }, { "code": null, "e": 4343, "s": 4297, "text": "Removes all of the elements from this vector." }, { "code": null, "e": 4358, "s": 4343, "text": "Object clone()" }, { "code": null, "e": 4390, "s": 4358, "text": "Returns a clone of this vector." }, { "code": null, "e": 4420, "s": 4390, "text": "boolean contains(Object elem)" }, { "code": null, "e": 4481, "s": 4420, "text": "Tests if the specified object is a component in this vector." }, { "code": null, "e": 4515, "s": 4481, "text": "boolean containsAll(Collection c)" }, { "code": null, "e": 4601, "s": 4515, "text": "Returns true if this vector contains all of the elements in the specified Collection." }, { "code": null, "e": 4633, "s": 4601, "text": "void copyInto(Object[] anArray)" }, { "code": null, "e": 4696, "s": 4633, "text": "Copies the components of this vector into the specified array." }, { "code": null, "e": 4724, "s": 4696, "text": "Object elementAt(int index)" }, { "code": null, "e": 4770, "s": 4724, "text": "Returns the component at the specified index." }, { "code": null, "e": 4793, "s": 4770, "text": "Enumeration elements()" }, { "code": null, "e": 4850, "s": 4793, "text": "Returns an enumeration of the components of this vector." }, { "code": null, "e": 4887, "s": 4850, "text": "void ensureCapacity(int minCapacity)" }, { "code": null, "e": 5045, "s": 4887, "text": "Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument." }, { "code": null, "e": 5070, "s": 5045, "text": "boolean equals(Object o)" }, { "code": null, "e": 5131, "s": 5070, "text": "Compares the specified Object with this vector for equality." }, { "code": null, "e": 5153, "s": 5131, "text": "Object firstElement()" }, { "code": null, "e": 5219, "s": 5153, "text": "Returns the first component (the item at index 0) of this vector." }, { "code": null, "e": 5241, "s": 5219, "text": "Object get(int index)" }, { "code": null, "e": 5303, "s": 5241, "text": "Returns the element at the specified position in this vector." }, { "code": null, "e": 5318, "s": 5303, "text": "int hashCode()" }, { "code": null, "e": 5363, "s": 5318, "text": "Returns the hash code value for this vector." }, { "code": null, "e": 5388, "s": 5363, "text": "int indexOf(Object elem)" }, { "code": null, "e": 5490, "s": 5388, "text": "Searches for the first occurence of the given argument, testing for equality using the equals method." }, { "code": null, "e": 5526, "s": 5490, "text": "int indexOf(Object elem, int index)" }, { "code": null, "e": 5663, "s": 5526, "text": "Searches for the first occurence of the given argument, beginning the search at index, and testing for equality using the equals method." }, { "code": null, "e": 5707, "s": 5663, "text": "void insertElementAt(Object obj, int index)" }, { "code": null, "e": 5790, "s": 5707, "text": "Inserts the specified object as a component in this vector at the specified index." }, { "code": null, "e": 5808, "s": 5790, "text": "boolean isEmpty()" }, { "code": null, "e": 5848, "s": 5808, "text": "Tests if this vector has no components." }, { "code": null, "e": 5869, "s": 5848, "text": "Object lastElement()" }, { "code": null, "e": 5911, "s": 5869, "text": "Returns the last component of the vector." }, { "code": null, "e": 5940, "s": 5911, "text": "int lastIndexOf(Object elem)" }, { "code": null, "e": 6021, "s": 5940, "text": "Returns the index of the last occurrence of the specified object in this vector." }, { "code": null, "e": 6061, "s": 6021, "text": "int lastIndexOf(Object elem, int index)" }, { "code": null, "e": 6169, "s": 6061, "text": "Searches backwards for the specified object, starting from the specified index, and returns an index to it." }, { "code": null, "e": 6194, "s": 6169, "text": "Object remove(int index)" }, { "code": null, "e": 6256, "s": 6194, "text": "Removes the element at the specified position in this vector." }, { "code": null, "e": 6281, "s": 6256, "text": "boolean remove(Object o)" }, { "code": null, "e": 6412, "s": 6281, "text": "Removes the first occurrence of the specified element in this vector, If the vector does not contain the element, it is unchanged." }, { "code": null, "e": 6444, "s": 6412, "text": "boolean removeAll(Collection c)" }, { "code": null, "e": 6537, "s": 6444, "text": "Removes from this vector all of its elements that are contained in the specified Collection." }, { "code": null, "e": 6562, "s": 6537, "text": "void removeAllElements()" }, { "code": null, "e": 6629, "s": 6562, "text": "Removes all components from this vector and sets its size to zero." }, { "code": null, "e": 6663, "s": 6629, "text": "boolean removeElement(Object obj)" }, { "code": null, "e": 6743, "s": 6663, "text": "Removes the first (lowest-indexed) occurrence of the argument from this vector." }, { "code": null, "e": 6775, "s": 6743, "text": "void removeElementAt(int index)" }, { "code": null, "e": 6803, "s": 6775, "text": "removeElementAt(int index)." }, { "code": null, "e": 6858, "s": 6803, "text": "protected void removeRange(int fromIndex, int toIndex)" }, { "code": null, "e": 6969, "s": 6858, "text": "Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive." }, { "code": null, "e": 7001, "s": 6969, "text": "boolean retainAll(Collection c)" }, { "code": null, "e": 7090, "s": 7001, "text": "Retains only the elements in this vector that are contained in the specified Collection." }, { "code": null, "e": 7128, "s": 7090, "text": "Object set(int index, Object element)" }, { "code": null, "e": 7218, "s": 7128, "text": "Replaces the element at the specified position in this vector with the specified element." }, { "code": null, "e": 7259, "s": 7218, "text": "void setElementAt(Object obj, int index)" }, { "code": null, "e": 7344, "s": 7259, "text": "Sets the component at the specified index of this vector to be the specified object." }, { "code": null, "e": 7370, "s": 7344, "text": "void setSize(int newSize)" }, { "code": null, "e": 7400, "s": 7370, "text": "Sets the size of this vector." }, { "code": null, "e": 7411, "s": 7400, "text": "int size()" }, { "code": null, "e": 7460, "s": 7411, "text": "Returns the number of components in this vector." }, { "code": null, "e": 7501, "s": 7460, "text": "List subList(int fromIndex, int toIndex)" }, { "code": null, "e": 7598, "s": 7501, "text": "Returns a view of the portion of this List between fromIndex, inclusive, and toIndex, exclusive." }, { "code": null, "e": 7617, "s": 7598, "text": "Object[] toArray()" }, { "code": null, "e": 7702, "s": 7617, "text": "Returns an array containing all of the elements in this vector in the correct order." }, { "code": null, "e": 7731, "s": 7702, "text": "Object[] toArray(Object[] a)" }, { "code": null, "e": 7887, "s": 7731, "text": "Returns an array containing all of the elements in this vector in the correct order; the runtime type of the returned array is that of the specified array." }, { "code": null, "e": 7905, "s": 7887, "text": "String toString()" }, { "code": null, "e": 8007, "s": 7905, "text": "Returns a string representation of this vector, containing the String representation of each element." }, { "code": null, "e": 8025, "s": 8007, "text": "void trimToSize()" }, { "code": null, "e": 8092, "s": 8025, "text": "Trims the capacity of this vector to be the vector's current size." }, { "code": null, "e": 8180, "s": 8092, "text": "The following program illustrates several of the methods supported by this collection −" }, { "code": null, "e": 9684, "s": 8180, "text": "import java.util.*;\npublic class VectorDemo {\n\n public static void main(String args[]) {\n // initial size is 3, increment is 2\n Vector v = new Vector(3, 2);\n System.out.println(\"Initial size: \" + v.size());\n System.out.println(\"Initial capacity: \" + v.capacity());\n \n v.addElement(new Integer(1));\n v.addElement(new Integer(2));\n v.addElement(new Integer(3));\n v.addElement(new Integer(4));\n System.out.println(\"Capacity after four additions: \" + v.capacity());\n\n v.addElement(new Double(5.45));\n System.out.println(\"Current capacity: \" + v.capacity());\n \n v.addElement(new Double(6.08));\n v.addElement(new Integer(7));\n System.out.println(\"Current capacity: \" + v.capacity());\n \n v.addElement(new Float(9.4));\n v.addElement(new Integer(10));\n System.out.println(\"Current capacity: \" + v.capacity());\n \n v.addElement(new Integer(11));\n v.addElement(new Integer(12));\n System.out.println(\"First element: \" + (Integer)v.firstElement());\n System.out.println(\"Last element: \" + (Integer)v.lastElement());\n \n if(v.contains(new Integer(3)))\n System.out.println(\"Vector contains 3.\");\n \n // enumerate the elements in the vector.\n Enumeration vEnum = v.elements();\n System.out.println(\"\\nElements in vector:\");\n \n while(vEnum.hasMoreElements())\n System.out.print(vEnum.nextElement() + \" \");\n System.out.println();\n }\n}" }, { "code": null, "e": 9725, "s": 9684, "text": "This will produce the following result −" }, { "code": null, "e": 9962, "s": 9725, "text": "Initial size: 0\nInitial capacity: 3\nCapacity after four additions: 5\nCurrent capacity: 5\nCurrent capacity: 7\nCurrent capacity: 9\nFirst element: 1\nLast element: 12\nVector contains 3.\n\nElements in vector:\n1 2 3 4 5.45 6.08 7 9.4 10 11 12\n" }, { "code": null, "e": 9995, "s": 9962, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 10011, "s": 9995, "text": " Malhar Lathkar" }, { "code": null, "e": 10044, "s": 10011, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 10060, "s": 10044, "text": " Malhar Lathkar" }, { "code": null, "e": 10095, "s": 10060, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10109, "s": 10095, "text": " Anadi Sharma" }, { "code": null, "e": 10143, "s": 10109, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 10157, "s": 10143, "text": " Tushar Kale" }, { "code": null, "e": 10194, "s": 10157, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 10209, "s": 10194, "text": " Monica Mittal" }, { "code": null, "e": 10242, "s": 10209, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 10261, "s": 10242, "text": " Arnab Chakraborty" }, { "code": null, "e": 10268, "s": 10261, "text": " Print" }, { "code": null, "e": 10279, "s": 10268, "text": " Add Notes" } ]
How to Call a Lua function from C?
Calling a Lua function from C is something that requires a series of steps and a mastery in the Lua library functions. Lua provides several library functions that we can use whenever we want to call Lua functions from C or the opposite. Some of the most commonly used Lua library functions for calling a Lua function from C are − luaL_dofile(L, "myFile.lua"); lua_getglobal(L, "add"); lua_pushnumber(L, a); and much more. We will make use of these functions when we will call a Lua function from C. The first step is to shut down the Lua interpreter and for that we need to write a code in C. Consider the example shown below − extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" } int main(int argc, char *argv[]) { lua_State* L; L = luaL_newstate(); luaL_openlibs(L); lua_close(L); printf( "Press enter to exit..." ); getchar(); return 0; } Now, we just need to call the luaL_dofile(L, "myFile.lua"); function for the file in which we will write some Lua code that will get invoked from the C code. Consider the code shown below as written inside the myFile.lua − add = function(a,b) return a + b end Now the C file which will call the above Lua function will look something like this − int luaAdd(lua_State* L, int a, int b) { // Push the add function on the top of the lua stack lua_getglobal(L, "add"); // Push the first argument on the top of the lua stack lua_pushnumber(L, a); // Push the second argument on the top of the lua stack lua_pushnumber(L, b); // Call the function with 2 arguments, returning 1 result lua_call(L, 2, 1); // Get the result int sum = (int)lua_tointeger(L, -1); lua_pop(L, 1); return sum; } And when we call this luaAdd() function in C, the output will be:(for a = 2,b = 3) 5
[ { "code": null, "e": 1299, "s": 1062, "text": "Calling a Lua function from C is something that requires a series of steps and a mastery in the Lua library functions. Lua provides several library functions that we can use whenever we want to call Lua functions from C or the opposite." }, { "code": null, "e": 1392, "s": 1299, "text": "Some of the most commonly used Lua library functions for calling a Lua function from C are −" }, { "code": null, "e": 1422, "s": 1392, "text": "luaL_dofile(L, \"myFile.lua\");" }, { "code": null, "e": 1447, "s": 1422, "text": "lua_getglobal(L, \"add\");" }, { "code": null, "e": 1469, "s": 1447, "text": "lua_pushnumber(L, a);" }, { "code": null, "e": 1484, "s": 1469, "text": "and much more." }, { "code": null, "e": 1561, "s": 1484, "text": "We will make use of these functions when we will call a Lua function from C." }, { "code": null, "e": 1655, "s": 1561, "text": "The first step is to shut down the Lua interpreter and for that we need to write a code in C." }, { "code": null, "e": 1690, "s": 1655, "text": "Consider the example shown below −" }, { "code": null, "e": 1954, "s": 1690, "text": "extern \"C\" {\n #include \"lua.h\"\n #include \"lualib.h\"\n #include \"lauxlib.h\"\n}\nint main(int argc, char *argv[]) {\n lua_State* L;\n L = luaL_newstate();\n luaL_openlibs(L);\n lua_close(L);\n printf( \"Press enter to exit...\" );\n getchar();\n return 0;\n}" }, { "code": null, "e": 2112, "s": 1954, "text": "Now, we just need to call the luaL_dofile(L, \"myFile.lua\"); function for the file in which we will write some Lua code that will get invoked from the C code." }, { "code": null, "e": 2177, "s": 2112, "text": "Consider the code shown below as written inside the myFile.lua −" }, { "code": null, "e": 2214, "s": 2177, "text": "add = function(a,b)\nreturn a + b\nend" }, { "code": null, "e": 2300, "s": 2214, "text": "Now the C file which will call the above Lua function will look something like this −" }, { "code": null, "e": 2771, "s": 2300, "text": "int luaAdd(lua_State* L, int a, int b) {\n // Push the add function on the top of the lua stack\n lua_getglobal(L, \"add\");\n // Push the first argument on the top of the lua stack\n lua_pushnumber(L, a);\n // Push the second argument on the top of the lua stack\n lua_pushnumber(L, b);\n // Call the function with 2 arguments, returning 1 result\n lua_call(L, 2, 1);\n // Get the result\n int sum = (int)lua_tointeger(L, -1);\n lua_pop(L, 1);\n return sum;\n}" }, { "code": null, "e": 2854, "s": 2771, "text": "And when we call this luaAdd() function in C, the output will be:(for a = 2,b = 3)" }, { "code": null, "e": 2856, "s": 2854, "text": "5" } ]
How to display all constraints on a table in MySQL?
To display all constraints on a table, you can try any of the following methods − You can check with the help of show command. The syntax is as follows − SHOW CREATE TABLE yourTableName; You can use information.schema. The syntax is as follows − select COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_COLUMN_NAME, REFERENCED_TABLE_NAME from information_schema.KEY_COLUMN_USAGE where TABLE_NAME = 'yourTableName'; To display all constraints on a table, implement the above syntax. Let’s say we already have a table ‘ConstraintDemo’. The query is as follows − mysql> select COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_COLUMN_NAME, REFERENCED_TABLE_NAME −> from information_schema.KEY_COLUMN_USAGE −> where TABLE_NAME = 'ConstraintDemo'; The following is the output displaying the constraints − +-------------+-----------------+------------------------+-----------------------+ | COLUMN_NAME | CONSTRAINT_NAME | REFERENCED_COLUMN_NAME | REFERENCED_TABLE_NAME | +-------------+-----------------+------------------------+-----------------------+ | Id | PRIMARY | NULL | NULL | | Id | Id | NULL | NULL | +-------------+-----------------+------------------------+-----------------------+ 2 rows in set, 2 warnings (0.04 sec) Now let us check using the show command. The query is as follows − mysql> show create table ConstraintDemo; The following is the output − +----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | ConstraintDemo | CREATE TABLE `constraintdemo` (`Id` int(11) NOT NULL,`Name` varchar(100) NOT NULL, PRIMARY KEY (`Id`), UNIQUE KEY `Id` (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci | +----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1144, "s": 1062, "text": "To display all constraints on a table, you can try any of the following methods −" }, { "code": null, "e": 1216, "s": 1144, "text": "You can check with the help of show command. The syntax is as follows −" }, { "code": null, "e": 1249, "s": 1216, "text": "SHOW CREATE TABLE yourTableName;" }, { "code": null, "e": 1308, "s": 1249, "text": "You can use information.schema. The syntax is as follows −" }, { "code": null, "e": 1468, "s": 1308, "text": "select COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_COLUMN_NAME, REFERENCED_TABLE_NAME\nfrom information_schema.KEY_COLUMN_USAGE\nwhere TABLE_NAME = 'yourTableName';" }, { "code": null, "e": 1587, "s": 1468, "text": "To display all constraints on a table, implement the above syntax. Let’s say we already have a table ‘ConstraintDemo’." }, { "code": null, "e": 1613, "s": 1587, "text": "The query is as follows −" }, { "code": null, "e": 1793, "s": 1613, "text": "mysql> select COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_COLUMN_NAME, REFERENCED_TABLE_NAME\n −> from information_schema.KEY_COLUMN_USAGE\n −> where TABLE_NAME = 'ConstraintDemo';" }, { "code": null, "e": 1850, "s": 1793, "text": "The following is the output displaying the constraints −" }, { "code": null, "e": 2385, "s": 1850, "text": "+-------------+-----------------+------------------------+-----------------------+\n| COLUMN_NAME | CONSTRAINT_NAME | REFERENCED_COLUMN_NAME | REFERENCED_TABLE_NAME |\n+-------------+-----------------+------------------------+-----------------------+\n| Id | PRIMARY | NULL | NULL |\n| Id | Id | NULL | NULL |\n+-------------+-----------------+------------------------+-----------------------+\n2 rows in set, 2 warnings (0.04 sec)" }, { "code": null, "e": 2452, "s": 2385, "text": "Now let us check using the show command. The query is as follows −" }, { "code": null, "e": 2493, "s": 2452, "text": "mysql> show create table ConstraintDemo;" }, { "code": null, "e": 2523, "s": 2493, "text": "The following is the output −" }, { "code": null, "e": 3476, "s": 2523, "text": "+----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| Table | Create Table |\n+----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| ConstraintDemo | CREATE TABLE `constraintdemo` (`Id` int(11) NOT NULL,`Name` varchar(100) NOT NULL, PRIMARY KEY (`Id`), UNIQUE KEY `Id` (`Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |\n+----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n1 row in set (0.00 sec)" } ]
java.lang.reflect.Constructor Class in Java - GeeksforGeeks
15 Nov, 2021 java.lang.reflect.Constructor class is used to manage the constructor metadata like the name of the constructors, parameter types of constructors, and access modifiers of the constructors. We can inspect the constructors of classes and instantiate objects at runtime. The Constructor[] array will have one Constructor instance for each public constructor declared in the class. In order to obtain Constructor objects, one can get the Constructor class object from the Class object. Parameter: T- the class in which constructor is declared Implemented interfaces are as follows: AnnotatedElement GenericDeclaration Member Illustration: Class aClass = Employee.class; Constructor[] constructors = aClass.getConstructors(); Pre-requisite: Lets us do discuss some methods by which we can get information about constructors getConstructors(): One can get all the public constructors in the respective class. it returns an array of Constructors.getDeclaredConstructors(): One can get all the constructors in the respective class irrespective of the public keyword.getName(): One can get the name of the respective constructor.getModifiers(): This returns the Java language modifiers for the constructor represented by this Constructor object as an integer. The Modifier class should be used to decode the modifiers. getParameterTypes(): This returns the parameter types of a particular constructor. getConstructors(): One can get all the public constructors in the respective class. it returns an array of Constructors. getDeclaredConstructors(): One can get all the constructors in the respective class irrespective of the public keyword. getName(): One can get the name of the respective constructor. getModifiers(): This returns the Java language modifiers for the constructor represented by this Constructor object as an integer. The Modifier class should be used to decode the modifiers. getParameterTypes(): This returns the parameter types of a particular constructor. Furthermore, the primary methods of this class are given below in tabular format which is as follows: Example: Java // Java program to show uses of Constructor class// present in java.lang.reflect package // Importing package to that examine and// introspect upon itselfimport java.lang.reflect.*; // Class 1// Helper classclass Employee { // Member variables of this class int empno; String name; String address; // Constructor of this class // Constructor 1 public Employee(int empno, String name, String address) { // 'this' keyword refers to the // current object itself this.empno = empno; this.name = name; this.address = address; } // Constructor 2 public Employee(int empno, String name) { this.empno = empno; this.name = name; } // Constructor 3 private Employee(String address) { this.address = address; } // Constructor 4 protected Employee(int empno) { this.empno = empno; }} // Class 2// Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating an object of above class // in the main() method Class c = Employee.class; // Display message System.out.println("All public constructor are :"); Constructor[] cons = c.getConstructors(); for (Constructor con : cons) // It will return all public constructor System.out.print(con.getName() + " "); // Display message for better readability System.out.println( "\n\nAll constructor irrespective of access modifiers"); // Getting constructors of this class // using getDeclaredConstructors() method cons = c.getDeclaredConstructors(); // Iterating to print all constructors for (Constructor con : cons) System.out.print(con.getName() + " "); // Display message System.out.println( "\n\naccess modifiers of each constructor"); // Iterating to get all the access modifiers for (Constructor con : cons) // Print all the access modifiers for all // constructors System.out.print( Modifier.toString(con.getModifiers()) + " "); // Parameters types // Display message only System.out.println( "\n\ngetting parameters type of each constructor"); // Iteerating to get parameter types of each // constructor using for-each loop for (Constructor con : cons) { Class[] parameratertypes = con.getParameterTypes(); for (Class c1 : parameratertypes) { // Print and display parameter types of all // constructors System.out.print(c1.getName() + " "); } // Here we are done with inner loop // New line System.out.println(); } }} All public constructor are : Employee Employee All constructor irrespective of access modifiers Employee Employee Employee Employee access modifiers of each constructor protected private public public getting parameters type of each constructor int java.lang.String int java.lang.String int java.lang.String java.lang.String adnanirshad158 singghakshay java-lang-reflect-package Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Generics in Java Comparator Interface in Java with Examples Strings in Java How to remove an element from ArrayList in Java? Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23557, "s": 23529, "text": "\n15 Nov, 2021" }, { "code": null, "e": 23935, "s": 23557, "text": "java.lang.reflect.Constructor class is used to manage the constructor metadata like the name of the constructors, parameter types of constructors, and access modifiers of the constructors. We can inspect the constructors of classes and instantiate objects at runtime. The Constructor[] array will have one Constructor instance for each public constructor declared in the class." }, { "code": null, "e": 24039, "s": 23935, "text": "In order to obtain Constructor objects, one can get the Constructor class object from the Class object." }, { "code": null, "e": 24097, "s": 24039, "text": "Parameter: T- the class in which constructor is declared " }, { "code": null, "e": 24136, "s": 24097, "text": "Implemented interfaces are as follows:" }, { "code": null, "e": 24153, "s": 24136, "text": "AnnotatedElement" }, { "code": null, "e": 24172, "s": 24153, "text": "GenericDeclaration" }, { "code": null, "e": 24179, "s": 24172, "text": "Member" }, { "code": null, "e": 24194, "s": 24179, "text": "Illustration: " }, { "code": null, "e": 24280, "s": 24194, "text": "Class aClass = Employee.class;\nConstructor[] constructors = aClass.getConstructors();" }, { "code": null, "e": 24295, "s": 24280, "text": "Pre-requisite:" }, { "code": null, "e": 24378, "s": 24295, "text": "Lets us do discuss some methods by which we can get information about constructors" }, { "code": null, "e": 24952, "s": 24378, "text": "getConstructors(): One can get all the public constructors in the respective class. it returns an array of Constructors.getDeclaredConstructors(): One can get all the constructors in the respective class irrespective of the public keyword.getName(): One can get the name of the respective constructor.getModifiers(): This returns the Java language modifiers for the constructor represented by this Constructor object as an integer. The Modifier class should be used to decode the modifiers. getParameterTypes(): This returns the parameter types of a particular constructor." }, { "code": null, "e": 25073, "s": 24952, "text": "getConstructors(): One can get all the public constructors in the respective class. it returns an array of Constructors." }, { "code": null, "e": 25193, "s": 25073, "text": "getDeclaredConstructors(): One can get all the constructors in the respective class irrespective of the public keyword." }, { "code": null, "e": 25256, "s": 25193, "text": "getName(): One can get the name of the respective constructor." }, { "code": null, "e": 25446, "s": 25256, "text": "getModifiers(): This returns the Java language modifiers for the constructor represented by this Constructor object as an integer. The Modifier class should be used to decode the modifiers." }, { "code": null, "e": 25530, "s": 25446, "text": " getParameterTypes(): This returns the parameter types of a particular constructor." }, { "code": null, "e": 25632, "s": 25530, "text": "Furthermore, the primary methods of this class are given below in tabular format which is as follows:" }, { "code": null, "e": 25641, "s": 25632, "text": "Example:" }, { "code": null, "e": 25646, "s": 25641, "text": "Java" }, { "code": "// Java program to show uses of Constructor class// present in java.lang.reflect package // Importing package to that examine and// introspect upon itselfimport java.lang.reflect.*; // Class 1// Helper classclass Employee { // Member variables of this class int empno; String name; String address; // Constructor of this class // Constructor 1 public Employee(int empno, String name, String address) { // 'this' keyword refers to the // current object itself this.empno = empno; this.name = name; this.address = address; } // Constructor 2 public Employee(int empno, String name) { this.empno = empno; this.name = name; } // Constructor 3 private Employee(String address) { this.address = address; } // Constructor 4 protected Employee(int empno) { this.empno = empno; }} // Class 2// Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating an object of above class // in the main() method Class c = Employee.class; // Display message System.out.println(\"All public constructor are :\"); Constructor[] cons = c.getConstructors(); for (Constructor con : cons) // It will return all public constructor System.out.print(con.getName() + \" \"); // Display message for better readability System.out.println( \"\\n\\nAll constructor irrespective of access modifiers\"); // Getting constructors of this class // using getDeclaredConstructors() method cons = c.getDeclaredConstructors(); // Iterating to print all constructors for (Constructor con : cons) System.out.print(con.getName() + \" \"); // Display message System.out.println( \"\\n\\naccess modifiers of each constructor\"); // Iterating to get all the access modifiers for (Constructor con : cons) // Print all the access modifiers for all // constructors System.out.print( Modifier.toString(con.getModifiers()) + \" \"); // Parameters types // Display message only System.out.println( \"\\n\\ngetting parameters type of each constructor\"); // Iteerating to get parameter types of each // constructor using for-each loop for (Constructor con : cons) { Class[] parameratertypes = con.getParameterTypes(); for (Class c1 : parameratertypes) { // Print and display parameter types of all // constructors System.out.print(c1.getName() + \" \"); } // Here we are done with inner loop // New line System.out.println(); } }}", "e": 28524, "s": 25646, "text": null }, { "code": null, "e": 28860, "s": 28524, "text": "All public constructor are :\nEmployee Employee \n\nAll constructor irrespective of access modifiers\nEmployee Employee Employee Employee \n\naccess modifiers of each constructor\nprotected private public public \n\ngetting parameters type of each constructor\nint \njava.lang.String \nint java.lang.String \nint java.lang.String java.lang.String " }, { "code": null, "e": 28877, "s": 28862, "text": "adnanirshad158" }, { "code": null, "e": 28890, "s": 28877, "text": "singghakshay" }, { "code": null, "e": 28916, "s": 28890, "text": "java-lang-reflect-package" }, { "code": null, "e": 28923, "s": 28916, "text": "Picked" }, { "code": null, "e": 28928, "s": 28923, "text": "Java" }, { "code": null, "e": 28933, "s": 28928, "text": "Java" }, { "code": null, "e": 29031, "s": 28933, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29040, "s": 29031, "text": "Comments" }, { "code": null, "e": 29053, "s": 29040, "text": "Old Comments" }, { "code": null, "e": 29083, "s": 29053, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29098, "s": 29083, "text": "Stream In Java" }, { "code": null, "e": 29119, "s": 29098, "text": "Constructors in Java" }, { "code": null, "e": 29165, "s": 29119, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29184, "s": 29165, "text": "Exceptions in Java" }, { "code": null, "e": 29201, "s": 29184, "text": "Generics in Java" }, { "code": null, "e": 29244, "s": 29201, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 29260, "s": 29244, "text": "Strings in Java" }, { "code": null, "e": 29309, "s": 29260, "text": "How to remove an element from ArrayList in Java?" } ]
Analyzing Medicare Data in Python | by Sadrach Pierre, Ph.D. | Towards Data Science
Medicare is a single-payer national social health insurance program for Americans age 65 and older. It also includes some younger adults with disability status, people living with ALS, and people with end-stage renal disease. The Center for Medicare & Medicaid Services provides public access to Medicare data. You can access the data through Google BigQuery. You can use the dataset to answer the following questions: What is the total number of medications prescribed in each state?What is the most prescribed medication in each state?What is the average cost for inpatient and outpatient treatment in each city and state?Which are the most common inpatient diagnostic conditions in the United States?Which cities have the most number of cases for each diagnostic condition?What are the average payments for these conditions in these cities and how do they compare to the national average? What is the total number of medications prescribed in each state? What is the most prescribed medication in each state? What is the average cost for inpatient and outpatient treatment in each city and state? Which are the most common inpatient diagnostic conditions in the United States? Which cities have the most number of cases for each diagnostic condition? What are the average payments for these conditions in these cities and how do they compare to the national average? In this post, we will perform some simple exploratory data analysis of data from Medicare database. While we will not answer all of the questions above, this post will provide a good start for interested readers. First, to access the data, you need to create a Google Cloud account. Next, you need to install Google BigQuery and generate authentication credentials. You can find the instructions for doing so here. Let’s get started! First, let’s import the necessary google authentication and BigQuery packages: from google.oauth2 import service_accountfrom google.cloud import bigquery Next, we need to import pandas and define the column settings to be ‘None’. We do this so that we can display all columns since pandas truncate them by default. import pandas as pdpd.set_option("display.max_columns", None) Next, we define our key path, client credentials, and client object: key_path = "key_path/key.json"credentials = service_account.Credentials.from_service_account_file( key_path, scopes=["https://www.googleapis.com/auth/cloud-platform"],)client = bigquery.Client( credentials=credentials, project=credentials.project_id,) Next, we define the dataset reference where we pass in the name of the database, ‘medicare’, and the name of the project, ‘bigquery-public-data’: dataset_ref = client.dataset("medicare", project="bigquery-public-data") We can look at the 12 tables available: columns = [x.table_id for x in client.list_tables(dataset_ref)]print(columns) Let’s look at the first element in the list, ‘inpatient_charges_2011’: table_ref = dataset_ref.table('inpatient_charges_2011')table = client.get_table(table_ref) We can store the results in a dataframe and print the names of the columns: df = client.list_rows(table).to_dataframe()print(df.columns) We can also look at the length of the dataframe: print(len(df)) We can also print the first five rows of the dataframe: print(df.head()) We can import the counter method from the collections module in python to analyze the distribution in some of the categorical variables. Let’s take a look at the ‘provider_name’ column: from collections import Counterprint(dict(Counter(df['provider_name'].values).most_common(20))) We can also visualize some of this output. Let’s define a function that takes a category string as input and displays a bar chart of the four most common values: import matplotlib.pyplot as pltimport seaborn as snsdef plot_most_common(category): sns.set() bar_plot = dict(Counter(df[category].values).most_common(4)) plt.bar(*zip(*bar_plot.items())) plt.show() Let’s now call the function with ‘provider_name’: plot_most_common('provider_name') We can also look at the four most common values for ‘drg_description’: plot_most_common('drg_description') We can also define a function to generate boxplots across categorical values. We use boxplots to visualize the distribution in numeric values based on the minimum, maximum, median, first quartile, and third quartile. If you are unfamiliar with them take a look at the article Understanding Boxplots. The function takes a data frame, categorical column and numerical column and displays boxplots for the most common categories based on the limit: def get_boxplot_of_categories(data_frame, categorical_column, numerical_column, limit): keys = [] for i in dict(Counter(df[categorical_column].values).most_common(limit)): keys.append(i) print(keys) df_new = df[df[categorical_column].isin(keys)] sns.boxplot(x = df_new[categorical_column], y = df_new[numerical_column]) Let’s generate boxplots for average medicare payments in the 5 most commonly occurring provider names: get_boxplot_of_categories(df, 'provider_name', 'average_medicare_payments', 5) We can generate a similar plot for ‘total_discharges’: get_boxplot_of_categories(df, 'provider_name', 'total_discharges', 5) We can also build a scatterplot function. This function takes a data frame, categorical column, categorical value, and two numerical columns as input and displays a scatterplot: def get_scatter_plot_category(data_frame, categorical_column, categorical_value, numerical_column_one, numerical_column_two): import matplotlib.pyplot as plt import seaborn as snsdf_new = data_frame[data_frame[categorical_column] == categorical_value] sns.set() plt.scatter(x= df_new[numerical_column_one], y = df_new[numerical_column_two]) plt.xlabel(numerical_column_one) plt.ylabel(numerical_column_two) Let’s generate a scatterplot of average_medicare_payments vs total_discharges for ‘GOOD SAMARITAN HOSPITAL’ : get_scatter_plot_category(df, 'provider_name', 'GOOD SAMARITAN HOSPITAL', 'average_medicare_payments', 'total_discharges') We can also look at the same plot for ‘NORTH SHORE MEDICAL CENTER’: get_scatter_plot_category(df, 'provider_name', 'NORTH SHORE MEDICAL CENTER', 'average_medicare_payments', 'total_discharges') To recap, in this post I performed simple exploratory data analysis on the Medicare dataset. I analyzed the distribution in categorical values of provider names. I also generated bar charts for visualizing the frequency of provider names in the dataset. Finally, I defined functions for generating boxplots across categorical values and visualizing scatterplots of numerical values. I hope this post was interesting. The code from this post is available on GitHub. Thank you for reading!
[ { "code": null, "e": 532, "s": 172, "text": "Medicare is a single-payer national social health insurance program for Americans age 65 and older. It also includes some younger adults with disability status, people living with ALS, and people with end-stage renal disease. The Center for Medicare & Medicaid Services provides public access to Medicare data. You can access the data through Google BigQuery." }, { "code": null, "e": 591, "s": 532, "text": "You can use the dataset to answer the following questions:" }, { "code": null, "e": 1064, "s": 591, "text": "What is the total number of medications prescribed in each state?What is the most prescribed medication in each state?What is the average cost for inpatient and outpatient treatment in each city and state?Which are the most common inpatient diagnostic conditions in the United States?Which cities have the most number of cases for each diagnostic condition?What are the average payments for these conditions in these cities and how do they compare to the national average?" }, { "code": null, "e": 1130, "s": 1064, "text": "What is the total number of medications prescribed in each state?" }, { "code": null, "e": 1184, "s": 1130, "text": "What is the most prescribed medication in each state?" }, { "code": null, "e": 1272, "s": 1184, "text": "What is the average cost for inpatient and outpatient treatment in each city and state?" }, { "code": null, "e": 1352, "s": 1272, "text": "Which are the most common inpatient diagnostic conditions in the United States?" }, { "code": null, "e": 1426, "s": 1352, "text": "Which cities have the most number of cases for each diagnostic condition?" }, { "code": null, "e": 1542, "s": 1426, "text": "What are the average payments for these conditions in these cities and how do they compare to the national average?" }, { "code": null, "e": 1755, "s": 1542, "text": "In this post, we will perform some simple exploratory data analysis of data from Medicare database. While we will not answer all of the questions above, this post will provide a good start for interested readers." }, { "code": null, "e": 1957, "s": 1755, "text": "First, to access the data, you need to create a Google Cloud account. Next, you need to install Google BigQuery and generate authentication credentials. You can find the instructions for doing so here." }, { "code": null, "e": 1976, "s": 1957, "text": "Let’s get started!" }, { "code": null, "e": 2055, "s": 1976, "text": "First, let’s import the necessary google authentication and BigQuery packages:" }, { "code": null, "e": 2130, "s": 2055, "text": "from google.oauth2 import service_accountfrom google.cloud import bigquery" }, { "code": null, "e": 2291, "s": 2130, "text": "Next, we need to import pandas and define the column settings to be ‘None’. We do this so that we can display all columns since pandas truncate them by default." }, { "code": null, "e": 2353, "s": 2291, "text": "import pandas as pdpd.set_option(\"display.max_columns\", None)" }, { "code": null, "e": 2422, "s": 2353, "text": "Next, we define our key path, client credentials, and client object:" }, { "code": null, "e": 2686, "s": 2422, "text": "key_path = \"key_path/key.json\"credentials = service_account.Credentials.from_service_account_file( key_path, scopes=[\"https://www.googleapis.com/auth/cloud-platform\"],)client = bigquery.Client( credentials=credentials, project=credentials.project_id,)" }, { "code": null, "e": 2832, "s": 2686, "text": "Next, we define the dataset reference where we pass in the name of the database, ‘medicare’, and the name of the project, ‘bigquery-public-data’:" }, { "code": null, "e": 2905, "s": 2832, "text": "dataset_ref = client.dataset(\"medicare\", project=\"bigquery-public-data\")" }, { "code": null, "e": 2945, "s": 2905, "text": "We can look at the 12 tables available:" }, { "code": null, "e": 3023, "s": 2945, "text": "columns = [x.table_id for x in client.list_tables(dataset_ref)]print(columns)" }, { "code": null, "e": 3094, "s": 3023, "text": "Let’s look at the first element in the list, ‘inpatient_charges_2011’:" }, { "code": null, "e": 3185, "s": 3094, "text": "table_ref = dataset_ref.table('inpatient_charges_2011')table = client.get_table(table_ref)" }, { "code": null, "e": 3261, "s": 3185, "text": "We can store the results in a dataframe and print the names of the columns:" }, { "code": null, "e": 3322, "s": 3261, "text": "df = client.list_rows(table).to_dataframe()print(df.columns)" }, { "code": null, "e": 3371, "s": 3322, "text": "We can also look at the length of the dataframe:" }, { "code": null, "e": 3386, "s": 3371, "text": "print(len(df))" }, { "code": null, "e": 3442, "s": 3386, "text": "We can also print the first five rows of the dataframe:" }, { "code": null, "e": 3459, "s": 3442, "text": "print(df.head())" }, { "code": null, "e": 3645, "s": 3459, "text": "We can import the counter method from the collections module in python to analyze the distribution in some of the categorical variables. Let’s take a look at the ‘provider_name’ column:" }, { "code": null, "e": 3741, "s": 3645, "text": "from collections import Counterprint(dict(Counter(df['provider_name'].values).most_common(20)))" }, { "code": null, "e": 3903, "s": 3741, "text": "We can also visualize some of this output. Let’s define a function that takes a category string as input and displays a bar chart of the four most common values:" }, { "code": null, "e": 4114, "s": 3903, "text": "import matplotlib.pyplot as pltimport seaborn as snsdef plot_most_common(category): sns.set() bar_plot = dict(Counter(df[category].values).most_common(4)) plt.bar(*zip(*bar_plot.items())) plt.show()" }, { "code": null, "e": 4164, "s": 4114, "text": "Let’s now call the function with ‘provider_name’:" }, { "code": null, "e": 4198, "s": 4164, "text": "plot_most_common('provider_name')" }, { "code": null, "e": 4269, "s": 4198, "text": "We can also look at the four most common values for ‘drg_description’:" }, { "code": null, "e": 4305, "s": 4269, "text": "plot_most_common('drg_description')" }, { "code": null, "e": 4605, "s": 4305, "text": "We can also define a function to generate boxplots across categorical values. We use boxplots to visualize the distribution in numeric values based on the minimum, maximum, median, first quartile, and third quartile. If you are unfamiliar with them take a look at the article Understanding Boxplots." }, { "code": null, "e": 4751, "s": 4605, "text": "The function takes a data frame, categorical column and numerical column and displays boxplots for the most common categories based on the limit:" }, { "code": null, "e": 5097, "s": 4751, "text": "def get_boxplot_of_categories(data_frame, categorical_column, numerical_column, limit): keys = [] for i in dict(Counter(df[categorical_column].values).most_common(limit)): keys.append(i) print(keys) df_new = df[df[categorical_column].isin(keys)] sns.boxplot(x = df_new[categorical_column], y = df_new[numerical_column])" }, { "code": null, "e": 5200, "s": 5097, "text": "Let’s generate boxplots for average medicare payments in the 5 most commonly occurring provider names:" }, { "code": null, "e": 5279, "s": 5200, "text": "get_boxplot_of_categories(df, 'provider_name', 'average_medicare_payments', 5)" }, { "code": null, "e": 5334, "s": 5279, "text": "We can generate a similar plot for ‘total_discharges’:" }, { "code": null, "e": 5404, "s": 5334, "text": "get_boxplot_of_categories(df, 'provider_name', 'total_discharges', 5)" }, { "code": null, "e": 5582, "s": 5404, "text": "We can also build a scatterplot function. This function takes a data frame, categorical column, categorical value, and two numerical columns as input and displays a scatterplot:" }, { "code": null, "e": 6007, "s": 5582, "text": "def get_scatter_plot_category(data_frame, categorical_column, categorical_value, numerical_column_one, numerical_column_two): import matplotlib.pyplot as plt import seaborn as snsdf_new = data_frame[data_frame[categorical_column] == categorical_value] sns.set() plt.scatter(x= df_new[numerical_column_one], y = df_new[numerical_column_two]) plt.xlabel(numerical_column_one) plt.ylabel(numerical_column_two)" }, { "code": null, "e": 6117, "s": 6007, "text": "Let’s generate a scatterplot of average_medicare_payments vs total_discharges for ‘GOOD SAMARITAN HOSPITAL’ :" }, { "code": null, "e": 6240, "s": 6117, "text": "get_scatter_plot_category(df, 'provider_name', 'GOOD SAMARITAN HOSPITAL', 'average_medicare_payments', 'total_discharges')" }, { "code": null, "e": 6308, "s": 6240, "text": "We can also look at the same plot for ‘NORTH SHORE MEDICAL CENTER’:" }, { "code": null, "e": 6434, "s": 6308, "text": "get_scatter_plot_category(df, 'provider_name', 'NORTH SHORE MEDICAL CENTER', 'average_medicare_payments', 'total_discharges')" }, { "code": null, "e": 6851, "s": 6434, "text": "To recap, in this post I performed simple exploratory data analysis on the Medicare dataset. I analyzed the distribution in categorical values of provider names. I also generated bar charts for visualizing the frequency of provider names in the dataset. Finally, I defined functions for generating boxplots across categorical values and visualizing scatterplots of numerical values. I hope this post was interesting." } ]
Master the basics of machine learning by solving a hackathon problem | by Saurabh Mhatre | Towards Data Science
Hackathons are a good way to learn and implement new concepts in a short span of time. Today we are going to cover basic steps in machine learning and how to get a good accuracy for a regression problem while trying to achieve a decent rank using a dataset from MachineHack Hackathon. The basic steps in any solving any machine learning problem are:- Identifying the target and independent featuresCleaning the data setFeature EngineeringFeature Encoding and ScalingFeature selectionCheck distribution of target variableGet insights from graphs for fine-tuning featuresModel application and hyper-parameter tuningCombining different models Identifying the target and independent features Cleaning the data set Feature Engineering Feature Encoding and Scaling Feature selection Check distribution of target variable Get insights from graphs for fine-tuning features Model application and hyper-parameter tuning Combining different models Phew...That’s a lot of steps to cover and beginners can get easily intimidated...so let’s deep dive into the problem and cover one step at a time... You can download the dataset by creating an account on MachineHack website and download the dataset by registering for the following hackathon:- Flight ticket price prediction Now there are 3 files which are provided in the zip file you get from the hackathon:- Here Data_Train.xlsx contains the data-set using which we need to train the model, Sample_submission as the name suggests specifies the format in which output needs to be submitted in the hackathon and Test_set is the data-set on which need we need to apply our model in order to predict flight ticket prices on the basis of which our score in the hackathon will be evaluated. Now one thing we need to keep in mind is whichever transformations we are going to apply on Data_Train data-set features the same would need to be applied on Test_set data-set so that the model gets a similar type of inputs from both of them. Next, download the juptyer notebook from this GitHub repository which covers all the above steps in detail: HackathonProblemSolution Well if you have come up to this step that means you are serious about learning new things so start some nice music in another tab to get into the zone and let’s begin... 1. Identifying target and independent features First step in solving any machine learning problem is to identify the source variables (independent variables) and the target variable (dependent variable). Target variable, in a machine learning context, is the variable should be the output. For example, it could be binary 0 or 1 if you are classifying or it could be a continuous variable if you are doing a regression. Independent variables (also referred to as Features) are the input for a process that is being analyzed. We have been provided the following information about the dataset on the official website:- Size of training set: 10683 records Size of test set: 2671 records FEATURES:Airline: The name of the airline. Date_of_Journey: The date of the journey Source: The source from which the service begins. Destination: The destination where the service ends. Route: The route that was taken by the flight to reach the destination. Dep_Time: The time when the journey starts from the source. Arrival_Time: Time of arrival at the destination. Duration: Total duration of the flight. Total_Stops: Total stops between the source and destination. Additional_Info: Additional information about the flight Price: The price of the ticket Let us import the dataset in the jupyter notebook using pd.read_excel command. You can find information about importing various kind of files in pandas here. Let us use df.head() command in pandas to get an idea about the columns in our dataset. Just keep in mind that I have kept the name of the dataset on which we are training the model as df_train Here we can see that price column is the target variable and since it has continuous values i.e. which cannot be classified into specific categories, the problem is a supervised regression one. 2. Cleaning the dataset: First, let us check the number of missing values in our dataset using df.isnull() command:- Since we have only one null value in our dataset I am simply removing it, as making efforts to impute a single value does not seem like a good option. But keep in mind that the general rule of thumb is if more than 30% values in any particular column are missing then we can exclude that column. Removing null values is easy in pandas by running the below command:- Here inplace parameter is used to do the operation implicitly i.e. apply the operation directly to the specified dataframe. Next, we should check if our dataset has any duplicates rows and drop them:- The df.duplicated() is used to find the total duplicate entries in our dataframe. Next, we need to drop the duplicate entries by running the following command:- #remove duplicate rows in training datasetdf_train.drop_duplicates(keep='first',inplace=True) In the drop_duplicates command above, keep='first' option allows us to keep the first occurrence of the row values while removing all the subsequent occurrences. You can now also remove unnecessary columns simply by taking a look at dataset at this step only. In the present dataset, there were no such columns so we can proceed ahead. If you observe the steps taken in the Data cleaning section of the notebook we have merged repeating values in Additional_Info column and renamed values in Total_Stops column. 3) Feature Engineering:- Feature engineering is the process of using domain knowledge of the problem and a bit of common sense to create new features which can increase the predictive power of machine learning models. This step does require quite a bit of imagination, critical thinking about the input features and using a part of your creative side. The Date_of_Journey column is in itself not quite useful but we can create new features from it like whether the flight was on a weekend or not, the day of the week and month. Whoa...That looks like a complicated piece of code to understand...Trust me I did not come up with it by myself and can probably never will. But this is where StackOverflow came to the rescue. You can read further about the code from the below links since this will help you in a)Understanding various ways in which same task can be achieved in python b)Just in case tomorrow this code snippet becomes redundant or doesn’t work for you guess which site is going to help you in finding the solution 😉 Links:- 1) Getting the day of the week in python 2) Check if a day falls on a weekend in pandas 3) Get year, month and day from a datetime variable in pandas We then convert the duration column values into minutes:- If you take a look at Duration column the format of values is like 2h 50m with some rows containing only hour values while some only minutes(Like how could someone enjoy a flight which ends in less than an hour but that’s a discussion for some other day) So in the above code, the initial for loops separate the hours and minutes parts while the second for loop is used to convert the duration into minutes. P.S. I even tried converting into seconds for improving the accuracy but please don’t follow such stupid steps unless you have loads of free time and hell-bent on improving rank on the leader-board 👻 Next, we have created a new column called called Duration_minutes and dropped the original Duration column from the dataframe. I have also performed similar steps on Arrival_Time column which you can follow up in the notebook. 4) Feature Encoding and Scaling:- We usually perform feature scaling and encoding on independent i.e input variables so let us separate the target and input variables from each other in the dataframe. Here X contains the data frame of input features while y is our target variable. I will cover the reason for applying log transformation to y in the next section. For now, let us focus on our input variables dataframe viz X The first step is to split input variables into categorical and numerical variables. Categorical variables contain a finite number of categories or distinct groups. Categorical data might not have a logical order. For example, categorical predictors include gender, material type, and payment method. Numerical variables as the name suggest contains continuous or discrete numerical values. We can make the split using df.select_dtypes() method:- In the case of categorical features, we can either apply label encoding or one hot encoding. You can read further about both the techniques here: Implementation When to use label encoding vs Label encoder In the current dataset, we have done label encoding for categorical features. In the case of numerical features, we can perform different types of scaling like MinMax, StandardScaler or BoxCox tranformation. I tried variations of standard scaling, min-max scaling and boxcox transformation for numerical ones. In the end, boxcox transformation gave the best accuracy score. The Box-Cox transformation is a family of power transform functions that are used to stabilize variance and make a dataset look more like a normal distribution. Explanation about box-cox transformation can be found here. The lam variable specifies the type of transformation to be applied:- lambda = -1. is a reciprocal transform. lambda = -0.5 is a reciprocal square root transform. lambda = 0.0 is a log transform. lambda = 0.5 is a square root transform. lambda = 1.0 is no transform. Once we are done with above transformations we join the categorical and numerical features back to get a set of transformed input variables. 5) Feature selection:- We can apply tree-based regression models like random forest regressor, extra trees, and xgboost to get feature importances. For example, RandomForestRegressor model can be applied on the dataset as follows:- We first split the dataset into training and testing samples using train_test_split method. The test_size param specifies the proportion of training and test data. A value of 0.3 i.e 30% splits the data into a 70:30 ratio of training and test data. We then define RandomForestRegressor model and apply it on the training sample(X_train, y_train). Then we make prediction on testing input sample(X_test) and compare it with the original target sample(y_test) to get various accuracy metrics. I will cover the accuracy metrics in further sections of the article. For now let us see feature importance predicted by the model using the function below:- In the above function, we create a new dataframe from feature importances provided by the model in descending order of importance. Then we create a horizontal bar plot using matplotlib library to see the feature importances visually. In the case of random forest regressor, the output of the function is:- As we can see the duration column has the highest importance while source city from which flight originated has the lowest feature importance. We can either select features manually from the graphs generated above or we can use SelectFromModel module from sklearn to select the most appropriate features automatically. I tried running the model on selected features according to above feature importances but accuracy reduced slightly which might be great if we were deploying the model in real-world scenario since the model is now a bit more robust but for a hackathon, accuracy matters the most so I ended up keeping all the features in the end. 7) Check distribution of target variable:- We should check the distribution of the target variable in a regression problem using distribution plot. If it is skewed then application of log, exponent or sqrt transform can help in reducing the skewness to get a normal distribution. The distribution of the target variable in our case initially was a bit right skewed:- After applying log transformation, it was normally distributed:- The log transformation did improve the overall accuracy of the model at the end which was the reason I applied log transformation to target input at the beginning of Step 4 above. 8) Get insights from graphs:- Check variation of target column with respect to input variables and distribution of various input variables:- The price should have increased with increase in duration but this was not the case here. Next, we check the variation of price against the total number of stops:- Insight from the above graph:-As expected, the price of flight tickets is higher for flights with a greater number of stops The distribution of numerical features can be checked using a histogram plot while the distribution on categorical features can be checked using a bar plot or box plot. In case of categorical features check if any of the column values can be combined together while in case of numerical features check if distribution can be normalized i.e. evenly distributed. I went back into categorical features and clubbed together last four airline categories later. Similar steps were followed for Additional_Info column:- You can find histograms of numerical features in the jupyter notebook and make necessary transformations if required. 9)Model application and hyper-parameter tuning:- After trying different kinds of regression models I found ExtraTrees, RandomForest, and XGboost gave slightly better accuracy than other models so it was time to perform hyperparameter tuning on all 3 of them to improve accuracy further. In machine learning, a hyperparameter is a parameter whose value is set before the learning process begins. We need to come up with optimum values of hyperparameters because these values are external to the model and their value cannot be estimated from data. Hyperparameter tuning is the process of choosing a set of optimal hyperparameters for a learning algorithm. The two common approaches to do hyperparameter tuning are GridSearchCV and RandomisedSearchCV. Although GridSearchCV is exhaustive, RandomisedSearchCV is helpful to get a range of relevant values quickly. More information about them can be found here. In the case of the RandomForest algorithm, the following article from towards data science helps us to understand how to do hyperparameter tuning properly:- Article Link A similar approach can be applied for ExtraTrees and XGBoost Regressor Models. 10) Combining different models Stacking is an ensemble learning technique in which we can combine multiple regression models via a meta-classifier or a meta-regressor. The base level models are trained based on a complete training set, then the meta-model is trained on the outputs of the base level models as input features. In the last step I combined above three models using the stacking technique to improve overall accuracy:- Here base models used are ExtraTrees, Random Forest and XGBoost Regressor while the meta-model used is Lasso. You can learn more about how to implement stacking here. Next, we fit the stacked model and make predictions on the test data sample Next, I have created a simple function to print all available accuracy metrics in the regression model:- Once we have our stacked model trained we simply need to apply the model on prediction dataset and submit the values to the hackathon website, which finishes of all the essential steps required in solving a machine learning problem. The final metrics of the stacked model are:- R-squared measures the strength of the relationship between your model and the dependent variables on a 0–1 scale. The information about other metrics can be found here. Hope you got at least a bit of a grasp on how to approach a supervised machine learning problem after finishing all the steps above. If you have any doubts, suggestions or corrections do mention them in the comments section and if you like this article show a bit of appreciation by sharing it with others. And last but not the least happy coding 🤓
[ { "code": null, "e": 332, "s": 47, "text": "Hackathons are a good way to learn and implement new concepts in a short span of time. Today we are going to cover basic steps in machine learning and how to get a good accuracy for a regression problem while trying to achieve a decent rank using a dataset from MachineHack Hackathon." }, { "code": null, "e": 398, "s": 332, "text": "The basic steps in any solving any machine learning problem are:-" }, { "code": null, "e": 687, "s": 398, "text": "Identifying the target and independent featuresCleaning the data setFeature EngineeringFeature Encoding and ScalingFeature selectionCheck distribution of target variableGet insights from graphs for fine-tuning featuresModel application and hyper-parameter tuningCombining different models" }, { "code": null, "e": 735, "s": 687, "text": "Identifying the target and independent features" }, { "code": null, "e": 757, "s": 735, "text": "Cleaning the data set" }, { "code": null, "e": 777, "s": 757, "text": "Feature Engineering" }, { "code": null, "e": 806, "s": 777, "text": "Feature Encoding and Scaling" }, { "code": null, "e": 824, "s": 806, "text": "Feature selection" }, { "code": null, "e": 862, "s": 824, "text": "Check distribution of target variable" }, { "code": null, "e": 912, "s": 862, "text": "Get insights from graphs for fine-tuning features" }, { "code": null, "e": 957, "s": 912, "text": "Model application and hyper-parameter tuning" }, { "code": null, "e": 984, "s": 957, "text": "Combining different models" }, { "code": null, "e": 1133, "s": 984, "text": "Phew...That’s a lot of steps to cover and beginners can get easily intimidated...so let’s deep dive into the problem and cover one step at a time..." }, { "code": null, "e": 1309, "s": 1133, "text": "You can download the dataset by creating an account on MachineHack website and download the dataset by registering for the following hackathon:- Flight ticket price prediction" }, { "code": null, "e": 1395, "s": 1309, "text": "Now there are 3 files which are provided in the zip file you get from the hackathon:-" }, { "code": null, "e": 1772, "s": 1395, "text": "Here Data_Train.xlsx contains the data-set using which we need to train the model, Sample_submission as the name suggests specifies the format in which output needs to be submitted in the hackathon and Test_set is the data-set on which need we need to apply our model in order to predict flight ticket prices on the basis of which our score in the hackathon will be evaluated." }, { "code": null, "e": 2015, "s": 1772, "text": "Now one thing we need to keep in mind is whichever transformations we are going to apply on Data_Train data-set features the same would need to be applied on Test_set data-set so that the model gets a similar type of inputs from both of them." }, { "code": null, "e": 2123, "s": 2015, "text": "Next, download the juptyer notebook from this GitHub repository which covers all the above steps in detail:" }, { "code": null, "e": 2148, "s": 2123, "text": "HackathonProblemSolution" }, { "code": null, "e": 2319, "s": 2148, "text": "Well if you have come up to this step that means you are serious about learning new things so start some nice music in another tab to get into the zone and let’s begin..." }, { "code": null, "e": 2366, "s": 2319, "text": "1. Identifying target and independent features" }, { "code": null, "e": 2523, "s": 2366, "text": "First step in solving any machine learning problem is to identify the source variables (independent variables) and the target variable (dependent variable)." }, { "code": null, "e": 2739, "s": 2523, "text": "Target variable, in a machine learning context, is the variable should be the output. For example, it could be binary 0 or 1 if you are classifying or it could be a continuous variable if you are doing a regression." }, { "code": null, "e": 2844, "s": 2739, "text": "Independent variables (also referred to as Features) are the input for a process that is being analyzed." }, { "code": null, "e": 2936, "s": 2844, "text": "We have been provided the following information about the dataset on the official website:-" }, { "code": null, "e": 2972, "s": 2936, "text": "Size of training set: 10683 records" }, { "code": null, "e": 3003, "s": 2972, "text": "Size of test set: 2671 records" }, { "code": null, "e": 3046, "s": 3003, "text": "FEATURES:Airline: The name of the airline." }, { "code": null, "e": 3087, "s": 3046, "text": "Date_of_Journey: The date of the journey" }, { "code": null, "e": 3137, "s": 3087, "text": "Source: The source from which the service begins." }, { "code": null, "e": 3190, "s": 3137, "text": "Destination: The destination where the service ends." }, { "code": null, "e": 3262, "s": 3190, "text": "Route: The route that was taken by the flight to reach the destination." }, { "code": null, "e": 3322, "s": 3262, "text": "Dep_Time: The time when the journey starts from the source." }, { "code": null, "e": 3372, "s": 3322, "text": "Arrival_Time: Time of arrival at the destination." }, { "code": null, "e": 3412, "s": 3372, "text": "Duration: Total duration of the flight." }, { "code": null, "e": 3473, "s": 3412, "text": "Total_Stops: Total stops between the source and destination." }, { "code": null, "e": 3530, "s": 3473, "text": "Additional_Info: Additional information about the flight" }, { "code": null, "e": 3561, "s": 3530, "text": "Price: The price of the ticket" }, { "code": null, "e": 3719, "s": 3561, "text": "Let us import the dataset in the jupyter notebook using pd.read_excel command. You can find information about importing various kind of files in pandas here." }, { "code": null, "e": 3913, "s": 3719, "text": "Let us use df.head() command in pandas to get an idea about the columns in our dataset. Just keep in mind that I have kept the name of the dataset on which we are training the model as df_train" }, { "code": null, "e": 4107, "s": 3913, "text": "Here we can see that price column is the target variable and since it has continuous values i.e. which cannot be classified into specific categories, the problem is a supervised regression one." }, { "code": null, "e": 4132, "s": 4107, "text": "2. Cleaning the dataset:" }, { "code": null, "e": 4224, "s": 4132, "text": "First, let us check the number of missing values in our dataset using df.isnull() command:-" }, { "code": null, "e": 4375, "s": 4224, "text": "Since we have only one null value in our dataset I am simply removing it, as making efforts to impute a single value does not seem like a good option." }, { "code": null, "e": 4520, "s": 4375, "text": "But keep in mind that the general rule of thumb is if more than 30% values in any particular column are missing then we can exclude that column." }, { "code": null, "e": 4590, "s": 4520, "text": "Removing null values is easy in pandas by running the below command:-" }, { "code": null, "e": 4714, "s": 4590, "text": "Here inplace parameter is used to do the operation implicitly i.e. apply the operation directly to the specified dataframe." }, { "code": null, "e": 4791, "s": 4714, "text": "Next, we should check if our dataset has any duplicates rows and drop them:-" }, { "code": null, "e": 4873, "s": 4791, "text": "The df.duplicated() is used to find the total duplicate entries in our dataframe." }, { "code": null, "e": 4952, "s": 4873, "text": "Next, we need to drop the duplicate entries by running the following command:-" }, { "code": null, "e": 5046, "s": 4952, "text": "#remove duplicate rows in training datasetdf_train.drop_duplicates(keep='first',inplace=True)" }, { "code": null, "e": 5208, "s": 5046, "text": "In the drop_duplicates command above, keep='first' option allows us to keep the first occurrence of the row values while removing all the subsequent occurrences." }, { "code": null, "e": 5382, "s": 5208, "text": "You can now also remove unnecessary columns simply by taking a look at dataset at this step only. In the present dataset, there were no such columns so we can proceed ahead." }, { "code": null, "e": 5558, "s": 5382, "text": "If you observe the steps taken in the Data cleaning section of the notebook we have merged repeating values in Additional_Info column and renamed values in Total_Stops column." }, { "code": null, "e": 5583, "s": 5558, "text": "3) Feature Engineering:-" }, { "code": null, "e": 5910, "s": 5583, "text": "Feature engineering is the process of using domain knowledge of the problem and a bit of common sense to create new features which can increase the predictive power of machine learning models. This step does require quite a bit of imagination, critical thinking about the input features and using a part of your creative side." }, { "code": null, "e": 6086, "s": 5910, "text": "The Date_of_Journey column is in itself not quite useful but we can create new features from it like whether the flight was on a weekend or not, the day of the week and month." }, { "code": null, "e": 6364, "s": 6086, "text": "Whoa...That looks like a complicated piece of code to understand...Trust me I did not come up with it by myself and can probably never will. But this is where StackOverflow came to the rescue. You can read further about the code from the below links since this will help you in" }, { "code": null, "e": 6438, "s": 6364, "text": "a)Understanding various ways in which same task can be achieved in python" }, { "code": null, "e": 6586, "s": 6438, "text": "b)Just in case tomorrow this code snippet becomes redundant or doesn’t work for you guess which site is going to help you in finding the solution 😉" }, { "code": null, "e": 6594, "s": 6586, "text": "Links:-" }, { "code": null, "e": 6635, "s": 6594, "text": "1) Getting the day of the week in python" }, { "code": null, "e": 6682, "s": 6635, "text": "2) Check if a day falls on a weekend in pandas" }, { "code": null, "e": 6744, "s": 6682, "text": "3) Get year, month and day from a datetime variable in pandas" }, { "code": null, "e": 6802, "s": 6744, "text": "We then convert the duration column values into minutes:-" }, { "code": null, "e": 7057, "s": 6802, "text": "If you take a look at Duration column the format of values is like 2h 50m with some rows containing only hour values while some only minutes(Like how could someone enjoy a flight which ends in less than an hour but that’s a discussion for some other day)" }, { "code": null, "e": 7210, "s": 7057, "text": "So in the above code, the initial for loops separate the hours and minutes parts while the second for loop is used to convert the duration into minutes." }, { "code": null, "e": 7410, "s": 7210, "text": "P.S. I even tried converting into seconds for improving the accuracy but please don’t follow such stupid steps unless you have loads of free time and hell-bent on improving rank on the leader-board 👻" }, { "code": null, "e": 7537, "s": 7410, "text": "Next, we have created a new column called called Duration_minutes and dropped the original Duration column from the dataframe." }, { "code": null, "e": 7637, "s": 7537, "text": "I have also performed similar steps on Arrival_Time column which you can follow up in the notebook." }, { "code": null, "e": 7671, "s": 7637, "text": "4) Feature Encoding and Scaling:-" }, { "code": null, "e": 7838, "s": 7671, "text": "We usually perform feature scaling and encoding on independent i.e input variables so let us separate the target and input variables from each other in the dataframe." }, { "code": null, "e": 8062, "s": 7838, "text": "Here X contains the data frame of input features while y is our target variable. I will cover the reason for applying log transformation to y in the next section. For now, let us focus on our input variables dataframe viz X" }, { "code": null, "e": 8147, "s": 8062, "text": "The first step is to split input variables into categorical and numerical variables." }, { "code": null, "e": 8363, "s": 8147, "text": "Categorical variables contain a finite number of categories or distinct groups. Categorical data might not have a logical order. For example, categorical predictors include gender, material type, and payment method." }, { "code": null, "e": 8453, "s": 8363, "text": "Numerical variables as the name suggest contains continuous or discrete numerical values." }, { "code": null, "e": 8509, "s": 8453, "text": "We can make the split using df.select_dtypes() method:-" }, { "code": null, "e": 8602, "s": 8509, "text": "In the case of categorical features, we can either apply label encoding or one hot encoding." }, { "code": null, "e": 8655, "s": 8602, "text": "You can read further about both the techniques here:" }, { "code": null, "e": 8670, "s": 8655, "text": "Implementation" }, { "code": null, "e": 8714, "s": 8670, "text": "When to use label encoding vs Label encoder" }, { "code": null, "e": 8792, "s": 8714, "text": "In the current dataset, we have done label encoding for categorical features." }, { "code": null, "e": 8922, "s": 8792, "text": "In the case of numerical features, we can perform different types of scaling like MinMax, StandardScaler or BoxCox tranformation." }, { "code": null, "e": 9088, "s": 8922, "text": "I tried variations of standard scaling, min-max scaling and boxcox transformation for numerical ones. In the end, boxcox transformation gave the best accuracy score." }, { "code": null, "e": 9309, "s": 9088, "text": "The Box-Cox transformation is a family of power transform functions that are used to stabilize variance and make a dataset look more like a normal distribution. Explanation about box-cox transformation can be found here." }, { "code": null, "e": 9379, "s": 9309, "text": "The lam variable specifies the type of transformation to be applied:-" }, { "code": null, "e": 9419, "s": 9379, "text": "lambda = -1. is a reciprocal transform." }, { "code": null, "e": 9472, "s": 9419, "text": "lambda = -0.5 is a reciprocal square root transform." }, { "code": null, "e": 9505, "s": 9472, "text": "lambda = 0.0 is a log transform." }, { "code": null, "e": 9546, "s": 9505, "text": "lambda = 0.5 is a square root transform." }, { "code": null, "e": 9576, "s": 9546, "text": "lambda = 1.0 is no transform." }, { "code": null, "e": 9717, "s": 9576, "text": "Once we are done with above transformations we join the categorical and numerical features back to get a set of transformed input variables." }, { "code": null, "e": 9740, "s": 9717, "text": "5) Feature selection:-" }, { "code": null, "e": 9865, "s": 9740, "text": "We can apply tree-based regression models like random forest regressor, extra trees, and xgboost to get feature importances." }, { "code": null, "e": 9949, "s": 9865, "text": "For example, RandomForestRegressor model can be applied on the dataset as follows:-" }, { "code": null, "e": 10296, "s": 9949, "text": "We first split the dataset into training and testing samples using train_test_split method. The test_size param specifies the proportion of training and test data. A value of 0.3 i.e 30% splits the data into a 70:30 ratio of training and test data. We then define RandomForestRegressor model and apply it on the training sample(X_train, y_train)." }, { "code": null, "e": 10510, "s": 10296, "text": "Then we make prediction on testing input sample(X_test) and compare it with the original target sample(y_test) to get various accuracy metrics. I will cover the accuracy metrics in further sections of the article." }, { "code": null, "e": 10598, "s": 10510, "text": "For now let us see feature importance predicted by the model using the function below:-" }, { "code": null, "e": 10729, "s": 10598, "text": "In the above function, we create a new dataframe from feature importances provided by the model in descending order of importance." }, { "code": null, "e": 10832, "s": 10729, "text": "Then we create a horizontal bar plot using matplotlib library to see the feature importances visually." }, { "code": null, "e": 10904, "s": 10832, "text": "In the case of random forest regressor, the output of the function is:-" }, { "code": null, "e": 11047, "s": 10904, "text": "As we can see the duration column has the highest importance while source city from which flight originated has the lowest feature importance." }, { "code": null, "e": 11223, "s": 11047, "text": "We can either select features manually from the graphs generated above or we can use SelectFromModel module from sklearn to select the most appropriate features automatically." }, { "code": null, "e": 11553, "s": 11223, "text": "I tried running the model on selected features according to above feature importances but accuracy reduced slightly which might be great if we were deploying the model in real-world scenario since the model is now a bit more robust but for a hackathon, accuracy matters the most so I ended up keeping all the features in the end." }, { "code": null, "e": 11596, "s": 11553, "text": "7) Check distribution of target variable:-" }, { "code": null, "e": 11833, "s": 11596, "text": "We should check the distribution of the target variable in a regression problem using distribution plot. If it is skewed then application of log, exponent or sqrt transform can help in reducing the skewness to get a normal distribution." }, { "code": null, "e": 11920, "s": 11833, "text": "The distribution of the target variable in our case initially was a bit right skewed:-" }, { "code": null, "e": 11985, "s": 11920, "text": "After applying log transformation, it was normally distributed:-" }, { "code": null, "e": 12165, "s": 11985, "text": "The log transformation did improve the overall accuracy of the model at the end which was the reason I applied log transformation to target input at the beginning of Step 4 above." }, { "code": null, "e": 12195, "s": 12165, "text": "8) Get insights from graphs:-" }, { "code": null, "e": 12306, "s": 12195, "text": "Check variation of target column with respect to input variables and distribution of various input variables:-" }, { "code": null, "e": 12396, "s": 12306, "text": "The price should have increased with increase in duration but this was not the case here." }, { "code": null, "e": 12470, "s": 12396, "text": "Next, we check the variation of price against the total number of stops:-" }, { "code": null, "e": 12594, "s": 12470, "text": "Insight from the above graph:-As expected, the price of flight tickets is higher for flights with a greater number of stops" }, { "code": null, "e": 12763, "s": 12594, "text": "The distribution of numerical features can be checked using a histogram plot while the distribution on categorical features can be checked using a bar plot or box plot." }, { "code": null, "e": 12955, "s": 12763, "text": "In case of categorical features check if any of the column values can be combined together while in case of numerical features check if distribution can be normalized i.e. evenly distributed." }, { "code": null, "e": 13050, "s": 12955, "text": "I went back into categorical features and clubbed together last four airline categories later." }, { "code": null, "e": 13107, "s": 13050, "text": "Similar steps were followed for Additional_Info column:-" }, { "code": null, "e": 13225, "s": 13107, "text": "You can find histograms of numerical features in the jupyter notebook and make necessary transformations if required." }, { "code": null, "e": 13274, "s": 13225, "text": "9)Model application and hyper-parameter tuning:-" }, { "code": null, "e": 13512, "s": 13274, "text": "After trying different kinds of regression models I found ExtraTrees, RandomForest, and XGboost gave slightly better accuracy than other models so it was time to perform hyperparameter tuning on all 3 of them to improve accuracy further." }, { "code": null, "e": 13772, "s": 13512, "text": "In machine learning, a hyperparameter is a parameter whose value is set before the learning process begins. We need to come up with optimum values of hyperparameters because these values are external to the model and their value cannot be estimated from data." }, { "code": null, "e": 13975, "s": 13772, "text": "Hyperparameter tuning is the process of choosing a set of optimal hyperparameters for a learning algorithm. The two common approaches to do hyperparameter tuning are GridSearchCV and RandomisedSearchCV." }, { "code": null, "e": 14132, "s": 13975, "text": "Although GridSearchCV is exhaustive, RandomisedSearchCV is helpful to get a range of relevant values quickly. More information about them can be found here." }, { "code": null, "e": 14302, "s": 14132, "text": "In the case of the RandomForest algorithm, the following article from towards data science helps us to understand how to do hyperparameter tuning properly:- Article Link" }, { "code": null, "e": 14381, "s": 14302, "text": "A similar approach can be applied for ExtraTrees and XGBoost Regressor Models." }, { "code": null, "e": 14412, "s": 14381, "text": "10) Combining different models" }, { "code": null, "e": 14707, "s": 14412, "text": "Stacking is an ensemble learning technique in which we can combine multiple regression models via a meta-classifier or a meta-regressor. The base level models are trained based on a complete training set, then the meta-model is trained on the outputs of the base level models as input features." }, { "code": null, "e": 14813, "s": 14707, "text": "In the last step I combined above three models using the stacking technique to improve overall accuracy:-" }, { "code": null, "e": 14980, "s": 14813, "text": "Here base models used are ExtraTrees, Random Forest and XGBoost Regressor while the meta-model used is Lasso. You can learn more about how to implement stacking here." }, { "code": null, "e": 15056, "s": 14980, "text": "Next, we fit the stacked model and make predictions on the test data sample" }, { "code": null, "e": 15161, "s": 15056, "text": "Next, I have created a simple function to print all available accuracy metrics in the regression model:-" }, { "code": null, "e": 15394, "s": 15161, "text": "Once we have our stacked model trained we simply need to apply the model on prediction dataset and submit the values to the hackathon website, which finishes of all the essential steps required in solving a machine learning problem." }, { "code": null, "e": 15439, "s": 15394, "text": "The final metrics of the stacked model are:-" }, { "code": null, "e": 15609, "s": 15439, "text": "R-squared measures the strength of the relationship between your model and the dependent variables on a 0–1 scale. The information about other metrics can be found here." }, { "code": null, "e": 15916, "s": 15609, "text": "Hope you got at least a bit of a grasp on how to approach a supervised machine learning problem after finishing all the steps above. If you have any doubts, suggestions or corrections do mention them in the comments section and if you like this article show a bit of appreciation by sharing it with others." } ]
How can I pass parameters to on_key in fig.canvas.mpl_connect('key_press_event',on_key)?
To pass parameters to on_key in fig.canvas.mpl_connect('key_press_event', on_key), we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Create a figure and a set of subplots. Set x and y scale of the axes. Bind the function to the event. To display the figure, use show() method. import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True fig, ax = plt.subplots() ax.set_xlim(0, 10) ax.set_ylim(0, 10) def onkey(event): if event.key.isalpha(): if event.xdata is not None and event.ydata is not None: ax.plot(event.xdata, event.ydata, 'bo-') fig.canvas.draw() cid2 = fig.canvas.mpl_connect('key_press_event', onkey) plt.show()
[ { "code": null, "e": 1179, "s": 1062, "text": "To pass parameters to on_key in fig.canvas.mpl_connect('key_press_event', on_key), we can take the following steps −" }, { "code": null, "e": 1255, "s": 1179, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1294, "s": 1255, "text": "Create a figure and a set of subplots." }, { "code": null, "e": 1325, "s": 1294, "text": "Set x and y scale of the axes." }, { "code": null, "e": 1357, "s": 1325, "text": "Bind the function to the event." }, { "code": null, "e": 1399, "s": 1357, "text": "To display the figure, use show() method." }, { "code": null, "e": 1835, "s": 1399, "text": "import matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nfig, ax = plt.subplots()\nax.set_xlim(0, 10)\nax.set_ylim(0, 10)\n\ndef onkey(event):\n if event.key.isalpha():\n if event.xdata is not None and event.ydata is not None:\n ax.plot(event.xdata, event.ydata, 'bo-')\n fig.canvas.draw()\n\ncid2 = fig.canvas.mpl_connect('key_press_event', onkey)\nplt.show()" } ]
mysqlcheck - A MySQL Table Maintenance Program
The mysqlcheck client performs table maintenance. It checks, repairs, optimizes, or analyses tables. If the user uses the --databases or --all-databases option to process all tables in one or more databases, invoking mysqlcheck would take a long time. This is true for the MySQL upgrade procedure as well, if it determines that the table checking is required since it processes tables in the same way. The command mysqlcheck should be used when the mysqld server is running. This means that the user need not have to stop the server to perform table maintenance. It uses the SQL statements such as CHECK TABLE, REPAIR TABLE, ANALYZE TABLE, and OPTIMIZE TABLE in a convenient way for the user. The command mysqlcheck should be used when the mysqld server is running. This means that the user need not have to stop the server to perform table maintenance. It uses the SQL statements such as CHECK TABLE, REPAIR TABLE, ANALYZE TABLE, and OPTIMIZE TABLE in a convenient way for the user. It helps determine which statements need to be used for the operation that needs to be performed. It then sends the statements to the server so as to be executed. It helps determine which statements need to be used for the operation that needs to be performed. It then sends the statements to the server so as to be executed. The three ways to invoke mysqlcheck − shell> mysqlcheck [options] db_name [tbl_name ...] shell> mysqlcheck [options] --databases db_name ... shell> mysqlcheck [options] --all-databases The default behaviour of mysqlcheck is checking tables (--check) that can be changed by renaming the binary. If the user has a tool that repairs tables by default, then a copy of mysqlcheck named mysqlrepair needs to be made. Otherwise, a symbolic link to mysqlcheck named mysqlrepair need to be made. If the user invokes mysqlrepair, it repairs tables. mysqlrepair: It is the default option is –repair. mysqlrepair: It is the default option is –repair. mysqlanalyze: It is the default option is –analyze. mysqlanalyze: It is the default option is –analyze. mysqloptimize: It is the default option is –optimize. mysqloptimize: It is the default option is –optimize.
[ { "code": null, "e": 1464, "s": 1062, "text": "The mysqlcheck client performs table maintenance. It checks, repairs, optimizes, or analyses tables. If the user uses the --databases or --all-databases option to process all tables in one or more databases, invoking mysqlcheck would take a long time. This is true for the MySQL upgrade procedure as well, if it determines that the table checking is required since it processes tables in the same way." }, { "code": null, "e": 1755, "s": 1464, "text": "The command mysqlcheck should be used when the mysqld server is running. This means that the user need not have to stop the server to perform table maintenance. It uses the SQL statements such as CHECK TABLE, REPAIR TABLE, ANALYZE TABLE, and OPTIMIZE TABLE in a convenient way for the user." }, { "code": null, "e": 2046, "s": 1755, "text": "The command mysqlcheck should be used when the mysqld server is running. This means that the user need not have to stop the server to perform table maintenance. It uses the SQL statements such as CHECK TABLE, REPAIR TABLE, ANALYZE TABLE, and OPTIMIZE TABLE in a convenient way for the user." }, { "code": null, "e": 2209, "s": 2046, "text": "It helps determine which statements need to be used for the operation that needs to be performed. It then sends the statements to the server so as to be executed." }, { "code": null, "e": 2372, "s": 2209, "text": "It helps determine which statements need to be used for the operation that needs to be performed. It then sends the statements to the server so as to be executed." }, { "code": null, "e": 2410, "s": 2372, "text": "The three ways to invoke mysqlcheck −" }, { "code": null, "e": 2557, "s": 2410, "text": "shell> mysqlcheck [options] db_name [tbl_name ...]\nshell> mysqlcheck [options] --databases db_name ...\nshell> mysqlcheck [options] --all-databases" }, { "code": null, "e": 2911, "s": 2557, "text": "The default behaviour of mysqlcheck is checking tables (--check) that can be changed by renaming the binary. If the user has a tool that repairs tables by default, then a copy of mysqlcheck named mysqlrepair needs to be made. Otherwise, a symbolic link to mysqlcheck named mysqlrepair need to be made. If the user invokes mysqlrepair, it repairs tables." }, { "code": null, "e": 2961, "s": 2911, "text": "mysqlrepair: It is the default option is –repair." }, { "code": null, "e": 3011, "s": 2961, "text": "mysqlrepair: It is the default option is –repair." }, { "code": null, "e": 3063, "s": 3011, "text": "mysqlanalyze: It is the default option is –analyze." }, { "code": null, "e": 3115, "s": 3063, "text": "mysqlanalyze: It is the default option is –analyze." }, { "code": null, "e": 3169, "s": 3115, "text": "mysqloptimize: It is the default option is –optimize." }, { "code": null, "e": 3223, "s": 3169, "text": "mysqloptimize: It is the default option is –optimize." } ]
Add minimum number to an array so that the sum becomes even in C programming
Given an array, add the minimum number (which should be greater than 0) to the array so that the sum of array becomes even. Input - 1 2 3 4, Output - 2 Explanation - Sum of array is 10, so we add minimum number 2 to make the sum even. Method 1: calculate the sum of all elements of the array, then check if the sum is even then add minimum number is 2, else add minimum number is 1. Input - 1 2 3 4, Output - 2 Explanation - Sum of array is 10, so we add minimum number 2 to make the sum even. #include<iostream> using namespace std; int main() { int arr[] = { 1, 2, 3, 4}; int n=4; int sum=0; for (int i = 0; i <n; i++) { sum+=arr[i]; } if (sum % 2==0) { cout <<"2"; } else { cout <<"1"; } return 0; } Method 2 - calculate count of odd number of elements in the array. If count of odd numbers present is even we return 2, else we return 1. Input - 1 2 3 4 5 Output - 1 Explanation - no. of in the array is 3add minimum number 1 to make the sum even. #include<iostream> using namespace std; int main() { int arr[] = { 1, 2, 3, 4,5}; int n=5; int odd = 0; for (int i = 0; i < n; i++) { if (arr[i] % 2!=0) { odd += 1; } } if (odd % 2==0) { cout <<"2"; } else { cout <<"1"; } return 0; } Method 3 - Take a flag variable (initialized as 0). Whenever we find the odd element in the array we perform the NOT(!) operation on the boolean variable. This logical operator inverts the value of the flag variable (meaning if it is 0, it converts the variable to 1 and vice-versa). Input - 1 2 3 4 5 Output - 1 Explanation - variable initialized as 0.Traversing the array1 is odd, variable changed 1.2 is even3 is odd, variable changed 0.4 is even5 is odd, variable changed 1 If variable value is 1 it means odd number of odd elements are present, minimum number to make sum of elements even is by adding 1. Else minimum number is 2. #include<iostream> using namespace std; int main() { int arr[] = { 1, 2, 3, 4,5}; int n=5; bool odd = 0; for (int i = 0; i < n; i++) { if (arr[i] % 2!=0) { odd = !odd; } } if (odd) { cout <<"1"; } else { cout <<"2"; } return 0; }
[ { "code": null, "e": 1186, "s": 1062, "text": "Given an array, add the minimum number (which should be greater than 0) to the array so that the sum of array becomes even." }, { "code": null, "e": 1203, "s": 1186, "text": "Input - 1 2 3 4," }, { "code": null, "e": 1214, "s": 1203, "text": "Output - 2" }, { "code": null, "e": 1255, "s": 1214, "text": "Explanation - Sum of array is 10, so we " }, { "code": null, "e": 1298, "s": 1255, "text": "add minimum number 2 to make the sum even." }, { "code": null, "e": 1446, "s": 1298, "text": "Method 1: calculate the sum of all elements of the array, then check if the sum is even then add minimum number is 2, else add minimum number is 1." }, { "code": null, "e": 1463, "s": 1446, "text": "Input - 1 2 3 4," }, { "code": null, "e": 1474, "s": 1463, "text": "Output - 2" }, { "code": null, "e": 1557, "s": 1474, "text": "Explanation - Sum of array is 10, so we\nadd minimum number 2 to make the sum even." }, { "code": null, "e": 1811, "s": 1557, "text": "#include<iostream>\nusing namespace std;\nint main() {\n int arr[] = { 1, 2, 3, 4};\n int n=4;\n int sum=0;\n for (int i = 0; i <n; i++) {\n sum+=arr[i];\n }\n if (sum % 2==0) {\n cout <<\"2\";\n } else {\n cout <<\"1\";\n }\n return 0;\n}" }, { "code": null, "e": 1949, "s": 1811, "text": "Method 2 - calculate count of odd number of elements in the array. If count of odd numbers present is even we return 2, else we return 1." }, { "code": null, "e": 1967, "s": 1949, "text": "Input - 1 2 3 4 5" }, { "code": null, "e": 1978, "s": 1967, "text": "Output - 1" }, { "code": null, "e": 2059, "s": 1978, "text": "Explanation - no. of in the array is 3add minimum number 1 to make the sum even." }, { "code": null, "e": 2353, "s": 2059, "text": "#include<iostream>\nusing namespace std;\nint main() {\n int arr[] = { 1, 2, 3, 4,5};\n int n=5;\n int odd = 0;\n for (int i = 0; i < n; i++) {\n if (arr[i] % 2!=0) {\n odd += 1;\n }\n }\n if (odd % 2==0) {\n cout <<\"2\";\n } else {\n cout <<\"1\";\n }\n return 0;\n}" }, { "code": null, "e": 2637, "s": 2353, "text": "Method 3 - Take a flag variable (initialized as 0). Whenever we find the odd element in the array we perform the NOT(!) operation on the boolean variable. This logical operator inverts the value of the flag variable (meaning if it is 0, it converts the variable to 1 and vice-versa)." }, { "code": null, "e": 2655, "s": 2637, "text": "Input - 1 2 3 4 5" }, { "code": null, "e": 2666, "s": 2655, "text": "Output - 1" }, { "code": null, "e": 2831, "s": 2666, "text": "Explanation - variable initialized as 0.Traversing the array1 is odd, variable changed 1.2 is even3 is odd, variable changed 0.4 is even5 is odd, variable changed 1" }, { "code": null, "e": 2963, "s": 2831, "text": "If variable value is 1 it means odd number of odd elements are present, minimum number to make sum of elements even is by adding 1." }, { "code": null, "e": 2989, "s": 2963, "text": "Else minimum number is 2." }, { "code": null, "e": 3279, "s": 2989, "text": "#include<iostream>\nusing namespace std;\nint main() {\n int arr[] = { 1, 2, 3, 4,5};\n int n=5;\n bool odd = 0;\n for (int i = 0; i < n; i++) {\n if (arr[i] % 2!=0) {\n odd = !odd;\n }\n }\n if (odd) {\n cout <<\"1\";\n } else {\n cout <<\"2\";\n }\n return 0;\n}" } ]
How can we implement line wrap and word wrap text inside a JTextArea in Java?
A JTextArea is a multi-line text component to display text or allow the user to enter the text and it will generate a CaretListener interface when we are trying to implement the functionality of the JTextArea component. A JTextArea class inherits the JTextComponent class in Java. In the below example, we can implement a JTextArea class with a user can select either word wrap or line wrap checkboxes using the ItemListener interface. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JTextAreaTest { public static void main(String[] args ) { EventQueue.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new JFrame("JTextArea Test"); frame.setSize(350, 275); final JTextArea textArea = new JTextArea(15, 65); frame.add(new JScrollPane(textArea)); final JCheckBox wordWrap = new JCheckBox("word wrap"); wordWrap.setSelected(textArea.getWrapStyleWord()); wordWrap.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent ie) { textArea.setWrapStyleWord(wordWrap.isSelected()); } }); frame.add(wordWrap, BorderLayout.NORTH); final JCheckBox lineWrap = new JCheckBox("line wrap"); lineWrap.setSelected(textArea.getLineWrap()); lineWrap.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent ie) { textArea.setLineWrap(lineWrap.isSelected()); } }); frame.add(lineWrap, BorderLayout.SOUTH ); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); frame.setVisible(true); } }); } }
[ { "code": null, "e": 1343, "s": 1062, "text": "A JTextArea is a multi-line text component to display text or allow the user to enter the text and it will generate a CaretListener interface when we are trying to implement the functionality of the JTextArea component. A JTextArea class inherits the JTextComponent class in Java." }, { "code": null, "e": 1498, "s": 1343, "text": "In the below example, we can implement a JTextArea class with a user can select either word wrap or line wrap checkboxes using the ItemListener interface." }, { "code": null, "e": 2961, "s": 1498, "text": "import javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.*;\npublic class JTextAreaTest {\n public static void main(String[] args ) {\n EventQueue.invokeLater(new Runnable() {\n @Override\n public void run() {\n JFrame frame = new JFrame(\"JTextArea Test\");\n frame.setSize(350, 275);\n final JTextArea textArea = new JTextArea(15, 65);\n frame.add(new JScrollPane(textArea));\n final JCheckBox wordWrap = new JCheckBox(\"word wrap\");\n wordWrap.setSelected(textArea.getWrapStyleWord());\n wordWrap.addItemListener(new ItemListener() {\n @Override\n public void itemStateChanged(ItemEvent ie) {\n textArea.setWrapStyleWord(wordWrap.isSelected());\n }\n });\n frame.add(wordWrap, BorderLayout.NORTH);\n final JCheckBox lineWrap = new JCheckBox(\"line wrap\");\n lineWrap.setSelected(textArea.getLineWrap());\n lineWrap.addItemListener(new ItemListener() {\n @Override\n public void itemStateChanged(ItemEvent ie) {\n textArea.setLineWrap(lineWrap.isSelected());\n }\n });\n frame.add(lineWrap, BorderLayout.SOUTH );\n frame.setLocationRelativeTo(null);\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );\n frame.setVisible(true);\n }\n });\n }\n}" } ]
How to create a list in SAPUI5?
I have gone through your code and it looks your list binding is incorrect. When you bind your data, your data should be in a JSON array format. Please find below the updated working code. var oModelData = [ {Animal: "Kangaroo", Zoo: "Sydney"}, {Animal: "Tiger", Zoo: "Melbourne"}, {Animal: "Lion", Zoo: "Alaska"} ]; var oItem = new sap.m.StandardListItem({ title : "{ Animal }", description : "{ Zoo }" }); var oList = new sap.m.List({ headerText:" Items", items: { path: "/", template: oItem } }); Hope it helps!
[ { "code": null, "e": 1251, "s": 1062, "text": "I have gone through your code and it looks your list binding is incorrect. When you bind your data, your data should be in a JSON array format. Please find below the updated working code." }, { "code": null, "e": 1600, "s": 1251, "text": "var oModelData =\n[\n {Animal: \"Kangaroo\", Zoo: \"Sydney\"},\n {Animal: \"Tiger\", Zoo: \"Melbourne\"},\n {Animal: \"Lion\", Zoo: \"Alaska\"}\n];\nvar oItem = new sap.m.StandardListItem({\n title : \"{ Animal }\",\n description : \"{ Zoo }\"\n});\nvar oList = new sap.m.List({\n headerText:\" Items\",\n items: {\n path: \"/\",\n template: oItem\n }\n});" }, { "code": null, "e": 1615, "s": 1600, "text": "Hope it helps!" } ]
How to Create Bar Chart using React Bootstrap ? - GeeksforGeeks
24 Jun, 2021 A bar plot or bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. The bar plots can be plotted horizontally or vertically. A bar chart describes the comparisons between the discrete categories. One of the axes of the plot represents the specific categories being compared, while the other axis represents the measured values corresponding to those categories. Creating React Application And Installing Module: Step 1: Create a React application using the following command.npx create-react-app foldername Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Step 3: After creating the ReactJS application, Install the required modules using the following command.npm install --save mdbreact react-chartjs-2 Step 3: After creating the ReactJS application, Install the required modules using the following command. npm install --save mdbreact react-chartjs-2 Step 4: Add Bootstrap CSS and fontawesome CSS to index.js.import '@fortawesome/fontawesome-free/css/all.min.css'; import 'bootstrap-css-only/css/bootstrap.min.css'; import 'mdbreact/dist/css/mdb.css'; Step 4: Add Bootstrap CSS and fontawesome CSS to index.js. import '@fortawesome/fontawesome-free/css/all.min.css'; import 'bootstrap-css-only/css/bootstrap.min.css'; import 'mdbreact/dist/css/mdb.css'; Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React from "react";import { MDBContainer } from "mdbreact";import { Bar } from "react-chartjs-2"; const App = () => { // Sample data const data = { labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], datasets: [ { label: "Hours Studied in Geeksforgeeks", data: [2, 5, 6, 7, 3, 3, 4], backgroundColor: "#02b844", borderWidth: 1, borderColor: "#000000", } ] } return ( <MDBContainer> <Bar data={data} style={{ maxHeight: '600px' }} /> </MDBContainer> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Picked React-Bootstrap Bootstrap ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? How to set active class to nav menu from bootstrap ? How to change font color of the active nav-item in Bootstrap ? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? Create a Responsive Navbar using ReactJS
[ { "code": null, "e": 25578, "s": 25550, "text": "\n24 Jun, 2021" }, { "code": null, "e": 26048, "s": 25578, "text": "A bar plot or bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. The bar plots can be plotted horizontally or vertically. A bar chart describes the comparisons between the discrete categories. One of the axes of the plot represents the specific categories being compared, while the other axis represents the measured values corresponding to those categories." }, { "code": null, "e": 26098, "s": 26048, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 26193, "s": 26098, "text": "Step 1: Create a React application using the following command.npx create-react-app foldername" }, { "code": null, "e": 26257, "s": 26193, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 26289, "s": 26257, "text": "npx create-react-app foldername" }, { "code": null, "e": 26403, "s": 26289, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername " }, { "code": null, "e": 26503, "s": 26403, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 26517, "s": 26503, "text": "cd foldername" }, { "code": null, "e": 26668, "s": 26519, "text": "Step 3: After creating the ReactJS application, Install the required modules using the following command.npm install --save mdbreact react-chartjs-2" }, { "code": null, "e": 26774, "s": 26668, "text": "Step 3: After creating the ReactJS application, Install the required modules using the following command." }, { "code": null, "e": 26818, "s": 26774, "text": "npm install --save mdbreact react-chartjs-2" }, { "code": null, "e": 27023, "s": 26818, "text": "Step 4: Add Bootstrap CSS and fontawesome CSS to index.js.import '@fortawesome/fontawesome-free/css/all.min.css'; \nimport 'bootstrap-css-only/css/bootstrap.min.css'; \nimport 'mdbreact/dist/css/mdb.css';" }, { "code": null, "e": 27082, "s": 27023, "text": "Step 4: Add Bootstrap CSS and fontawesome CSS to index.js." }, { "code": null, "e": 27229, "s": 27082, "text": "import '@fortawesome/fontawesome-free/css/all.min.css'; \nimport 'bootstrap-css-only/css/bootstrap.min.css'; \nimport 'mdbreact/dist/css/mdb.css';" }, { "code": null, "e": 27281, "s": 27229, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 27299, "s": 27281, "text": "Project Structure" }, { "code": null, "e": 27429, "s": 27299, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 27440, "s": 27429, "text": "Javascript" }, { "code": "import React from \"react\";import { MDBContainer } from \"mdbreact\";import { Bar } from \"react-chartjs-2\"; const App = () => { // Sample data const data = { labels: [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"], datasets: [ { label: \"Hours Studied in Geeksforgeeks\", data: [2, 5, 6, 7, 3, 3, 4], backgroundColor: \"#02b844\", borderWidth: 1, borderColor: \"#000000\", } ] } return ( <MDBContainer> <Bar data={data} style={{ maxHeight: '600px' }} /> </MDBContainer> );} export default App;", "e": 28049, "s": 27440, "text": null }, { "code": null, "e": 28162, "s": 28049, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 28172, "s": 28162, "text": "npm start" }, { "code": null, "e": 28271, "s": 28172, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 28278, "s": 28271, "text": "Picked" }, { "code": null, "e": 28294, "s": 28278, "text": "React-Bootstrap" }, { "code": null, "e": 28304, "s": 28294, "text": "Bootstrap" }, { "code": null, "e": 28312, "s": 28304, "text": "ReactJS" }, { "code": null, "e": 28329, "s": 28312, "text": "Web Technologies" }, { "code": null, "e": 28427, "s": 28329, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28436, "s": 28427, "text": "Comments" }, { "code": null, "e": 28449, "s": 28436, "text": "Old Comments" }, { "code": null, "e": 28490, "s": 28449, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 28553, "s": 28490, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 28586, "s": 28553, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 28639, "s": 28586, "text": "How to set active class to nav menu from bootstrap ?" }, { "code": null, "e": 28702, "s": 28639, "text": "How to change font color of the active nav-item in Bootstrap ?" }, { "code": null, "e": 28745, "s": 28702, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28790, "s": 28745, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 28855, "s": 28790, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 28923, "s": 28855, "text": "How to pass data from one component to other component in ReactJS ?" } ]
Print all shortest paths between given source and destination in an undirected graph - GeeksforGeeks
03 Feb, 2022 Given an undirected and unweighted graph and two nodes as source and destination, the task is to print all the paths of the shortest length between the given source and destination.Examples: Input: source = 0, destination = 5 Output: 0 -> 1 -> 3 -> 50 -> 2 -> 3 -> 50 -> 1 -> 4 -> 5 Explanation: All the above paths are of length 3, which is the shortest distance between 0 and 5.Input: source = 0, destination = 4 Output: 0 -> 1 -> 4 Approach: The is to do a Breadth First Traversal (BFS) for a graph. Below are the steps: Start BFS traversal from source vertex.While doing BFS, store the shortest distance to each of the other nodes and also maintain a parent vector for each of the nodes.Make the parent of source node as “-1”. For each node, it will store all the parents for which it has the shortest distance from the source node.Recover all the paths using parent array. At any instant, we will push one vertex in the path array and then call for all its parents.If we encounter “-1” in the above steps, then it means a path has been found and can be stored in the paths array. Start BFS traversal from source vertex. While doing BFS, store the shortest distance to each of the other nodes and also maintain a parent vector for each of the nodes. Make the parent of source node as “-1”. For each node, it will store all the parents for which it has the shortest distance from the source node. Recover all the paths using parent array. At any instant, we will push one vertex in the path array and then call for all its parents. If we encounter “-1” in the above steps, then it means a path has been found and can be stored in the paths array. Below is the implementation of the above approach: cpp14 Java Python3 C# // Cpp program for the above approach#include <bits/stdc++.h>using namespace std; // Function to form edge between// two vertices src and destvoid add_edge(vector<int> adj[], int src, int dest){ adj[src].push_back(dest); adj[dest].push_back(src);} // Function which finds all the paths// and stores it in paths arrayvoid find_paths(vector<vector<int> >& paths, vector<int>& path, vector<int> parent[], int n, int u){ // Base Case if (u == -1) { paths.push_back(path); return; } // Loop for all the parents // of the given vertex for (int par : parent[u]) { // Insert the current // vertex in path path.push_back(u); // Recursive call for its parent find_paths(paths, path, parent, n, par); // Remove the current vertex path.pop_back(); }} // Function which performs bfs// from the given source vertexvoid bfs(vector<int> adj[], vector<int> parent[], int n, int start){ // dist will contain shortest distance // from start to every other vertex vector<int> dist(n, INT_MAX); queue<int> q; // Insert source vertex in queue and make // its parent -1 and distance 0 q.push(start); parent[start] = { -1 }; dist[start] = 0; // Until Queue is empty while (!q.empty()) { int u = q.front(); q.pop(); for (int v : adj[u]) { if (dist[v] > dist[u] + 1) { // A shorter distance is found // So erase all the previous parents // and insert new parent u in parent[v] dist[v] = dist[u] + 1; q.push(v); parent[v].clear(); parent[v].push_back(u); } else if (dist[v] == dist[u] + 1) { // Another candidate parent for // shortes path found parent[v].push_back(u); } } }} // Function which prints all the paths// from start to endvoid print_paths(vector<int> adj[], int n, int start, int end){ vector<vector<int> > paths; vector<int> path; vector<int> parent[n]; // Function call to bfs bfs(adj, parent, n, start); // Function call to find_paths find_paths(paths, path, parent, n, end); for (auto v : paths) { // Since paths contain each // path in reverse order, // so reverse it reverse(v.begin(), v.end()); // Print node for the current path for (int u : v) cout << u << " "; cout << endl; }} // Driver Codeint main(){ // Number of vertices int n = 6; // array of vectors is used // to store the graph // in the form of an adjacency list vector<int> adj[n]; // Given Graph add_edge(adj, 0, 1); add_edge(adj, 0, 2); add_edge(adj, 1, 3); add_edge(adj, 1, 4); add_edge(adj, 2, 3); add_edge(adj, 3, 5); add_edge(adj, 4, 5); // Given source and destination int src = 0; int dest = n - 1; // Function Call print_paths(adj, n, src, dest); return 0;} /*package whatever //do not write package name here */ import java.io.*;import java.util.*; class GFG { // Function to form edge between // two vertices src and dest static void add_edge(ArrayList<ArrayList<Integer>> adj, int src, int dest){ adj.get(src).add(dest); adj.get(dest).add(src); } // Function which finds all the paths // and stores it in paths array static void find_paths(ArrayList<ArrayList<Integer>> paths, ArrayList<Integer> path, ArrayList<ArrayList<Integer>> parent, int n, int u) { // Base Case if (u == -1) { paths.add(new ArrayList<>(path)); return; } // Loop for all the parents // of the given vertex for (int par : parent.get(u)) { // Insert the current // vertex in path path.add(u); // Recursive call for its parent find_paths(paths, path, parent, n, par); // Remove the current vertex path.remove(path.size()-1); } } // Function which performs bfs // from the given source vertex static void bfs(ArrayList<ArrayList<Integer>> adj, ArrayList<ArrayList<Integer>> parent, int n, int start) { // dist will contain shortest distance // from start to every other vertex int[] dist = new int[n]; Arrays.fill(dist, Integer.MAX_VALUE); Queue<Integer> q = new LinkedList<>(); // Insert source vertex in queue and make // its parent -1 and distance 0 q.offer(start); parent.get(start).clear(); parent.get(start).add(-1); dist[start] = 0; // Until Queue is empty while (!q.isEmpty()) { int u = q.poll(); for (int v : adj.get(u)) { if (dist[v] > dist[u] + 1) { // A shorter distance is found // So erase all the previous parents // and insert new parent u in parent[v] dist[v] = dist[u] + 1; q.offer(v); parent.get(v).clear(); parent.get(v).add(u); } else if (dist[v] == dist[u] + 1) { // Another candidate parent for // shortes path found parent.get(v).add(u); } } } } // Function which prints all the paths // from start to end static void print_paths(ArrayList<ArrayList<Integer>> adj, int n, int start, int end){ ArrayList<ArrayList<Integer>> paths = new ArrayList<>(); ArrayList<Integer> path = new ArrayList<>(); ArrayList<ArrayList<Integer>> parent = new ArrayList<>(); for(int i = 0; i < n; i++){ parent.add(new ArrayList<>()); } // Function call to bfs bfs(adj, parent, n, start); // Function call to find_paths find_paths(paths, path, parent, n, end); for (ArrayList<Integer> v : paths) { // Since paths contain each // path in reverse order, // so reverse it Collections.reverse(v); // Print node for the current path for (int u : v) System.out.print(u + " "); System.out.println(); } } public static void main (String[] args) { // Number of vertices int n = 6; // array of vectors is used // to store the graph // in the form of an adjacency list ArrayList<ArrayList<Integer>> adj = new ArrayList<>(); for(int i = 0; i < n; i++){ adj.add(new ArrayList<>()); } // Given Graph add_edge(adj, 0, 1); add_edge(adj, 0, 2); add_edge(adj, 1, 3); add_edge(adj, 1, 4); add_edge(adj, 2, 3); add_edge(adj, 3, 5); add_edge(adj, 4, 5); // Given source and destination int src = 0; int dest = n - 1; // Function Call print_paths(adj, n, src, dest); }} // This code is contributed by ayush123ngp. # Python program for the above approach # Function to form edge between# two vertices src and destfrom typing import Listfrom sys import maxsizefrom collections import deque def add_edge(adj: List[List[int]], src: int, dest: int) -> None: adj[src].append(dest) adj[dest].append(src) # Function which finds all the paths# and stores it in paths arraydef find_paths(paths: List[List[int]], path: List[int], parent: List[List[int]], n: int, u: int) -> None: # Base Case if (u == -1): paths.append(path.copy()) return # Loop for all the parents # of the given vertex for par in parent[u]: # Insert the current # vertex in path path.append(u) # Recursive call for its parent find_paths(paths, path, parent, n, par) # Remove the current vertex path.pop() # Function which performs bfs# from the given source vertexdef bfs(adj: List[List[int]], parent: List[List[int]], n: int, start: int) -> None: # dist will contain shortest distance # from start to every other vertex dist = [maxsize for _ in range(n)] q = deque() # Insert source vertex in queue and make # its parent -1 and distance 0 q.append(start) parent[start] = [-1] dist[start] = 0 # Until Queue is empty while q: u = q[0] q.popleft() for v in adj[u]: if (dist[v] > dist[u] + 1): # A shorter distance is found # So erase all the previous parents # and insert new parent u in parent[v] dist[v] = dist[u] + 1 q.append(v) parent[v].clear() parent[v].append(u) elif (dist[v] == dist[u] + 1): # Another candidate parent for # shortes path found parent[v].append(u) # Function which prints all the paths# from start to enddef print_paths(adj: List[List[int]], n: int, start: int, end: int) -> None: paths = [] path = [] parent = [[] for _ in range(n)] # Function call to bfs bfs(adj, parent, n, start) # Function call to find_paths find_paths(paths, path, parent, n, end) for v in paths: # Since paths contain each # path in reverse order, # so reverse it v = reversed(v) # Print node for the current path for u in v: print(u, end = " ") print() # Driver Codeif __name__ == "__main__": # Number of vertices n = 6 # array of vectors is used # to store the graph # in the form of an adjacency list adj = [[] for _ in range(n)] # Given Graph add_edge(adj, 0, 1) add_edge(adj, 0, 2) add_edge(adj, 1, 3) add_edge(adj, 1, 4) add_edge(adj, 2, 3) add_edge(adj, 3, 5) add_edge(adj, 4, 5) # Given source and destination src = 0 dest = n - 1 # Function Call print_paths(adj, n, src, dest) # This code is contributed by sanjeev2552 /*package whatever //do not write package name here */using System;using System.Collections.Generic; public class GFG{ // Function to form edge between // two vertices src and dest static void add_edge(List<List<int>> adj, int src, int dest){ adj[src].Add(dest); adj[dest].Add(src); } // Function which finds all the paths // and stores it in paths array static void find_paths(List<List<int>> paths, List<int> path, List<List<int>> parent, int n, int u) { // Base Case if (u == -1) { paths.Add(new List<int>(path)); return; } // Loop for all the parents // of the given vertex foreach (int par in parent[u]) { // Insert the current // vertex in path path.Add(u); // Recursive call for its parent find_paths(paths, path, parent, n, par); // Remove the current vertex path.RemoveAt(path.Count-1); } } // Function which performs bfs // from the given source vertex static void bfs(List<List<int>> adj, List<List<int>> parent, int n, int start) { // dist will contain shortest distance // from start to every other vertex int[] dist = new int[n]; for(int i=0;i<n;i++) dist[i] = int.MaxValue; Queue<int> q = new Queue<int>(); // Insert source vertex in queue and make // its parent -1 and distance 0 q.Enqueue(start); parent[start].Clear(); parent[start].Add(-1); dist[start] = 0; // Until Queue is empty while (q.Count!=0) { int u = q.Dequeue(); foreach (int v in adj[u]) { if (dist[v] > dist[u] + 1) { // A shorter distance is found // So erase all the previous parents // and insert new parent u in parent[v] dist[v] = dist[u] + 1; q.Enqueue(v); parent[v].Clear(); parent[v].Add(u); } else if (dist[v] == dist[u] + 1) { // Another candidate parent for // shortes path found parent[v].Add(u); } } } } // Function which prints all the paths // from start to end static void print_paths(List<List<int>> adj, int n, int start, int end){ List<List<int>> paths = new List<List<int>>(); List<int> path = new List<int>(); List<List<int>> parent = new List<List<int>>(); for(int i = 0; i < n; i++){ parent.Add(new List<int>()); } // Function call to bfs bfs(adj, parent, n, start); // Function call to find_paths find_paths(paths, path, parent, n, end); foreach (List<int> v in paths) { // Since paths contain each // path in reverse order, // so reverse it v.Reverse(); // Print node for the current path foreach (int u in v) Console.Write(u + " "); Console.WriteLine(); } } public static void Main(String[] args) { // Number of vertices int n = 6; // array of vectors is used // to store the graph // in the form of an adjacency list List<List<int>> adj = new List<List<int>>(); for(int i = 0; i < n; i++){ adj.Add(new List<int>()); } // Given Graph add_edge(adj, 0, 1); add_edge(adj, 0, 2); add_edge(adj, 1, 3); add_edge(adj, 1, 4); add_edge(adj, 2, 3); add_edge(adj, 3, 5); add_edge(adj, 4, 5); // Given source and destination int src = 0; int dest = n - 1; // Function Call print_paths(adj, n, src, dest); }} // This code is contributed by shikhasingrajput 0 1 3 5 0 2 3 5 0 1 4 5 Time Complexity: O(V + E) where V is the number of vertices and E is the number of edges. Auxiliary Space: O(V) where V is the number of vertices. sanjeev2552 ayush123ngp gulshankumarar231 clintra shikhasingrajput BFS Data Structures Graph Traversals Algorithms Competitive Programming Data Structures Graph Data Structures Graph BFS Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Introduction to Algorithms Difference between Informed and Uninformed Search in AI How to write a Pseudo Code? Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Competitive Programming - A Complete Guide Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 24677, "s": 24649, "text": "\n03 Feb, 2022" }, { "code": null, "e": 24870, "s": 24677, "text": "Given an undirected and unweighted graph and two nodes as source and destination, the task is to print all the paths of the shortest length between the given source and destination.Examples: " }, { "code": null, "e": 24907, "s": 24870, "text": "Input: source = 0, destination = 5 " }, { "code": null, "e": 25098, "s": 24907, "text": "Output: 0 -> 1 -> 3 -> 50 -> 2 -> 3 -> 50 -> 1 -> 4 -> 5 Explanation: All the above paths are of length 3, which is the shortest distance between 0 and 5.Input: source = 0, destination = 4 " }, { "code": null, "e": 25120, "s": 25098, "text": "Output: 0 -> 1 -> 4 " }, { "code": null, "e": 25212, "s": 25122, "text": "Approach: The is to do a Breadth First Traversal (BFS) for a graph. Below are the steps: " }, { "code": null, "e": 25773, "s": 25212, "text": "Start BFS traversal from source vertex.While doing BFS, store the shortest distance to each of the other nodes and also maintain a parent vector for each of the nodes.Make the parent of source node as “-1”. For each node, it will store all the parents for which it has the shortest distance from the source node.Recover all the paths using parent array. At any instant, we will push one vertex in the path array and then call for all its parents.If we encounter “-1” in the above steps, then it means a path has been found and can be stored in the paths array." }, { "code": null, "e": 25813, "s": 25773, "text": "Start BFS traversal from source vertex." }, { "code": null, "e": 25942, "s": 25813, "text": "While doing BFS, store the shortest distance to each of the other nodes and also maintain a parent vector for each of the nodes." }, { "code": null, "e": 26088, "s": 25942, "text": "Make the parent of source node as “-1”. For each node, it will store all the parents for which it has the shortest distance from the source node." }, { "code": null, "e": 26223, "s": 26088, "text": "Recover all the paths using parent array. At any instant, we will push one vertex in the path array and then call for all its parents." }, { "code": null, "e": 26338, "s": 26223, "text": "If we encounter “-1” in the above steps, then it means a path has been found and can be stored in the paths array." }, { "code": null, "e": 26390, "s": 26338, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26396, "s": 26390, "text": "cpp14" }, { "code": null, "e": 26401, "s": 26396, "text": "Java" }, { "code": null, "e": 26409, "s": 26401, "text": "Python3" }, { "code": null, "e": 26412, "s": 26409, "text": "C#" }, { "code": "// Cpp program for the above approach#include <bits/stdc++.h>using namespace std; // Function to form edge between// two vertices src and destvoid add_edge(vector<int> adj[], int src, int dest){ adj[src].push_back(dest); adj[dest].push_back(src);} // Function which finds all the paths// and stores it in paths arrayvoid find_paths(vector<vector<int> >& paths, vector<int>& path, vector<int> parent[], int n, int u){ // Base Case if (u == -1) { paths.push_back(path); return; } // Loop for all the parents // of the given vertex for (int par : parent[u]) { // Insert the current // vertex in path path.push_back(u); // Recursive call for its parent find_paths(paths, path, parent, n, par); // Remove the current vertex path.pop_back(); }} // Function which performs bfs// from the given source vertexvoid bfs(vector<int> adj[], vector<int> parent[], int n, int start){ // dist will contain shortest distance // from start to every other vertex vector<int> dist(n, INT_MAX); queue<int> q; // Insert source vertex in queue and make // its parent -1 and distance 0 q.push(start); parent[start] = { -1 }; dist[start] = 0; // Until Queue is empty while (!q.empty()) { int u = q.front(); q.pop(); for (int v : adj[u]) { if (dist[v] > dist[u] + 1) { // A shorter distance is found // So erase all the previous parents // and insert new parent u in parent[v] dist[v] = dist[u] + 1; q.push(v); parent[v].clear(); parent[v].push_back(u); } else if (dist[v] == dist[u] + 1) { // Another candidate parent for // shortes path found parent[v].push_back(u); } } }} // Function which prints all the paths// from start to endvoid print_paths(vector<int> adj[], int n, int start, int end){ vector<vector<int> > paths; vector<int> path; vector<int> parent[n]; // Function call to bfs bfs(adj, parent, n, start); // Function call to find_paths find_paths(paths, path, parent, n, end); for (auto v : paths) { // Since paths contain each // path in reverse order, // so reverse it reverse(v.begin(), v.end()); // Print node for the current path for (int u : v) cout << u << \" \"; cout << endl; }} // Driver Codeint main(){ // Number of vertices int n = 6; // array of vectors is used // to store the graph // in the form of an adjacency list vector<int> adj[n]; // Given Graph add_edge(adj, 0, 1); add_edge(adj, 0, 2); add_edge(adj, 1, 3); add_edge(adj, 1, 4); add_edge(adj, 2, 3); add_edge(adj, 3, 5); add_edge(adj, 4, 5); // Given source and destination int src = 0; int dest = n - 1; // Function Call print_paths(adj, n, src, dest); return 0;}", "e": 29558, "s": 26412, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*;import java.util.*; class GFG { // Function to form edge between // two vertices src and dest static void add_edge(ArrayList<ArrayList<Integer>> adj, int src, int dest){ adj.get(src).add(dest); adj.get(dest).add(src); } // Function which finds all the paths // and stores it in paths array static void find_paths(ArrayList<ArrayList<Integer>> paths, ArrayList<Integer> path, ArrayList<ArrayList<Integer>> parent, int n, int u) { // Base Case if (u == -1) { paths.add(new ArrayList<>(path)); return; } // Loop for all the parents // of the given vertex for (int par : parent.get(u)) { // Insert the current // vertex in path path.add(u); // Recursive call for its parent find_paths(paths, path, parent, n, par); // Remove the current vertex path.remove(path.size()-1); } } // Function which performs bfs // from the given source vertex static void bfs(ArrayList<ArrayList<Integer>> adj, ArrayList<ArrayList<Integer>> parent, int n, int start) { // dist will contain shortest distance // from start to every other vertex int[] dist = new int[n]; Arrays.fill(dist, Integer.MAX_VALUE); Queue<Integer> q = new LinkedList<>(); // Insert source vertex in queue and make // its parent -1 and distance 0 q.offer(start); parent.get(start).clear(); parent.get(start).add(-1); dist[start] = 0; // Until Queue is empty while (!q.isEmpty()) { int u = q.poll(); for (int v : adj.get(u)) { if (dist[v] > dist[u] + 1) { // A shorter distance is found // So erase all the previous parents // and insert new parent u in parent[v] dist[v] = dist[u] + 1; q.offer(v); parent.get(v).clear(); parent.get(v).add(u); } else if (dist[v] == dist[u] + 1) { // Another candidate parent for // shortes path found parent.get(v).add(u); } } } } // Function which prints all the paths // from start to end static void print_paths(ArrayList<ArrayList<Integer>> adj, int n, int start, int end){ ArrayList<ArrayList<Integer>> paths = new ArrayList<>(); ArrayList<Integer> path = new ArrayList<>(); ArrayList<ArrayList<Integer>> parent = new ArrayList<>(); for(int i = 0; i < n; i++){ parent.add(new ArrayList<>()); } // Function call to bfs bfs(adj, parent, n, start); // Function call to find_paths find_paths(paths, path, parent, n, end); for (ArrayList<Integer> v : paths) { // Since paths contain each // path in reverse order, // so reverse it Collections.reverse(v); // Print node for the current path for (int u : v) System.out.print(u + \" \"); System.out.println(); } } public static void main (String[] args) { // Number of vertices int n = 6; // array of vectors is used // to store the graph // in the form of an adjacency list ArrayList<ArrayList<Integer>> adj = new ArrayList<>(); for(int i = 0; i < n; i++){ adj.add(new ArrayList<>()); } // Given Graph add_edge(adj, 0, 1); add_edge(adj, 0, 2); add_edge(adj, 1, 3); add_edge(adj, 1, 4); add_edge(adj, 2, 3); add_edge(adj, 3, 5); add_edge(adj, 4, 5); // Given source and destination int src = 0; int dest = n - 1; // Function Call print_paths(adj, n, src, dest); }} // This code is contributed by ayush123ngp.", "e": 33709, "s": 29558, "text": null }, { "code": "# Python program for the above approach # Function to form edge between# two vertices src and destfrom typing import Listfrom sys import maxsizefrom collections import deque def add_edge(adj: List[List[int]], src: int, dest: int) -> None: adj[src].append(dest) adj[dest].append(src) # Function which finds all the paths# and stores it in paths arraydef find_paths(paths: List[List[int]], path: List[int], parent: List[List[int]], n: int, u: int) -> None: # Base Case if (u == -1): paths.append(path.copy()) return # Loop for all the parents # of the given vertex for par in parent[u]: # Insert the current # vertex in path path.append(u) # Recursive call for its parent find_paths(paths, path, parent, n, par) # Remove the current vertex path.pop() # Function which performs bfs# from the given source vertexdef bfs(adj: List[List[int]], parent: List[List[int]], n: int, start: int) -> None: # dist will contain shortest distance # from start to every other vertex dist = [maxsize for _ in range(n)] q = deque() # Insert source vertex in queue and make # its parent -1 and distance 0 q.append(start) parent[start] = [-1] dist[start] = 0 # Until Queue is empty while q: u = q[0] q.popleft() for v in adj[u]: if (dist[v] > dist[u] + 1): # A shorter distance is found # So erase all the previous parents # and insert new parent u in parent[v] dist[v] = dist[u] + 1 q.append(v) parent[v].clear() parent[v].append(u) elif (dist[v] == dist[u] + 1): # Another candidate parent for # shortes path found parent[v].append(u) # Function which prints all the paths# from start to enddef print_paths(adj: List[List[int]], n: int, start: int, end: int) -> None: paths = [] path = [] parent = [[] for _ in range(n)] # Function call to bfs bfs(adj, parent, n, start) # Function call to find_paths find_paths(paths, path, parent, n, end) for v in paths: # Since paths contain each # path in reverse order, # so reverse it v = reversed(v) # Print node for the current path for u in v: print(u, end = \" \") print() # Driver Codeif __name__ == \"__main__\": # Number of vertices n = 6 # array of vectors is used # to store the graph # in the form of an adjacency list adj = [[] for _ in range(n)] # Given Graph add_edge(adj, 0, 1) add_edge(adj, 0, 2) add_edge(adj, 1, 3) add_edge(adj, 1, 4) add_edge(adj, 2, 3) add_edge(adj, 3, 5) add_edge(adj, 4, 5) # Given source and destination src = 0 dest = n - 1 # Function Call print_paths(adj, n, src, dest) # This code is contributed by sanjeev2552", "e": 36703, "s": 33709, "text": null }, { "code": "/*package whatever //do not write package name here */using System;using System.Collections.Generic; public class GFG{ // Function to form edge between // two vertices src and dest static void add_edge(List<List<int>> adj, int src, int dest){ adj[src].Add(dest); adj[dest].Add(src); } // Function which finds all the paths // and stores it in paths array static void find_paths(List<List<int>> paths, List<int> path, List<List<int>> parent, int n, int u) { // Base Case if (u == -1) { paths.Add(new List<int>(path)); return; } // Loop for all the parents // of the given vertex foreach (int par in parent[u]) { // Insert the current // vertex in path path.Add(u); // Recursive call for its parent find_paths(paths, path, parent, n, par); // Remove the current vertex path.RemoveAt(path.Count-1); } } // Function which performs bfs // from the given source vertex static void bfs(List<List<int>> adj, List<List<int>> parent, int n, int start) { // dist will contain shortest distance // from start to every other vertex int[] dist = new int[n]; for(int i=0;i<n;i++) dist[i] = int.MaxValue; Queue<int> q = new Queue<int>(); // Insert source vertex in queue and make // its parent -1 and distance 0 q.Enqueue(start); parent[start].Clear(); parent[start].Add(-1); dist[start] = 0; // Until Queue is empty while (q.Count!=0) { int u = q.Dequeue(); foreach (int v in adj[u]) { if (dist[v] > dist[u] + 1) { // A shorter distance is found // So erase all the previous parents // and insert new parent u in parent[v] dist[v] = dist[u] + 1; q.Enqueue(v); parent[v].Clear(); parent[v].Add(u); } else if (dist[v] == dist[u] + 1) { // Another candidate parent for // shortes path found parent[v].Add(u); } } } } // Function which prints all the paths // from start to end static void print_paths(List<List<int>> adj, int n, int start, int end){ List<List<int>> paths = new List<List<int>>(); List<int> path = new List<int>(); List<List<int>> parent = new List<List<int>>(); for(int i = 0; i < n; i++){ parent.Add(new List<int>()); } // Function call to bfs bfs(adj, parent, n, start); // Function call to find_paths find_paths(paths, path, parent, n, end); foreach (List<int> v in paths) { // Since paths contain each // path in reverse order, // so reverse it v.Reverse(); // Print node for the current path foreach (int u in v) Console.Write(u + \" \"); Console.WriteLine(); } } public static void Main(String[] args) { // Number of vertices int n = 6; // array of vectors is used // to store the graph // in the form of an adjacency list List<List<int>> adj = new List<List<int>>(); for(int i = 0; i < n; i++){ adj.Add(new List<int>()); } // Given Graph add_edge(adj, 0, 1); add_edge(adj, 0, 2); add_edge(adj, 1, 3); add_edge(adj, 1, 4); add_edge(adj, 2, 3); add_edge(adj, 3, 5); add_edge(adj, 4, 5); // Given source and destination int src = 0; int dest = n - 1; // Function Call print_paths(adj, n, src, dest); }} // This code is contributed by shikhasingrajput", "e": 40145, "s": 36703, "text": null }, { "code": null, "e": 40171, "s": 40145, "text": "0 1 3 5 \n0 2 3 5 \n0 1 4 5" }, { "code": null, "e": 40321, "s": 40173, "text": "Time Complexity: O(V + E) where V is the number of vertices and E is the number of edges. Auxiliary Space: O(V) where V is the number of vertices. " }, { "code": null, "e": 40333, "s": 40321, "text": "sanjeev2552" }, { "code": null, "e": 40345, "s": 40333, "text": "ayush123ngp" }, { "code": null, "e": 40363, "s": 40345, "text": "gulshankumarar231" }, { "code": null, "e": 40371, "s": 40363, "text": "clintra" }, { "code": null, "e": 40388, "s": 40371, "text": "shikhasingrajput" }, { "code": null, "e": 40392, "s": 40388, "text": "BFS" }, { "code": null, "e": 40408, "s": 40392, "text": "Data Structures" }, { "code": null, "e": 40425, "s": 40408, "text": "Graph Traversals" }, { "code": null, "e": 40436, "s": 40425, "text": "Algorithms" }, { "code": null, "e": 40460, "s": 40436, "text": "Competitive Programming" }, { "code": null, "e": 40476, "s": 40460, "text": "Data Structures" }, { "code": null, "e": 40482, "s": 40476, "text": "Graph" }, { "code": null, "e": 40498, "s": 40482, "text": "Data Structures" }, { "code": null, "e": 40504, "s": 40498, "text": "Graph" }, { "code": null, "e": 40508, "s": 40504, "text": "BFS" }, { "code": null, "e": 40519, "s": 40508, "text": "Algorithms" }, { "code": null, "e": 40617, "s": 40519, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40626, "s": 40617, "text": "Comments" }, { "code": null, "e": 40639, "s": 40626, "text": "Old Comments" }, { "code": null, "e": 40688, "s": 40639, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 40713, "s": 40688, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 40740, "s": 40713, "text": "Introduction to Algorithms" }, { "code": null, "e": 40796, "s": 40740, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 40824, "s": 40796, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 40867, "s": 40824, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 40908, "s": 40867, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 40951, "s": 40908, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 40978, "s": 40951, "text": "Modulo 10^9+7 (1000000007)" } ]
Python Pandas and SQLite. Using SQLite to store your Pandas... | by Alan Jones | Towards Data Science
The SQLite database is a built-in feature of Python and a very useful one, at that. It is not a complete implementation of SQL but it has all the features that you need for a personal database or even a backend for a data-driven web site. Using it with Pandas is simple and really useful. You can permanently store your dataframes in a table and read them directly into a new dataframe as you need them. But it isn’t just the storage aspect that is so useful. You can select and filter the data using simple SQL commands: this saves you having to process the dataframe itself. I’m going to demonstrate a few simple techniques using SQLite and Pandas using my favourite London weather data set. It’s derived from public domain data from the UK Met Office and you can download it from my Github account. All the code here was written in a Jupyter notebook but should run perfectly well as a standalone Python program, too. Let’s start by importing the libraries: import sqlite3 as sqlimport pandas as pdimport matplotlib.pyplot as plt Obviously, we need the SQLite and Pandas libraries and we’ll get matplotlib as well because we are going to plot some graphs. Now let’s get the data. There’s about 70 years worth of temperature, rainfall and sunshine data in a csv file. We download it like this: weather = pd.read_csv('https://github.com/alanjones2/dataviz/raw/master/londonweather.csv') And this is what it looks like. The data is recorded for each month of the year. The temperatures are in degrees Celsius, the rainfall is in millimetres and ‘Sun’ is the total number of hours sunshine for the month. Now we are going to save the dataframe in an SQLite database. First we open a connection to a new database (this will create the database if it doesn’t already exist) and then create a new table in that database called weather. conn = sql.connect('weather.db')weather.to_sql('weather', conn) We don’t need to run this code ever again unless the original data changes and, indeed, we shouldn’t, because SQLIte will not allow us to create a new table in the database if one of the same name already exists. Let’s assume that we have run the code above once and we have our database, weather, with the table, also called weather, in it. We could now start a new notebook or Python program to do the rest of this tutorial or simply comment out the code to download and create the database. So, we have a database with our weather data in it and now and we want to read it into a dataframe. Here is how we load the database table into a dataframe. First, we make a connection to the database in the same way as before. Then we use the sql_read method from Pandas to read in the data. But to do this we have to send a query to the database: SELECT * FROM weather This is just about the simplest SQL query you can make. It means select all columns from the table called weather and return that data. Here’s the code (the query is passed as a string). conn = sql.connect('weather.db')weather = pd.read_sql('SELECT * FROM weather', conn) That, of course, is just reproducing the original dataframe, so let’s use the power of SQL to load just a subset of the data. We’ll get the data for a couple of years, 50 years apart, and compare them to see if there was any clear difference. Let’s start by getting the data for the year 2010. We are going to create a new dataframe called y2010 using read_sql, as before, but with a slightly different query. We add a WHERE clause. This only selects the data where the condition following the keyword WHERE is true. So, in this case, we only get the rows of data where the value in the year column is ‘2010’. y2010 = pd.read_sql('SELECT * FROM weather WHERE Year == 2010', conn) You can see that the only data that has been returned is for the year 2010. Here’s a line plot for Tmax. Now let’s do that again but for 1960, 50 years earlier y1960 = pd.read_sql('SELECT * FROM weather WHERE Year == 1960', conn) And now let’s plot the Tmax for the two individual years. ax2010 = y2010.plot(y='Tmax')ax = y1960.plot(y='Tmax',color = 'red', ax=ax2010)ax.legend(['2010','1960']) Interesting, 2010 was both hotter and colder than 1960 it seems. Is the weather getting more extreme? We need to do a bit more analysis to come to that conclusion. Maybe we could start by finding the hottest years, say the ones where the temperature was over 25 degrees. We do this by using a WHERE clause with a condition, Tmax > 25, that is, select the rows where Tmax was more than 25 degrees But also since we are only interested in the max temperature, we will only select the columns that we are interested in. We do this by modifying the SELECT clause in the SQL query. Instead of selecting * (i.e. all columns), we list the columns that we want returned: Year, Month and Tmax. high = pd.read_sql('SELECT Year,Month,Tmax FROM weather WHERE Tmax > 25', conn) That’s in year order. Maybe it would be more interesting to have it in order of temperature. We can do that with SQL, too. We add the clause ORDER BY and give the column which should dictate the order. DESC means in descending order (omit that and you’ll get the default, ascending order). high = pd.read_sql('SELECT Year,Month,Tmax FROM weather WHERE Tmax > 25 ORDER BY Tmax DESC', conn) So, topping the chart is 2018 with 2006 not far behind. But 1983 and 1995 are in third and fourth place so there is no obvious pattern here that shows that temperatures are getting hotter over time. One thing we can see is that the hottest months are in the summer! (Who’d have thought it.) But to be sure let’s plot a histogram. high.plot.hist(y='Month', xticks=high['Month']) Yes, the hottest month tends to be July. So, if we are looking for a trend why don’t we take a look at the months of July throughout the decades and see how the temperature changes. Here’s another query: july = pd.read_sql('SELECT Year,Month,Tmax FROM weather WHERE month == 6', conn) This gives us a table of temperature for all years but only where the month is equal to 6, i.e. July. Now we’ll make a bar plot of the Tmax values over time. july.plot.bar(x='Year', y='Tmax', figsize=(20,5)); We could do a regression plot to see if there is any trend but frankly looking at this bar chart there is no obvious trend. So, with this extremely limited analysis of temperature data in London, we can’t come to any conclusion as to whether climate change is affecting Londoners (but from personal experience, I can tell that it’s feeling pretty warm there lately). But I hope that I’ve demonstrated that SQLite is a useful tool when used alongside Pandas and, if you haven’t done any SQL before, you can see how, even the tiny part of it that I’ve used here, might benefit your data analysis. As always, thanks for reading. If you would like to know when I publish new articles, please consider signing up for an email alert here. If you are not a Medium subscriber, how about signing up so you can read as many articles as you like for $5 a month. Sign up here and I’ll earn a small commision. You can find sample code for this and other articles on my Github page.
[ { "code": null, "e": 411, "s": 172, "text": "The SQLite database is a built-in feature of Python and a very useful one, at that. It is not a complete implementation of SQL but it has all the features that you need for a personal database or even a backend for a data-driven web site." }, { "code": null, "e": 576, "s": 411, "text": "Using it with Pandas is simple and really useful. You can permanently store your dataframes in a table and read them directly into a new dataframe as you need them." }, { "code": null, "e": 749, "s": 576, "text": "But it isn’t just the storage aspect that is so useful. You can select and filter the data using simple SQL commands: this saves you having to process the dataframe itself." }, { "code": null, "e": 974, "s": 749, "text": "I’m going to demonstrate a few simple techniques using SQLite and Pandas using my favourite London weather data set. It’s derived from public domain data from the UK Met Office and you can download it from my Github account." }, { "code": null, "e": 1093, "s": 974, "text": "All the code here was written in a Jupyter notebook but should run perfectly well as a standalone Python program, too." }, { "code": null, "e": 1133, "s": 1093, "text": "Let’s start by importing the libraries:" }, { "code": null, "e": 1205, "s": 1133, "text": "import sqlite3 as sqlimport pandas as pdimport matplotlib.pyplot as plt" }, { "code": null, "e": 1331, "s": 1205, "text": "Obviously, we need the SQLite and Pandas libraries and we’ll get matplotlib as well because we are going to plot some graphs." }, { "code": null, "e": 1468, "s": 1331, "text": "Now let’s get the data. There’s about 70 years worth of temperature, rainfall and sunshine data in a csv file. We download it like this:" }, { "code": null, "e": 1560, "s": 1468, "text": "weather = pd.read_csv('https://github.com/alanjones2/dataviz/raw/master/londonweather.csv')" }, { "code": null, "e": 1776, "s": 1560, "text": "And this is what it looks like. The data is recorded for each month of the year. The temperatures are in degrees Celsius, the rainfall is in millimetres and ‘Sun’ is the total number of hours sunshine for the month." }, { "code": null, "e": 1838, "s": 1776, "text": "Now we are going to save the dataframe in an SQLite database." }, { "code": null, "e": 2004, "s": 1838, "text": "First we open a connection to a new database (this will create the database if it doesn’t already exist) and then create a new table in that database called weather." }, { "code": null, "e": 2068, "s": 2004, "text": "conn = sql.connect('weather.db')weather.to_sql('weather', conn)" }, { "code": null, "e": 2281, "s": 2068, "text": "We don’t need to run this code ever again unless the original data changes and, indeed, we shouldn’t, because SQLIte will not allow us to create a new table in the database if one of the same name already exists." }, { "code": null, "e": 2562, "s": 2281, "text": "Let’s assume that we have run the code above once and we have our database, weather, with the table, also called weather, in it. We could now start a new notebook or Python program to do the rest of this tutorial or simply comment out the code to download and create the database." }, { "code": null, "e": 2719, "s": 2562, "text": "So, we have a database with our weather data in it and now and we want to read it into a dataframe. Here is how we load the database table into a dataframe." }, { "code": null, "e": 2886, "s": 2719, "text": "First, we make a connection to the database in the same way as before. Then we use the sql_read method from Pandas to read in the data. But to do this we have to send" }, { "code": null, "e": 2911, "s": 2886, "text": "a query to the database:" }, { "code": null, "e": 2933, "s": 2911, "text": "SELECT * FROM weather" }, { "code": null, "e": 3120, "s": 2933, "text": "This is just about the simplest SQL query you can make. It means select all columns from the table called weather and return that data. Here’s the code (the query is passed as a string)." }, { "code": null, "e": 3205, "s": 3120, "text": "conn = sql.connect('weather.db')weather = pd.read_sql('SELECT * FROM weather', conn)" }, { "code": null, "e": 3331, "s": 3205, "text": "That, of course, is just reproducing the original dataframe, so let’s use the power of SQL to load just a subset of the data." }, { "code": null, "e": 3448, "s": 3331, "text": "We’ll get the data for a couple of years, 50 years apart, and compare them to see if there was any clear difference." }, { "code": null, "e": 3499, "s": 3448, "text": "Let’s start by getting the data for the year 2010." }, { "code": null, "e": 3815, "s": 3499, "text": "We are going to create a new dataframe called y2010 using read_sql, as before, but with a slightly different query. We add a WHERE clause. This only selects the data where the condition following the keyword WHERE is true. So, in this case, we only get the rows of data where the value in the year column is ‘2010’." }, { "code": null, "e": 3885, "s": 3815, "text": "y2010 = pd.read_sql('SELECT * FROM weather WHERE Year == 2010', conn)" }, { "code": null, "e": 3961, "s": 3885, "text": "You can see that the only data that has been returned is for the year 2010." }, { "code": null, "e": 3990, "s": 3961, "text": "Here’s a line plot for Tmax." }, { "code": null, "e": 4045, "s": 3990, "text": "Now let’s do that again but for 1960, 50 years earlier" }, { "code": null, "e": 4115, "s": 4045, "text": "y1960 = pd.read_sql('SELECT * FROM weather WHERE Year == 1960', conn)" }, { "code": null, "e": 4173, "s": 4115, "text": "And now let’s plot the Tmax for the two individual years." }, { "code": null, "e": 4279, "s": 4173, "text": "ax2010 = y2010.plot(y='Tmax')ax = y1960.plot(y='Tmax',color = 'red', ax=ax2010)ax.legend(['2010','1960'])" }, { "code": null, "e": 4443, "s": 4279, "text": "Interesting, 2010 was both hotter and colder than 1960 it seems. Is the weather getting more extreme? We need to do a bit more analysis to come to that conclusion." }, { "code": null, "e": 4550, "s": 4443, "text": "Maybe we could start by finding the hottest years, say the ones where the temperature was over 25 degrees." }, { "code": null, "e": 4675, "s": 4550, "text": "We do this by using a WHERE clause with a condition, Tmax > 25, that is, select the rows where Tmax was more than 25 degrees" }, { "code": null, "e": 4856, "s": 4675, "text": "But also since we are only interested in the max temperature, we will only select the columns that we are interested in. We do this by modifying the SELECT clause in the SQL query." }, { "code": null, "e": 4964, "s": 4856, "text": "Instead of selecting * (i.e. all columns), we list the columns that we want returned: Year, Month and Tmax." }, { "code": null, "e": 5044, "s": 4964, "text": "high = pd.read_sql('SELECT Year,Month,Tmax FROM weather WHERE Tmax > 25', conn)" }, { "code": null, "e": 5137, "s": 5044, "text": "That’s in year order. Maybe it would be more interesting to have it in order of temperature." }, { "code": null, "e": 5334, "s": 5137, "text": "We can do that with SQL, too. We add the clause ORDER BY and give the column which should dictate the order. DESC means in descending order (omit that and you’ll get the default, ascending order)." }, { "code": null, "e": 5433, "s": 5334, "text": "high = pd.read_sql('SELECT Year,Month,Tmax FROM weather WHERE Tmax > 25 ORDER BY Tmax DESC', conn)" }, { "code": null, "e": 5632, "s": 5433, "text": "So, topping the chart is 2018 with 2006 not far behind. But 1983 and 1995 are in third and fourth place so there is no obvious pattern here that shows that temperatures are getting hotter over time." }, { "code": null, "e": 5763, "s": 5632, "text": "One thing we can see is that the hottest months are in the summer! (Who’d have thought it.) But to be sure let’s plot a histogram." }, { "code": null, "e": 5811, "s": 5763, "text": "high.plot.hist(y='Month', xticks=high['Month'])" }, { "code": null, "e": 5993, "s": 5811, "text": "Yes, the hottest month tends to be July. So, if we are looking for a trend why don’t we take a look at the months of July throughout the decades and see how the temperature changes." }, { "code": null, "e": 6015, "s": 5993, "text": "Here’s another query:" }, { "code": null, "e": 6096, "s": 6015, "text": "july = pd.read_sql('SELECT Year,Month,Tmax FROM weather WHERE month == 6', conn)" }, { "code": null, "e": 6198, "s": 6096, "text": "This gives us a table of temperature for all years but only where the month is equal to 6, i.e. July." }, { "code": null, "e": 6254, "s": 6198, "text": "Now we’ll make a bar plot of the Tmax values over time." }, { "code": null, "e": 6305, "s": 6254, "text": "july.plot.bar(x='Year', y='Tmax', figsize=(20,5));" }, { "code": null, "e": 6429, "s": 6305, "text": "We could do a regression plot to see if there is any trend but frankly looking at this bar chart there is no obvious trend." }, { "code": null, "e": 6672, "s": 6429, "text": "So, with this extremely limited analysis of temperature data in London, we can’t come to any conclusion as to whether climate change is affecting Londoners (but from personal experience, I can tell that it’s feeling pretty warm there lately)." }, { "code": null, "e": 6900, "s": 6672, "text": "But I hope that I’ve demonstrated that SQLite is a useful tool when used alongside Pandas and, if you haven’t done any SQL before, you can see how, even the tiny part of it that I’ve used here, might benefit your data analysis." }, { "code": null, "e": 7038, "s": 6900, "text": "As always, thanks for reading. If you would like to know when I publish new articles, please consider signing up for an email alert here." }, { "code": null, "e": 7202, "s": 7038, "text": "If you are not a Medium subscriber, how about signing up so you can read as many articles as you like for $5 a month. Sign up here and I’ll earn a small commision." } ]
Stop Using “Print” and Start Using “Logging” | by Naser Tamimi | Towards Data Science
Logging is a popular solution for tracking events in a code or debugging. Many of us (Python programmers and data scientists) have this bad habit of using print() to debug and track events in our codes. Why using print() for logging and debugging is not a good practice? The print() statement fails if your code does not have access to the console.To define basic logging needs, several lines of code are needed.Including additional logging information is not easy.The print() statement only displays messages on the console. Recording logging data inside a file or sending it over the internet needs additional works. The print() statement fails if your code does not have access to the console. To define basic logging needs, several lines of code are needed. Including additional logging information is not easy. The print() statement only displays messages on the console. Recording logging data inside a file or sending it over the internet needs additional works. A better way to track your code events and do debugging is using the “Logging” library (a Python standard library). The logging library provides you five tools to accomplish the logging tasks. Debug (logging.debug()): Providing information to diagnosing problems.Info (logging.info()): Tracking the normal operation of a program.Warning (logging.warning()): Although the code is still working as expected, something unexpected happened.Error (logging.error()): The code was unable to run some parts.Critical (logging.critical()): The code cannot run. Debug (logging.debug()): Providing information to diagnosing problems. Info (logging.info()): Tracking the normal operation of a program. Warning (logging.warning()): Although the code is still working as expected, something unexpected happened. Error (logging.error()): The code was unable to run some parts. Critical (logging.critical()): The code cannot run. Before using these tools, let’s understand different levels of logging in Python. There are six logging levels in Python. The highest level is CRITICAL. If you set your logging level to CRITICAL, only logging messages of the CRITICAL level will be shown. To set your logging level to CRITICAL, you can use logging.basicConfig(). logging.basicConfig(level=logging.CRITICAL) or logging.basicConfig(level=50) As you see the level argument in logging.basicConfig() takes an integer number (i.e. 50 or constant logging.CRITICAL) and sets the logging level. The levels of logging from the lowest to the highest are NOTSET=0, DEBUG=10, INFO=20, WARNING=30, ERROR=40, and CRITICAL=50. The default level is WARNING (i.e. 30) which means, the logging module only displays/logs events with warning, error, or critical severity. Again, remember that you can set your logging level using logging.basicConfig(). Here is an example code to display different levels of logging messages. Note, I set the logging level to the lowest (logging.NOTSET) to displays all messages. The output is something like this: DEBUG:root:Here you have some information for debugging.INFO:root:Everything is normal. Relax!WARNING:root:Something unexpected but not important happend.ERROR:root:Something unexpected and important happened.CRITICAL:root:OMG!!! A critical error happend and the code cannot run! Let’s change the logging level to WARNING. In this case, the output is: WARNING:root:Something unexpected but not important happend.ERROR:root:Something unexpected and important happened.CRITICAL:root:OMG!!! A critical error happend and the code cannot run! As you see, because I set my logging level to WARNING (using logging.WARNING constant value), only messages with a severity of WARNING or higher are shown. OK, it is good to use logging tools to display appropriate messages, but can I format my messages better that help me do betting logging of my code? The answer is YES. Let’s read the next section to format our logging messages better (and in a more meaningful way). One of the advantages of using the logging module to track our codes is the ability to format the messages based on our needs. For example, in my code, I would like to log the date and time with appropriate messages. Here is an example. And here is the output. 2021-02-14 23:02:34,089 | DEBUG: Here you have some information for debugging.2021-02-14 23:02:34,089 | INFO: Everything is normal. Relax!2021-02-14 23:02:34,090 | WARNING: Something unexpected but not important happend.2021-02-14 23:02:34,092 | ERROR: Something unexpected and important happened.2021-02-14 23:02:34,092 | CRITICAL: OMG!!! A critical error happend and the code cannot run! As you see, to format my logging messages, I need to pass a string to logging.basicConfig(). The formatting string can include a mix of characters and attributes. For example, in my formatting string, the attributes are asctime (%(asctime)s), levelname (%(levelname)s), and message (%(message)s). The first attribute, asctime, shows the logging date and time. The levelname attribute outputs the logging level (DEBUG, INFO, etc.). Finally, we have the message attribute, which is simply the message we want to show. There are twenty useful attributes that you can use based on your needs. Here is a list of them (source). So far, we have sent the logging messages to the console for printing. Sometimes, we need to record the logging messages and information in a file for our record. It is super easy to switch from printing to console to writing on a file. We only need to pass a file name to logging.basicConfig()to start logging into a file. Here is an example. For basic logging, what is mentioned so far is more than enough. Although if you like to do more complicated logging tasks, you might need to do it more professionally. In a more advanced approach, we use a logger object to track events in the code. You need to set up your logger object in 4 simple steps. STEP 1) Instantiate a logger object STEP 2) Setting the lowest severity for logging STEP 3) Set a destination (also called a handler) for your logs (e.g., console, file, or HTTP.) STEP 4) Setting format of messages for the handler The following code show all 4 steps. The output of this code, as you correctly guessed, is: 2021-02-15 15:04:03,364 | ERROR: Something unexpected and important happened.2021-02-15 15:04:03,364 | CRITICAL: OMG!!! A critical error happend and the code cannot run! As the final example, let’s go a little more advanced and imagine you need two loggers. One logger prints only important messages (ERROR and higher) to the console. The second logger records more logging message (INFO and higher) in a log file with more details (for example, it includes execution line number or %(lineno)d). Here is the code to handle this scenario. If you run this code, you will see the following output in the console. 2021-02-15 15:04:25,349 | ERROR: Something unexpected and important happened.2021-02-15 15:04:25,350 | CRITICAL: OMG!!! A critical error happend and the code cannot run! But in your log file (sample.log), you will see more detailed information. 2021-02-15 15:04:25,340 | INFO | 22: Everything is normal. Relax!2021-02-15 15:04:25,349 | WARNING | 23: Something unexpected but not important happend.2021-02-15 15:04:25,349 | ERROR | 24: Something unexpected and important happened.2021-02-15 15:04:25,350 | CRITICAL | 25: OMG!!! A critical error happend and the code cannot run! As you see in the code, I simply created a logger object. Then, I started creating my console handler and setting its level and format. I added my console handler to the logger object. I repeated a similar process for the file handler. Finally, I started logging, and the logger managed both handlers properly. Very easy and straightforward. Now, you can imagine how hard it would be to replicate the same functionality with the print() statement. There are many advanced tools and settings that you can use in your logger. As an example, you can send your logging results to a central URL address over HTTP by using the HTTP logging handler (logging.HTTPHandler()). Or you can use filters to ask the logger to react differently to different events. Python logging library provides many tools and settings for handling different logging tasks. You can learn more about all available tools and settings in the Logging Cookbook. Using print() for logging and debugging is a bad practice. In Python, we have specialized tools inside the “Logging” library to handle different logging and debugging tasks. In this article, I showed you how to use the basic logging tools and settings.
[ { "code": null, "e": 375, "s": 172, "text": "Logging is a popular solution for tracking events in a code or debugging. Many of us (Python programmers and data scientists) have this bad habit of using print() to debug and track events in our codes." }, { "code": null, "e": 443, "s": 375, "text": "Why using print() for logging and debugging is not a good practice?" }, { "code": null, "e": 791, "s": 443, "text": "The print() statement fails if your code does not have access to the console.To define basic logging needs, several lines of code are needed.Including additional logging information is not easy.The print() statement only displays messages on the console. Recording logging data inside a file or sending it over the internet needs additional works." }, { "code": null, "e": 869, "s": 791, "text": "The print() statement fails if your code does not have access to the console." }, { "code": null, "e": 934, "s": 869, "text": "To define basic logging needs, several lines of code are needed." }, { "code": null, "e": 988, "s": 934, "text": "Including additional logging information is not easy." }, { "code": null, "e": 1142, "s": 988, "text": "The print() statement only displays messages on the console. Recording logging data inside a file or sending it over the internet needs additional works." }, { "code": null, "e": 1258, "s": 1142, "text": "A better way to track your code events and do debugging is using the “Logging” library (a Python standard library)." }, { "code": null, "e": 1335, "s": 1258, "text": "The logging library provides you five tools to accomplish the logging tasks." }, { "code": null, "e": 1693, "s": 1335, "text": "Debug (logging.debug()): Providing information to diagnosing problems.Info (logging.info()): Tracking the normal operation of a program.Warning (logging.warning()): Although the code is still working as expected, something unexpected happened.Error (logging.error()): The code was unable to run some parts.Critical (logging.critical()): The code cannot run." }, { "code": null, "e": 1764, "s": 1693, "text": "Debug (logging.debug()): Providing information to diagnosing problems." }, { "code": null, "e": 1831, "s": 1764, "text": "Info (logging.info()): Tracking the normal operation of a program." }, { "code": null, "e": 1939, "s": 1831, "text": "Warning (logging.warning()): Although the code is still working as expected, something unexpected happened." }, { "code": null, "e": 2003, "s": 1939, "text": "Error (logging.error()): The code was unable to run some parts." }, { "code": null, "e": 2055, "s": 2003, "text": "Critical (logging.critical()): The code cannot run." }, { "code": null, "e": 2137, "s": 2055, "text": "Before using these tools, let’s understand different levels of logging in Python." }, { "code": null, "e": 2384, "s": 2137, "text": "There are six logging levels in Python. The highest level is CRITICAL. If you set your logging level to CRITICAL, only logging messages of the CRITICAL level will be shown. To set your logging level to CRITICAL, you can use logging.basicConfig()." }, { "code": null, "e": 2428, "s": 2384, "text": "logging.basicConfig(level=logging.CRITICAL)" }, { "code": null, "e": 2431, "s": 2428, "text": "or" }, { "code": null, "e": 2461, "s": 2431, "text": "logging.basicConfig(level=50)" }, { "code": null, "e": 2732, "s": 2461, "text": "As you see the level argument in logging.basicConfig() takes an integer number (i.e. 50 or constant logging.CRITICAL) and sets the logging level. The levels of logging from the lowest to the highest are NOTSET=0, DEBUG=10, INFO=20, WARNING=30, ERROR=40, and CRITICAL=50." }, { "code": null, "e": 2953, "s": 2732, "text": "The default level is WARNING (i.e. 30) which means, the logging module only displays/logs events with warning, error, or critical severity. Again, remember that you can set your logging level using logging.basicConfig()." }, { "code": null, "e": 3113, "s": 2953, "text": "Here is an example code to display different levels of logging messages. Note, I set the logging level to the lowest (logging.NOTSET) to displays all messages." }, { "code": null, "e": 3148, "s": 3113, "text": "The output is something like this:" }, { "code": null, "e": 3428, "s": 3148, "text": "DEBUG:root:Here you have some information for debugging.INFO:root:Everything is normal. Relax!WARNING:root:Something unexpected but not important happend.ERROR:root:Something unexpected and important happened.CRITICAL:root:OMG!!! A critical error happend and the code cannot run!" }, { "code": null, "e": 3471, "s": 3428, "text": "Let’s change the logging level to WARNING." }, { "code": null, "e": 3500, "s": 3471, "text": "In this case, the output is:" }, { "code": null, "e": 3686, "s": 3500, "text": "WARNING:root:Something unexpected but not important happend.ERROR:root:Something unexpected and important happened.CRITICAL:root:OMG!!! A critical error happend and the code cannot run!" }, { "code": null, "e": 3842, "s": 3686, "text": "As you see, because I set my logging level to WARNING (using logging.WARNING constant value), only messages with a severity of WARNING or higher are shown." }, { "code": null, "e": 4108, "s": 3842, "text": "OK, it is good to use logging tools to display appropriate messages, but can I format my messages better that help me do betting logging of my code? The answer is YES. Let’s read the next section to format our logging messages better (and in a more meaningful way)." }, { "code": null, "e": 4345, "s": 4108, "text": "One of the advantages of using the logging module to track our codes is the ability to format the messages based on our needs. For example, in my code, I would like to log the date and time with appropriate messages. Here is an example." }, { "code": null, "e": 4369, "s": 4345, "text": "And here is the output." }, { "code": null, "e": 4759, "s": 4369, "text": "2021-02-14 23:02:34,089 | DEBUG: Here you have some information for debugging.2021-02-14 23:02:34,089 | INFO: Everything is normal. Relax!2021-02-14 23:02:34,090 | WARNING: Something unexpected but not important happend.2021-02-14 23:02:34,092 | ERROR: Something unexpected and important happened.2021-02-14 23:02:34,092 | CRITICAL: OMG!!! A critical error happend and the code cannot run!" }, { "code": null, "e": 5381, "s": 4759, "text": "As you see, to format my logging messages, I need to pass a string to logging.basicConfig(). The formatting string can include a mix of characters and attributes. For example, in my formatting string, the attributes are asctime (%(asctime)s), levelname (%(levelname)s), and message (%(message)s). The first attribute, asctime, shows the logging date and time. The levelname attribute outputs the logging level (DEBUG, INFO, etc.). Finally, we have the message attribute, which is simply the message we want to show. There are twenty useful attributes that you can use based on your needs. Here is a list of them (source)." }, { "code": null, "e": 5725, "s": 5381, "text": "So far, we have sent the logging messages to the console for printing. Sometimes, we need to record the logging messages and information in a file for our record. It is super easy to switch from printing to console to writing on a file. We only need to pass a file name to logging.basicConfig()to start logging into a file. Here is an example." }, { "code": null, "e": 5894, "s": 5725, "text": "For basic logging, what is mentioned so far is more than enough. Although if you like to do more complicated logging tasks, you might need to do it more professionally." }, { "code": null, "e": 6032, "s": 5894, "text": "In a more advanced approach, we use a logger object to track events in the code. You need to set up your logger object in 4 simple steps." }, { "code": null, "e": 6068, "s": 6032, "text": "STEP 1) Instantiate a logger object" }, { "code": null, "e": 6116, "s": 6068, "text": "STEP 2) Setting the lowest severity for logging" }, { "code": null, "e": 6212, "s": 6116, "text": "STEP 3) Set a destination (also called a handler) for your logs (e.g., console, file, or HTTP.)" }, { "code": null, "e": 6263, "s": 6212, "text": "STEP 4) Setting format of messages for the handler" }, { "code": null, "e": 6300, "s": 6263, "text": "The following code show all 4 steps." }, { "code": null, "e": 6355, "s": 6300, "text": "The output of this code, as you correctly guessed, is:" }, { "code": null, "e": 6525, "s": 6355, "text": "2021-02-15 15:04:03,364 | ERROR: Something unexpected and important happened.2021-02-15 15:04:03,364 | CRITICAL: OMG!!! A critical error happend and the code cannot run!" }, { "code": null, "e": 6893, "s": 6525, "text": "As the final example, let’s go a little more advanced and imagine you need two loggers. One logger prints only important messages (ERROR and higher) to the console. The second logger records more logging message (INFO and higher) in a log file with more details (for example, it includes execution line number or %(lineno)d). Here is the code to handle this scenario." }, { "code": null, "e": 6965, "s": 6893, "text": "If you run this code, you will see the following output in the console." }, { "code": null, "e": 7135, "s": 6965, "text": "2021-02-15 15:04:25,349 | ERROR: Something unexpected and important happened.2021-02-15 15:04:25,350 | CRITICAL: OMG!!! A critical error happend and the code cannot run!" }, { "code": null, "e": 7210, "s": 7135, "text": "But in your log file (sample.log), you will see more detailed information." }, { "code": null, "e": 7542, "s": 7210, "text": "2021-02-15 15:04:25,340 | INFO | 22: Everything is normal. Relax!2021-02-15 15:04:25,349 | WARNING | 23: Something unexpected but not important happend.2021-02-15 15:04:25,349 | ERROR | 24: Something unexpected and important happened.2021-02-15 15:04:25,350 | CRITICAL | 25: OMG!!! A critical error happend and the code cannot run!" }, { "code": null, "e": 7990, "s": 7542, "text": "As you see in the code, I simply created a logger object. Then, I started creating my console handler and setting its level and format. I added my console handler to the logger object. I repeated a similar process for the file handler. Finally, I started logging, and the logger managed both handlers properly. Very easy and straightforward. Now, you can imagine how hard it would be to replicate the same functionality with the print() statement." }, { "code": null, "e": 8292, "s": 7990, "text": "There are many advanced tools and settings that you can use in your logger. As an example, you can send your logging results to a central URL address over HTTP by using the HTTP logging handler (logging.HTTPHandler()). Or you can use filters to ask the logger to react differently to different events." }, { "code": null, "e": 8469, "s": 8292, "text": "Python logging library provides many tools and settings for handling different logging tasks. You can learn more about all available tools and settings in the Logging Cookbook." } ]
Loading Multiple Well Log LAS Files Using Python | by Andy McDonald | Towards Data Science
Log ASCII Standard (LAS) files are a common Oil & Gas industry format for storing and transferring well log data. The data contained within is used to analyze and understand the subsurface, as well as identify potential hydrocarbon reserves. In my previous article: Loading and Displaying Well Log Data, I covered how to load a single LAS file using the LASIO library. In this article, I expand upon that by showing how to load multiple las files from a subfolder into a single pandas dataframe. Doing this allows us to work with data from multiple wells and visualize the data quickly using matplotlib. It also allows us to prepare the data in a single format that is suitable for running through Machine Learning algorithms. This article forms part of my Python & Petrophysics series. Details of the full series can be found here. You can also find my Jupyter Notebooks and datasets on my GitHub repository at the following link. github.com To follow along with this article, the Jupyter Notebook can be found at the link above and the data file for this article can be found in the Data subfolder of the Python & Petrophysics repository. The data used for this article originates from the publicly accessible Netherlands NLOG Dutch Oil and Gas Portal. The first step is to bring in the libraries we will be working with. We will be using five libraries: pandas, matplotlib, seaborn, os, and lasio. Pandas, os and lasio will be used to load and store our data, whereas matplotlib and seaborn will allow us to visualize the contents of the wells. Next we are going setup an empty list which will hold all of our las file names. Secondly, in this example we have our files stored within a sub folder called Data/15-LASFiles/. This will change depending on where your files are stored. We can now use the os.listdir method and pass in the file path. When we run this code, we will be able to see a list of all the files in the data folder. From this code, we get a list of the contents of the folder. ['L05B03_comp.las', 'L0507_comp.las', 'L0506_comp.las', 'L0509_comp.las', 'WLC_PETRO_COMPUTED_1_INF_1.ASC'] As you can see above, we have returned 4 LAS files and 1 ASC file. As we are only interested in the LAS files we need to loop through each file and check if the extension is .las. Also, to catch any cases where the extension is capitalized (.LAS instead of .las), we need to call upon .lower() to convert the file extension string to lowercase characters. Once we have identified if the file ends with .las, we can then add the path (‘Data/15-LASFiles/’) to the file name. This is required for lasio to pick up the files correctly. If we only passed the file name, the reader would be looking in the same directory as the script or notebook, and would fail as a result. When we call the las_file_list we can see the full path for each of the 4 LAS files. ['Data/15-LASFiles/L05B03_comp.las', 'Data/15-LASFiles/L0507_comp.las', 'Data/15-LASFiles/L0506_comp.las', 'Data/15-LASFiles/L0509_comp.las'] There are a number of different ways to concatenate and / or append data to dataframes. In this article we will use a simple method of create a list of dataframes, which we will concatenate together. First, we will create an empty list using df_list=[]. Then secondly, we will loop through the las_file_list, read the file and convert it to a dataframe. It is useful for us to to know where the data originated. If we didn’t retain this information, we would end up with a dataframe full of data with no information about it’s origins. To do this, we can create a new column and assign the well name value: lasdf['WELL']=las.well.WELL.value. This will make it easy to work with the data later on. Additionally, as lasio sets the dataframe index to the depth value from the file, we can create an additional column called DEPTH. We will now create a working dataframe containing all of the data from the LAS files by concatenating the list objects. When we call upon the working dataframe, we can see that we have our data from multiple wells in the same dataframe. We can also confirm that we have all the wells loaded by checking for the unique values within the well column: Which returns an array of the unique well names: array(['L05-B-03', 'L05-07', 'L05-06', 'L05-B-01'], dtype=object) If our LAS files contain different curve mnemonics, which is often the case, new columns will be created for each new mnemonic that isn’t already in the dataframe. Now that we have our data loaded into a pandas dataframe object, we can create some simple and quick multi-plots to gain insight into our data. We will do this using crossplot/scatterplots, a boxplot and a Kernel Density Estimate (KDE) plot. To start this, we first need to group our dataframe by the well name using the following: Crossplots (also known as scatterplots) are used to plot one variable against another. For this example we will use a neutron porosity vs bulk density crossplot, which is a very common plot used in petrophysics. Using a similar piece of code that was previously mentioned on my Exploratory Data Analysis With Well Log Data article, we can loop through each of the groups in the dataframe and generate a crossplot (scatter plot) of neutron porosity (NPHI) vs bulk density (RHOB). This generates the following image with 4 subplots: Next up, we will display a boxplot of the gamma ray cuvre from all wells. The box plot will show us the extent of the data (minimum to maximum), the quartiles, and the median value of the data. This can be achieved using a single line of code in the seaborn library. In the arguments we can pass in the workingdf dataframe for data, and the WELL column for the hue. The latter of which will split the data up into individual boxes, each with it’s own unique color. Finally, we can view the distribution of the values of a curve in the dataframe by using a Kernel Density Estimate plot, which is similar to a histogram. Again, this example shows another way to apply the groupby function. We can tidy up the plot by calling up matplotlib functions to set the x and y limits. In this article we have covered how to load multiple LAS files by searching a directory for all files with a .las extension and concatenate them into a single pandas dataframe. Once we have this data in a dataframe, we can easily call upon matplotlib and seaborn to make quick and easy to understand visualizations of the data. Thanks for reading! If you have found this article useful, please feel free to check out my other articles looking at various aspects of Python and well log data. You can also find my code used in this article and others at GitHub. If you want to get in touch you can find me on LinkedIn or at my website. Interested in learning more about python and well log data or petrophysics? Follow me on Medium.
[ { "code": null, "e": 541, "s": 172, "text": "Log ASCII Standard (LAS) files are a common Oil & Gas industry format for storing and transferring well log data. The data contained within is used to analyze and understand the subsurface, as well as identify potential hydrocarbon reserves. In my previous article: Loading and Displaying Well Log Data, I covered how to load a single LAS file using the LASIO library." }, { "code": null, "e": 899, "s": 541, "text": "In this article, I expand upon that by showing how to load multiple las files from a subfolder into a single pandas dataframe. Doing this allows us to work with data from multiple wells and visualize the data quickly using matplotlib. It also allows us to prepare the data in a single format that is suitable for running through Machine Learning algorithms." }, { "code": null, "e": 1104, "s": 899, "text": "This article forms part of my Python & Petrophysics series. Details of the full series can be found here. You can also find my Jupyter Notebooks and datasets on my GitHub repository at the following link." }, { "code": null, "e": 1115, "s": 1104, "text": "github.com" }, { "code": null, "e": 1313, "s": 1115, "text": "To follow along with this article, the Jupyter Notebook can be found at the link above and the data file for this article can be found in the Data subfolder of the Python & Petrophysics repository." }, { "code": null, "e": 1427, "s": 1313, "text": "The data used for this article originates from the publicly accessible Netherlands NLOG Dutch Oil and Gas Portal." }, { "code": null, "e": 1573, "s": 1427, "text": "The first step is to bring in the libraries we will be working with. We will be using five libraries: pandas, matplotlib, seaborn, os, and lasio." }, { "code": null, "e": 1720, "s": 1573, "text": "Pandas, os and lasio will be used to load and store our data, whereas matplotlib and seaborn will allow us to visualize the contents of the wells." }, { "code": null, "e": 1801, "s": 1720, "text": "Next we are going setup an empty list which will hold all of our las file names." }, { "code": null, "e": 1957, "s": 1801, "text": "Secondly, in this example we have our files stored within a sub folder called Data/15-LASFiles/. This will change depending on where your files are stored." }, { "code": null, "e": 2111, "s": 1957, "text": "We can now use the os.listdir method and pass in the file path. When we run this code, we will be able to see a list of all the files in the data folder." }, { "code": null, "e": 2172, "s": 2111, "text": "From this code, we get a list of the contents of the folder." }, { "code": null, "e": 2280, "s": 2172, "text": "['L05B03_comp.las', 'L0507_comp.las', 'L0506_comp.las', 'L0509_comp.las', 'WLC_PETRO_COMPUTED_1_INF_1.ASC']" }, { "code": null, "e": 2951, "s": 2280, "text": "As you can see above, we have returned 4 LAS files and 1 ASC file. As we are only interested in the LAS files we need to loop through each file and check if the extension is .las. Also, to catch any cases where the extension is capitalized (.LAS instead of .las), we need to call upon .lower() to convert the file extension string to lowercase characters. Once we have identified if the file ends with .las, we can then add the path (‘Data/15-LASFiles/’) to the file name. This is required for lasio to pick up the files correctly. If we only passed the file name, the reader would be looking in the same directory as the script or notebook, and would fail as a result." }, { "code": null, "e": 3036, "s": 2951, "text": "When we call the las_file_list we can see the full path for each of the 4 LAS files." }, { "code": null, "e": 3178, "s": 3036, "text": "['Data/15-LASFiles/L05B03_comp.las', 'Data/15-LASFiles/L0507_comp.las', 'Data/15-LASFiles/L0506_comp.las', 'Data/15-LASFiles/L0509_comp.las']" }, { "code": null, "e": 3378, "s": 3178, "text": "There are a number of different ways to concatenate and / or append data to dataframes. In this article we will use a simple method of create a list of dataframes, which we will concatenate together." }, { "code": null, "e": 3532, "s": 3378, "text": "First, we will create an empty list using df_list=[]. Then secondly, we will loop through the las_file_list, read the file and convert it to a dataframe." }, { "code": null, "e": 3875, "s": 3532, "text": "It is useful for us to to know where the data originated. If we didn’t retain this information, we would end up with a dataframe full of data with no information about it’s origins. To do this, we can create a new column and assign the well name value: lasdf['WELL']=las.well.WELL.value. This will make it easy to work with the data later on." }, { "code": null, "e": 4006, "s": 3875, "text": "Additionally, as lasio sets the dataframe index to the depth value from the file, we can create an additional column called DEPTH." }, { "code": null, "e": 4126, "s": 4006, "text": "We will now create a working dataframe containing all of the data from the LAS files by concatenating the list objects." }, { "code": null, "e": 4243, "s": 4126, "text": "When we call upon the working dataframe, we can see that we have our data from multiple wells in the same dataframe." }, { "code": null, "e": 4355, "s": 4243, "text": "We can also confirm that we have all the wells loaded by checking for the unique values within the well column:" }, { "code": null, "e": 4404, "s": 4355, "text": "Which returns an array of the unique well names:" }, { "code": null, "e": 4470, "s": 4404, "text": "array(['L05-B-03', 'L05-07', 'L05-06', 'L05-B-01'], dtype=object)" }, { "code": null, "e": 4634, "s": 4470, "text": "If our LAS files contain different curve mnemonics, which is often the case, new columns will be created for each new mnemonic that isn’t already in the dataframe." }, { "code": null, "e": 4876, "s": 4634, "text": "Now that we have our data loaded into a pandas dataframe object, we can create some simple and quick multi-plots to gain insight into our data. We will do this using crossplot/scatterplots, a boxplot and a Kernel Density Estimate (KDE) plot." }, { "code": null, "e": 4966, "s": 4876, "text": "To start this, we first need to group our dataframe by the well name using the following:" }, { "code": null, "e": 5178, "s": 4966, "text": "Crossplots (also known as scatterplots) are used to plot one variable against another. For this example we will use a neutron porosity vs bulk density crossplot, which is a very common plot used in petrophysics." }, { "code": null, "e": 5445, "s": 5178, "text": "Using a similar piece of code that was previously mentioned on my Exploratory Data Analysis With Well Log Data article, we can loop through each of the groups in the dataframe and generate a crossplot (scatter plot) of neutron porosity (NPHI) vs bulk density (RHOB)." }, { "code": null, "e": 5497, "s": 5445, "text": "This generates the following image with 4 subplots:" }, { "code": null, "e": 5691, "s": 5497, "text": "Next up, we will display a boxplot of the gamma ray cuvre from all wells. The box plot will show us the extent of the data (minimum to maximum), the quartiles, and the median value of the data." }, { "code": null, "e": 5962, "s": 5691, "text": "This can be achieved using a single line of code in the seaborn library. In the arguments we can pass in the workingdf dataframe for data, and the WELL column for the hue. The latter of which will split the data up into individual boxes, each with it’s own unique color." }, { "code": null, "e": 6116, "s": 5962, "text": "Finally, we can view the distribution of the values of a curve in the dataframe by using a Kernel Density Estimate plot, which is similar to a histogram." }, { "code": null, "e": 6271, "s": 6116, "text": "Again, this example shows another way to apply the groupby function. We can tidy up the plot by calling up matplotlib functions to set the x and y limits." }, { "code": null, "e": 6599, "s": 6271, "text": "In this article we have covered how to load multiple LAS files by searching a directory for all files with a .las extension and concatenate them into a single pandas dataframe. Once we have this data in a dataframe, we can easily call upon matplotlib and seaborn to make quick and easy to understand visualizations of the data." }, { "code": null, "e": 6619, "s": 6599, "text": "Thanks for reading!" }, { "code": null, "e": 6831, "s": 6619, "text": "If you have found this article useful, please feel free to check out my other articles looking at various aspects of Python and well log data. You can also find my code used in this article and others at GitHub." }, { "code": null, "e": 6905, "s": 6831, "text": "If you want to get in touch you can find me on LinkedIn or at my website." } ]