title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
The 5 Sampling Algorithms every Data Scientist need to know | by Rahul Agarwal | Towards Data Science
Data Science is the study of algorithms. I grapple through with many algorithms on a day to day basis so I thought of listing some of the most common and most used algorithms one will end up using in this new DS Algorithm series. This post is about some of the most common sampling techniques one can use while working with data. Say you want to select a subset of a population in which each member of the subset has an equal probability of being chosen. Below we select 100 sample points from a dataset. sample_df = df.sample(100) Assume that we need to estimate the average number of votes for each candidate in an election. Assume that the country has 3 towns: Town A has 1 million factory workers, Town B has 2 million workers, and Town C has 3 million retirees. We can choose to get a random sample of size 60 over the entire population but there is some chance that the random sample turns out to be not well balanced across these towns and hence is biased causing a significant error in estimation. Instead, if we choose to take a random sample of 10, 20 and 30 from Town A, B and C respectively then we can produce a smaller error in estimation for the same total size of the sample. You can do something like this pretty easily with Python: from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=0.25) I love this problem statement: Say you have a stream of items of large and unknown length that we can only iterate over once. Create an algorithm that randomly chooses an item from this stream such that each item is equally likely to be selected. How can we do that? Let us assume we have to sample 5 objects out of an infinite stream such that each element has an equal probability of getting selected. import randomdef generator(max): number = 1 while number < max: number += 1 yield number# Create as stream generatorstream = generator(10000)# Doing Reservoir Sampling from the streamk=5reservoir = []for i, element in enumerate(stream): if i+1<= k: reservoir.append(element) else: probability = k/(i+1) if random.random() < probability: # Select item in stream and remove one of the k items already selected reservoir[random.choice(range(0,k))] = elementprint(reservoir)------------------------------------[1369, 4108, 9986, 828, 5589] It can be mathematically proved that in the sample each element has the same probability of getting selected from the stream. How? It always helps to think of a smaller problem when it comes to mathematics. So, let us think of a stream of only 3 items and we have to keep 2 of them. We see the first item, we hold it in the list as our reservoir has space. We see the second item, we hold it in the list as our reservoir has space. We see the third item. Here is where things get interesting. We choose the third item to be in the list with probability 2/3. Let us now see the probability of first item getting selected: The probability of removing the first item is the probability of element 3 getting selected multiplied by the probability of Element 1 getting randomly chosen as the replacement candidate from the 2 elements in the reservoir. That probability is: 2/3*1/2 = 1/3 Thus the probability of 1 getting selected is: 1–1/3 = 2/3 We can have the exact same argument for the Second Element and we can extend it for many elements. Thus each item has the same probability of getting selected: 2/3 or in general k/n It is too often that we encounter an imbalanced dataset. A widely adopted technique for dealing with highly imbalanced datasets is called resampling. It consists of removing samples from the majority class (under-sampling) and/or adding more examples from the minority class (over-sampling). Let us first create some example imbalanced data. from sklearn.datasets import make_classificationX, y = make_classification( n_classes=2, class_sep=1.5, weights=[0.9, 0.1], n_informative=3, n_redundant=1, flip_y=0, n_features=20, n_clusters_per_class=1, n_samples=100, random_state=10)X = pd.DataFrame(X)X['target'] = y We can now do random oversampling and undersampling using: num_0 = len(X[X['target']==0])num_1 = len(X[X['target']==1])print(num_0,num_1)# random undersampleundersampled_data = pd.concat([ X[X['target']==0].sample(num_1) , X[X['target']==1] ])print(len(undersampled_data))# random oversampleoversampled_data = pd.concat([ X[X['target']==0] , X[X['target']==1].sample(num_0, replace=True) ])print(len(oversampled_data))------------------------------------------------------------OUTPUT:90 1020180 imbalanced-learn(imblearn) is a Python Package to tackle the curse of imbalanced datasets. It provides a variety of methods to undersample and oversample. One of such methods it provides is called Tomek Links. Tomek links are pairs of examples of opposite classes in close vicinity. In this algorithm, we end up removing the majority element from the Tomek link which provides a better decision boundary for a classifier. from imblearn.under_sampling import TomekLinkstl = TomekLinks(return_indices=True, ratio='majority')X_tl, y_tl, id_tl = tl.fit_sample(X, y) In SMOTE (Synthetic Minority Oversampling Technique) we synthesize elements for the minority class, in the vicinity of already existing elements. from imblearn.over_sampling import SMOTEsmote = SMOTE(ratio='minority')X_sm, y_sm = smote.fit_sample(X, y) There are a variety of other methods in the imblearn package for both undersampling(Cluster Centroids, NearMiss, etc.) and oversampling(ADASYN and bSMOTE) that you can check out. Algorithms are the lifeblood of data science. Sampling is an important topic in data science and we really don’t talk about it as much as we should. A good sampling strategy sometimes could pull the whole project forward. A bad sampling strategy could give us incorrect results. So one should be careful while selecting a sampling strategy. So use sampling, be it at work or at bars. If you want to learn more about Data Science, I would like to call out this excellent course by Andrew Ng. This was the one that got me started. Do check it out. Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz.
[ { "code": null, "e": 213, "s": 172, "text": "Data Science is the study of algorithms." }, { "code": null, "e": 402, "s": 213, "text": "I grapple through with many algorithms on a day to day basis so I thought of listing some of the most common and most used algorithms one will end up using in this new DS Algorithm series." }, { "code": null, "e": 502, "s": 402, "text": "This post is about some of the most common sampling techniques one can use while working with data." }, { "code": null, "e": 627, "s": 502, "text": "Say you want to select a subset of a population in which each member of the subset has an equal probability of being chosen." }, { "code": null, "e": 677, "s": 627, "text": "Below we select 100 sample points from a dataset." }, { "code": null, "e": 704, "s": 677, "text": "sample_df = df.sample(100)" }, { "code": null, "e": 836, "s": 704, "text": "Assume that we need to estimate the average number of votes for each candidate in an election. Assume that the country has 3 towns:" }, { "code": null, "e": 874, "s": 836, "text": "Town A has 1 million factory workers," }, { "code": null, "e": 908, "s": 874, "text": "Town B has 2 million workers, and" }, { "code": null, "e": 939, "s": 908, "text": "Town C has 3 million retirees." }, { "code": null, "e": 1178, "s": 939, "text": "We can choose to get a random sample of size 60 over the entire population but there is some chance that the random sample turns out to be not well balanced across these towns and hence is biased causing a significant error in estimation." }, { "code": null, "e": 1364, "s": 1178, "text": "Instead, if we choose to take a random sample of 10, 20 and 30 from Town A, B and C respectively then we can produce a smaller error in estimation for the same total size of the sample." }, { "code": null, "e": 1422, "s": 1364, "text": "You can do something like this pretty easily with Python:" }, { "code": null, "e": 1663, "s": 1422, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=0.25)" }, { "code": null, "e": 1694, "s": 1663, "text": "I love this problem statement:" }, { "code": null, "e": 1789, "s": 1694, "text": "Say you have a stream of items of large and unknown length that we can only iterate over once." }, { "code": null, "e": 1910, "s": 1789, "text": "Create an algorithm that randomly chooses an item from this stream such that each item is equally likely to be selected." }, { "code": null, "e": 1930, "s": 1910, "text": "How can we do that?" }, { "code": null, "e": 2067, "s": 1930, "text": "Let us assume we have to sample 5 objects out of an infinite stream such that each element has an equal probability of getting selected." }, { "code": null, "e": 2673, "s": 2067, "text": "import randomdef generator(max): number = 1 while number < max: number += 1 yield number# Create as stream generatorstream = generator(10000)# Doing Reservoir Sampling from the streamk=5reservoir = []for i, element in enumerate(stream): if i+1<= k: reservoir.append(element) else: probability = k/(i+1) if random.random() < probability: # Select item in stream and remove one of the k items already selected reservoir[random.choice(range(0,k))] = elementprint(reservoir)------------------------------------[1369, 4108, 9986, 828, 5589]" }, { "code": null, "e": 2799, "s": 2673, "text": "It can be mathematically proved that in the sample each element has the same probability of getting selected from the stream." }, { "code": null, "e": 2804, "s": 2799, "text": "How?" }, { "code": null, "e": 2880, "s": 2804, "text": "It always helps to think of a smaller problem when it comes to mathematics." }, { "code": null, "e": 2956, "s": 2880, "text": "So, let us think of a stream of only 3 items and we have to keep 2 of them." }, { "code": null, "e": 3105, "s": 2956, "text": "We see the first item, we hold it in the list as our reservoir has space. We see the second item, we hold it in the list as our reservoir has space." }, { "code": null, "e": 3231, "s": 3105, "text": "We see the third item. Here is where things get interesting. We choose the third item to be in the list with probability 2/3." }, { "code": null, "e": 3294, "s": 3231, "text": "Let us now see the probability of first item getting selected:" }, { "code": null, "e": 3541, "s": 3294, "text": "The probability of removing the first item is the probability of element 3 getting selected multiplied by the probability of Element 1 getting randomly chosen as the replacement candidate from the 2 elements in the reservoir. That probability is:" }, { "code": null, "e": 3555, "s": 3541, "text": "2/3*1/2 = 1/3" }, { "code": null, "e": 3602, "s": 3555, "text": "Thus the probability of 1 getting selected is:" }, { "code": null, "e": 3614, "s": 3602, "text": "1–1/3 = 2/3" }, { "code": null, "e": 3713, "s": 3614, "text": "We can have the exact same argument for the Second Element and we can extend it for many elements." }, { "code": null, "e": 3796, "s": 3713, "text": "Thus each item has the same probability of getting selected: 2/3 or in general k/n" }, { "code": null, "e": 3853, "s": 3796, "text": "It is too often that we encounter an imbalanced dataset." }, { "code": null, "e": 4088, "s": 3853, "text": "A widely adopted technique for dealing with highly imbalanced datasets is called resampling. It consists of removing samples from the majority class (under-sampling) and/or adding more examples from the minority class (over-sampling)." }, { "code": null, "e": 4138, "s": 4088, "text": "Let us first create some example imbalanced data." }, { "code": null, "e": 4421, "s": 4138, "text": "from sklearn.datasets import make_classificationX, y = make_classification( n_classes=2, class_sep=1.5, weights=[0.9, 0.1], n_informative=3, n_redundant=1, flip_y=0, n_features=20, n_clusters_per_class=1, n_samples=100, random_state=10)X = pd.DataFrame(X)X['target'] = y" }, { "code": null, "e": 4480, "s": 4421, "text": "We can now do random oversampling and undersampling using:" }, { "code": null, "e": 4917, "s": 4480, "text": "num_0 = len(X[X['target']==0])num_1 = len(X[X['target']==1])print(num_0,num_1)# random undersampleundersampled_data = pd.concat([ X[X['target']==0].sample(num_1) , X[X['target']==1] ])print(len(undersampled_data))# random oversampleoversampled_data = pd.concat([ X[X['target']==0] , X[X['target']==1].sample(num_0, replace=True) ])print(len(oversampled_data))------------------------------------------------------------OUTPUT:90 1020180" }, { "code": null, "e": 5008, "s": 4917, "text": "imbalanced-learn(imblearn) is a Python Package to tackle the curse of imbalanced datasets." }, { "code": null, "e": 5072, "s": 5008, "text": "It provides a variety of methods to undersample and oversample." }, { "code": null, "e": 5200, "s": 5072, "text": "One of such methods it provides is called Tomek Links. Tomek links are pairs of examples of opposite classes in close vicinity." }, { "code": null, "e": 5339, "s": 5200, "text": "In this algorithm, we end up removing the majority element from the Tomek link which provides a better decision boundary for a classifier." }, { "code": null, "e": 5479, "s": 5339, "text": "from imblearn.under_sampling import TomekLinkstl = TomekLinks(return_indices=True, ratio='majority')X_tl, y_tl, id_tl = tl.fit_sample(X, y)" }, { "code": null, "e": 5625, "s": 5479, "text": "In SMOTE (Synthetic Minority Oversampling Technique) we synthesize elements for the minority class, in the vicinity of already existing elements." }, { "code": null, "e": 5732, "s": 5625, "text": "from imblearn.over_sampling import SMOTEsmote = SMOTE(ratio='minority')X_sm, y_sm = smote.fit_sample(X, y)" }, { "code": null, "e": 5911, "s": 5732, "text": "There are a variety of other methods in the imblearn package for both undersampling(Cluster Centroids, NearMiss, etc.) and oversampling(ADASYN and bSMOTE) that you can check out." }, { "code": null, "e": 5957, "s": 5911, "text": "Algorithms are the lifeblood of data science." }, { "code": null, "e": 6060, "s": 5957, "text": "Sampling is an important topic in data science and we really don’t talk about it as much as we should." }, { "code": null, "e": 6252, "s": 6060, "text": "A good sampling strategy sometimes could pull the whole project forward. A bad sampling strategy could give us incorrect results. So one should be careful while selecting a sampling strategy." }, { "code": null, "e": 6295, "s": 6252, "text": "So use sampling, be it at work or at bars." }, { "code": null, "e": 6457, "s": 6295, "text": "If you want to learn more about Data Science, I would like to call out this excellent course by Andrew Ng. This was the one that got me started. Do check it out." } ]
How to add custom view in alert dialog?
This example demonstrate about How to add custom view in alert dialog Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent"> <TextView android:id = "@+id/click" android:layout_width = "wrap_content" android:textSize = "30sp" android:layout_height = "wrap_content" android:text = "Click"/> </LinearLayout> In the above code, we have taken text view. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.annotation.TargetApi; import android.content.DialogInterface; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { TextView text; @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text = findViewById(R.id.click); text.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showAlertDialog(); } }); } private void showAlertDialog() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); final View customLayout = getLayoutInflater().inflate(R.layout.custom, null); alertDialog.setView(customLayout); alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // send data from the AlertDialog to the Activity EditText editText = customLayout.findViewById(R.id.editText); Toast.makeText(MainActivity.this,editText.getText().toString(),Toast.LENGTH_LONG).show(); } }); AlertDialog alert = alertDialog.create(); alert.setCanceledOnTouchOutside(false); alert.show(); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Now click on textview to open Alert Dialog. Now click on ok button to show toast as shown below –
[ { "code": null, "e": 1132, "s": 1062, "text": "This example demonstrate about How to add custom view in alert dialog" }, { "code": null, "e": 1261, "s": 1132, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1326, "s": 1261, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1771, "s": 1326, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\">\n <TextView\n android:id = \"@+id/click\"\n android:layout_width = \"wrap_content\"\n android:textSize = \"30sp\"\n android:layout_height = \"wrap_content\"\n android:text = \"Click\"/>\n</LinearLayout>" }, { "code": null, "e": 1815, "s": 1771, "text": "In the above code, we have taken text view." }, { "code": null, "e": 1872, "s": 1815, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3552, "s": 1872, "text": "package com.example.myapplication;\nimport android.annotation.TargetApi;\nimport android.content.DialogInterface;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.v7.app.AlertDialog;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.EditText;\nimport android.widget.Switch;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\npublic class MainActivity extends AppCompatActivity {\n TextView text;\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n text = findViewById(R.id.click);\n text.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n showAlertDialog();\n }\n });\n }\n private void showAlertDialog() {\n AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);\n final View customLayout = getLayoutInflater().inflate(R.layout.custom, null);\n alertDialog.setView(customLayout);\n alertDialog.setPositiveButton(\"OK\", new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n // send data from the AlertDialog to the Activity\n EditText editText = customLayout.findViewById(R.id.editText);\n Toast.makeText(MainActivity.this,editText.getText().toString(),Toast.LENGTH_LONG).show();\n }\n });\n AlertDialog alert = alertDialog.create();\n alert.setCanceledOnTouchOutside(false);\n alert.show();\n }\n}" }, { "code": null, "e": 3899, "s": 3552, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 3943, "s": 3899, "text": "Now click on textview to open Alert Dialog." }, { "code": null, "e": 3997, "s": 3943, "text": "Now click on ok button to show toast as shown below –" } ]
TPOT: Automated Machine Learning in Python | by Dario Radečić | Towards Data Science
Everybody and their mother wants to get into machine learning. That’s great, but the field got automated over the years — to a degree. Nowadays, you don’t have to be a machine learning engineer to produce good quality models. How? That’s where libraries like TPOT come into play. If you’re more of a video person, or just want to reinforce your knowledge, feel free to watch our video on the topic. Source code is included: Let’s face the facts — machine learning isn’t as interesting as hyped by the media. You can do amazing things with it, don’t get me wrong. I’m only talking about the actual machine learning process. You know, the process of finding an optimal algorithm and its hyperparameters. It’s good this part is getting (or already got) automated — since we as engineers can focus on more interesting things. The ideal reader is someone familiar with the Python programming language and with the general flow of a machine learning project. You don’t have to be an expert, or even work in the field, but it’s expected that you’re familiar with the most common algorithms and how to use them. The article is structured as follows: What’s TPOT?Genetic programming introductionDataset loading and preparationTPOT in action What’s TPOT? Genetic programming introduction Dataset loading and preparation TPOT in action So without much ado, let’s get started! TPOT, or Tree-based Pipeline Optimization Tool is a Python library for automated machine learning. Here’s the official definition: Consider TPOT your Data Science Assistant. TPOT is a Python Automated Machine Learning tool that optimizes machine learning pipelines using genetic programming.[1] In a way, TPOT is your data science assistant. It automates the “boring” stuff and leaves you with the tasks of data gathering and preparation. I know this segment isn’t fun to some of you — but it’s 80% of the job. With libraries like TPOT, that percentage might only get higher. Plus, data gathering and preparation can’t be fully automated, for obvious reasons. Another sentence over at the official documentation drives the point home: TPOT will automate the most tedious part of machine learning by intelligently exploring thousands of possible pipelines to find the best one for your data.[1] Let’s take a quick look at your average machine learning pipeline to see where TPOT fits in: As you can see, the library automates every tedious portion of the process. But how? By using something known as “genetic programming”. Let’s explore this term in the next section. The official website summarizes the concept pretty well: Genetic Programming (GP) is a type of Evolutionary Algorithm (EA), a subset of machine learning. EAs are used to discover solutions to problems humans do not know how to solve, directly. Free of human preconceptions or biases, the adaptive nature of EAs can generate solutions that are comparable to, and often better than the best human efforts. Inspired by biological evolution and its fundamental mechanisms, GP software systems implement an algorithm that uses random mutation, crossover, a fitness function, and multiple generations of evolution to resolve a user-defined task. GP can be used to discover a functional relationship between features in data (symbolic regression), to group data into categories (classification), and to assist in the design of electrical circuits, antennae, and quantum algorithms. GP is applied to software engineering through code synthesis, genetic improvement, automatic bug-fixing, and in developing game-playing strategies, ... and more.[2] With the right data and the right amounts of data, we can use machine learning to learn any function. Still, knowing which algorithm to use can be daunting — there’s just too many of them. And we still haven't touched the idea of hyperparameter tweaking. That’s where genetic programming really shines, because it is inspired by the Darwinian process of Natural Selection, and they are used to generate solutions to optimization in computer science. Genetic algorithms have 3 properties: Selection: where you have a population of a possible solution and a fitness function — then at every iteration each fit is evaluatedCrossover — selecting the fittest solution and performing crossover to create a new populationMutation — taking their children and mutating them with some random modification until you get the fittest or best solution Selection: where you have a population of a possible solution and a fitness function — then at every iteration each fit is evaluated Crossover — selecting the fittest solution and performing crossover to create a new population Mutation — taking their children and mutating them with some random modification until you get the fittest or best solution Sounds like a lot, definitely, but TPOT doesn’t require us to be experts in genetic programming. Knowing the concepts is, as always, beneficial. Okay, we have the theory part covered thus far. We’ll gather and prepare some data in the next section. I love using the Titanic dataset for most of my examples. The dataset isn’t too basic, as it requires some preparation, but it isn’t too complex in the means that the preparation process would take too long. You could definitely spend more time preparing this dataset then I did, but this will be enough for our needs. Imports-wise, we’ll need 3 things for now: Pandas, StandardScaler and train test split: import pandas as pdfrom sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import train_test_split Next, we can load in the dataset and display the first couple of rows: data = pd.read_csv(‘https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv')data.head() Here’s what we’ll do, preparation-wise: Drop irrelevant columns (Ticket and PassengerId) Remap Sex column to zeros and ones Check if a passenger had a unique title (like doctor) or had something more generic (like Mr., Miss.) — can be extracted from the Name column Check if cabin information was known — if the value of Cabin column is not NaN Create dummy variables from the Embarked column — 3 options Fill Age values with the simple mean And here’s the code for the preparation process: data.drop([‘Ticket’, ‘PassengerId’], axis=1, inplace=True)gender_mapper = {‘male’: 0, ‘female’: 1}data[‘Sex’].replace(gender_mapper, inplace=True)data[‘Title’] = data[‘Name’].apply(lambda x: x.split(‘,’)[1].strip().split(‘ ‘)[0])data[‘Title’] = [0 if x in [‘Mr.’, ‘Miss.’, ‘Mrs.’] else 1 for x in data[‘Title’]]data = data.rename(columns={‘Title’: ‘Title_Unusual’})data.drop(‘Name’, axis=1, inplace=True)data[‘Cabin_Known’] = [0 if str(x) == ‘nan’ else 1 for x in data[‘Cabin’]]data.drop(‘Cabin’, axis=1, inplace=True)emb_dummies = pd.get_dummies(data[‘Embarked’], drop_first=True, prefix=’Embarked’)data = pd.concat([data, emb_dummies], axis=1)data.drop(‘Embarked’, axis=1, inplace=True)data[‘Age’] = data[‘Age’].fillna(int(data[‘Age’].mean())) Feel free to just copy it over, as this isn’t the article on data preparation. Here's how our dataset looks now: Looks fine, but some attributes are on a much greater scale than the others — Age and Fare. We’ll use the standard scaler to address this, but first, let’s perform the train test split: X = data.drop(‘Survived’, axis=1)y = data[‘Survived’]X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8) And now let’s fit the standard scaler to the train data, and transform both train and test data: ss = StandardScaler()X_train_scaled = ss.fit_transform(X_train)X_test_scaled = ss.transform(X_test) That’s it for this section. In the next one, we’ll see the TPOT library in action. We’ve covered a lot thus far, and now we’ll shift our focus to the meat of the article. First, we need to import TPOT — either the regressor or the classifier. We’re dealing with the classification problem here, so guess which one we’ll use. from tpot import TPOTClassifier The training process can’t be easier: tpot = TPOTClassifier(verbosity=2, max_time_mins=10)tpot.fit(X_train_scaled, y_train) Here we’ve specified the verbosity parameter as 2, as we want more information printed out, and also specified for how long we want training to last. Feel free to train it for longer, but 10 minutes is perfectly fine for a demonstration case. We’ll get some info printed out during the training: It’s only 4 generations, so the model won’t be perfect, but we didn’t want to spend an entire day training the model. You could. We can now check for the best pipeline: tpot.fitted_pipeline_ As you can see, the gradient boosting method was used with tweaked hyperparameter values. TPOT got to this point in only 10 minutes! Think about how much time would it take to get here manually. We can now check for the accuracy on the test set: tpot.score(X_test_scaled, y_test)>>> 0.8491620111731844 Not terrible, by any means. And that’s just enough for an introduction to the TPOT library. Feel free to explore further on your own. The official documentation is a great place to start. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
[ { "code": null, "e": 451, "s": 171, "text": "Everybody and their mother wants to get into machine learning. That’s great, but the field got automated over the years — to a degree. Nowadays, you don’t have to be a machine learning engineer to produce good quality models. How? That’s where libraries like TPOT come into play." }, { "code": null, "e": 595, "s": 451, "text": "If you’re more of a video person, or just want to reinforce your knowledge, feel free to watch our video on the topic. Source code is included:" }, { "code": null, "e": 873, "s": 595, "text": "Let’s face the facts — machine learning isn’t as interesting as hyped by the media. You can do amazing things with it, don’t get me wrong. I’m only talking about the actual machine learning process. You know, the process of finding an optimal algorithm and its hyperparameters." }, { "code": null, "e": 993, "s": 873, "text": "It’s good this part is getting (or already got) automated — since we as engineers can focus on more interesting things." }, { "code": null, "e": 1275, "s": 993, "text": "The ideal reader is someone familiar with the Python programming language and with the general flow of a machine learning project. You don’t have to be an expert, or even work in the field, but it’s expected that you’re familiar with the most common algorithms and how to use them." }, { "code": null, "e": 1313, "s": 1275, "text": "The article is structured as follows:" }, { "code": null, "e": 1403, "s": 1313, "text": "What’s TPOT?Genetic programming introductionDataset loading and preparationTPOT in action" }, { "code": null, "e": 1416, "s": 1403, "text": "What’s TPOT?" }, { "code": null, "e": 1449, "s": 1416, "text": "Genetic programming introduction" }, { "code": null, "e": 1481, "s": 1449, "text": "Dataset loading and preparation" }, { "code": null, "e": 1496, "s": 1481, "text": "TPOT in action" }, { "code": null, "e": 1536, "s": 1496, "text": "So without much ado, let’s get started!" }, { "code": null, "e": 1667, "s": 1536, "text": "TPOT, or Tree-based Pipeline Optimization Tool is a Python library for automated machine learning. Here’s the official definition:" }, { "code": null, "e": 1831, "s": 1667, "text": "Consider TPOT your Data Science Assistant. TPOT is a Python Automated Machine Learning tool that optimizes machine learning pipelines using genetic programming.[1]" }, { "code": null, "e": 2112, "s": 1831, "text": "In a way, TPOT is your data science assistant. It automates the “boring” stuff and leaves you with the tasks of data gathering and preparation. I know this segment isn’t fun to some of you — but it’s 80% of the job. With libraries like TPOT, that percentage might only get higher." }, { "code": null, "e": 2271, "s": 2112, "text": "Plus, data gathering and preparation can’t be fully automated, for obvious reasons. Another sentence over at the official documentation drives the point home:" }, { "code": null, "e": 2430, "s": 2271, "text": "TPOT will automate the most tedious part of machine learning by intelligently exploring thousands of possible pipelines to find the best one for your data.[1]" }, { "code": null, "e": 2523, "s": 2430, "text": "Let’s take a quick look at your average machine learning pipeline to see where TPOT fits in:" }, { "code": null, "e": 2599, "s": 2523, "text": "As you can see, the library automates every tedious portion of the process." }, { "code": null, "e": 2704, "s": 2599, "text": "But how? By using something known as “genetic programming”. Let’s explore this term in the next section." }, { "code": null, "e": 2761, "s": 2704, "text": "The official website summarizes the concept pretty well:" }, { "code": null, "e": 3108, "s": 2761, "text": "Genetic Programming (GP) is a type of Evolutionary Algorithm (EA), a subset of machine learning. EAs are used to discover solutions to problems humans do not know how to solve, directly. Free of human preconceptions or biases, the adaptive nature of EAs can generate solutions that are comparable to, and often better than the best human efforts." }, { "code": null, "e": 3744, "s": 3108, "text": "Inspired by biological evolution and its fundamental mechanisms, GP software systems implement an algorithm that uses random mutation, crossover, a fitness function, and multiple generations of evolution to resolve a user-defined task. GP can be used to discover a functional relationship between features in data (symbolic regression), to group data into categories (classification), and to assist in the design of electrical circuits, antennae, and quantum algorithms. GP is applied to software engineering through code synthesis, genetic improvement, automatic bug-fixing, and in developing game-playing strategies, ... and more.[2]" }, { "code": null, "e": 3999, "s": 3744, "text": "With the right data and the right amounts of data, we can use machine learning to learn any function. Still, knowing which algorithm to use can be daunting — there’s just too many of them. And we still haven't touched the idea of hyperparameter tweaking." }, { "code": null, "e": 4194, "s": 3999, "text": "That’s where genetic programming really shines, because it is inspired by the Darwinian process of Natural Selection, and they are used to generate solutions to optimization in computer science." }, { "code": null, "e": 4232, "s": 4194, "text": "Genetic algorithms have 3 properties:" }, { "code": null, "e": 4582, "s": 4232, "text": "Selection: where you have a population of a possible solution and a fitness function — then at every iteration each fit is evaluatedCrossover — selecting the fittest solution and performing crossover to create a new populationMutation — taking their children and mutating them with some random modification until you get the fittest or best solution" }, { "code": null, "e": 4715, "s": 4582, "text": "Selection: where you have a population of a possible solution and a fitness function — then at every iteration each fit is evaluated" }, { "code": null, "e": 4810, "s": 4715, "text": "Crossover — selecting the fittest solution and performing crossover to create a new population" }, { "code": null, "e": 4934, "s": 4810, "text": "Mutation — taking their children and mutating them with some random modification until you get the fittest or best solution" }, { "code": null, "e": 5079, "s": 4934, "text": "Sounds like a lot, definitely, but TPOT doesn’t require us to be experts in genetic programming. Knowing the concepts is, as always, beneficial." }, { "code": null, "e": 5183, "s": 5079, "text": "Okay, we have the theory part covered thus far. We’ll gather and prepare some data in the next section." }, { "code": null, "e": 5502, "s": 5183, "text": "I love using the Titanic dataset for most of my examples. The dataset isn’t too basic, as it requires some preparation, but it isn’t too complex in the means that the preparation process would take too long. You could definitely spend more time preparing this dataset then I did, but this will be enough for our needs." }, { "code": null, "e": 5590, "s": 5502, "text": "Imports-wise, we’ll need 3 things for now: Pandas, StandardScaler and train test split:" }, { "code": null, "e": 5710, "s": 5590, "text": "import pandas as pdfrom sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import train_test_split" }, { "code": null, "e": 5781, "s": 5710, "text": "Next, we can load in the dataset and display the first couple of rows:" }, { "code": null, "e": 5892, "s": 5781, "text": "data = pd.read_csv(‘https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv')data.head()" }, { "code": null, "e": 5932, "s": 5892, "text": "Here’s what we’ll do, preparation-wise:" }, { "code": null, "e": 5981, "s": 5932, "text": "Drop irrelevant columns (Ticket and PassengerId)" }, { "code": null, "e": 6016, "s": 5981, "text": "Remap Sex column to zeros and ones" }, { "code": null, "e": 6158, "s": 6016, "text": "Check if a passenger had a unique title (like doctor) or had something more generic (like Mr., Miss.) — can be extracted from the Name column" }, { "code": null, "e": 6237, "s": 6158, "text": "Check if cabin information was known — if the value of Cabin column is not NaN" }, { "code": null, "e": 6297, "s": 6237, "text": "Create dummy variables from the Embarked column — 3 options" }, { "code": null, "e": 6334, "s": 6297, "text": "Fill Age values with the simple mean" }, { "code": null, "e": 6383, "s": 6334, "text": "And here’s the code for the preparation process:" }, { "code": null, "e": 7129, "s": 6383, "text": "data.drop([‘Ticket’, ‘PassengerId’], axis=1, inplace=True)gender_mapper = {‘male’: 0, ‘female’: 1}data[‘Sex’].replace(gender_mapper, inplace=True)data[‘Title’] = data[‘Name’].apply(lambda x: x.split(‘,’)[1].strip().split(‘ ‘)[0])data[‘Title’] = [0 if x in [‘Mr.’, ‘Miss.’, ‘Mrs.’] else 1 for x in data[‘Title’]]data = data.rename(columns={‘Title’: ‘Title_Unusual’})data.drop(‘Name’, axis=1, inplace=True)data[‘Cabin_Known’] = [0 if str(x) == ‘nan’ else 1 for x in data[‘Cabin’]]data.drop(‘Cabin’, axis=1, inplace=True)emb_dummies = pd.get_dummies(data[‘Embarked’], drop_first=True, prefix=’Embarked’)data = pd.concat([data, emb_dummies], axis=1)data.drop(‘Embarked’, axis=1, inplace=True)data[‘Age’] = data[‘Age’].fillna(int(data[‘Age’].mean()))" }, { "code": null, "e": 7208, "s": 7129, "text": "Feel free to just copy it over, as this isn’t the article on data preparation." }, { "code": null, "e": 7242, "s": 7208, "text": "Here's how our dataset looks now:" }, { "code": null, "e": 7428, "s": 7242, "text": "Looks fine, but some attributes are on a much greater scale than the others — Age and Fare. We’ll use the standard scaler to address this, but first, let’s perform the train test split:" }, { "code": null, "e": 7555, "s": 7428, "text": "X = data.drop(‘Survived’, axis=1)y = data[‘Survived’]X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8)" }, { "code": null, "e": 7652, "s": 7555, "text": "And now let’s fit the standard scaler to the train data, and transform both train and test data:" }, { "code": null, "e": 7752, "s": 7652, "text": "ss = StandardScaler()X_train_scaled = ss.fit_transform(X_train)X_test_scaled = ss.transform(X_test)" }, { "code": null, "e": 7835, "s": 7752, "text": "That’s it for this section. In the next one, we’ll see the TPOT library in action." }, { "code": null, "e": 8077, "s": 7835, "text": "We’ve covered a lot thus far, and now we’ll shift our focus to the meat of the article. First, we need to import TPOT — either the regressor or the classifier. We’re dealing with the classification problem here, so guess which one we’ll use." }, { "code": null, "e": 8109, "s": 8077, "text": "from tpot import TPOTClassifier" }, { "code": null, "e": 8147, "s": 8109, "text": "The training process can’t be easier:" }, { "code": null, "e": 8233, "s": 8147, "text": "tpot = TPOTClassifier(verbosity=2, max_time_mins=10)tpot.fit(X_train_scaled, y_train)" }, { "code": null, "e": 8476, "s": 8233, "text": "Here we’ve specified the verbosity parameter as 2, as we want more information printed out, and also specified for how long we want training to last. Feel free to train it for longer, but 10 minutes is perfectly fine for a demonstration case." }, { "code": null, "e": 8529, "s": 8476, "text": "We’ll get some info printed out during the training:" }, { "code": null, "e": 8658, "s": 8529, "text": "It’s only 4 generations, so the model won’t be perfect, but we didn’t want to spend an entire day training the model. You could." }, { "code": null, "e": 8698, "s": 8658, "text": "We can now check for the best pipeline:" }, { "code": null, "e": 8720, "s": 8698, "text": "tpot.fitted_pipeline_" }, { "code": null, "e": 8915, "s": 8720, "text": "As you can see, the gradient boosting method was used with tweaked hyperparameter values. TPOT got to this point in only 10 minutes! Think about how much time would it take to get here manually." }, { "code": null, "e": 8966, "s": 8915, "text": "We can now check for the accuracy on the test set:" }, { "code": null, "e": 9022, "s": 8966, "text": "tpot.score(X_test_scaled, y_test)>>> 0.8491620111731844" }, { "code": null, "e": 9050, "s": 9022, "text": "Not terrible, by any means." }, { "code": null, "e": 9210, "s": 9050, "text": "And that’s just enough for an introduction to the TPOT library. Feel free to explore further on your own. The official documentation is a great place to start." } ]
How to create a vertical line with CSS?
To create a vertical line with CSS, the code is as follows − Live Demo <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .vLine { border-left: 6px solid rgb(128, 0, 128); height: 500px; margin-left: 5%; } </style> </head> <body> <h1>Vertical Line Example<h1> <div class="vLine"></div> </body> </html> The above code will produce the following output −
[ { "code": null, "e": 1123, "s": 1062, "text": "To create a vertical line with CSS, the code is as follows −" }, { "code": null, "e": 1134, "s": 1123, "text": " Live Demo" }, { "code": null, "e": 1445, "s": 1134, "text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<style>\n .vLine {\n border-left: 6px solid rgb(128, 0, 128);\n height: 500px;\n margin-left: 5%;\n }\n</style>\n</head>\n<body>\n<h1>Vertical Line Example<h1>\n<div class=\"vLine\"></div>\n</body>\n</html>" }, { "code": null, "e": 1496, "s": 1445, "text": "The above code will produce the following output −" } ]
How to Line Breaks to JavaScript Alert?
To add line breaks to JavaScript alert, use “\r\n”. In the following example, we will see how to display text in JavaScript alert. Live Demo <html> <body> <script> function DisplayAlert() { var newLine = "\r\n" var msg = "Showing how to add line break." msg += newLine; msg += "Line Break can be easily added in JavaScript."; msg += newLine; msg += "Simply Easy Learning"; msg+= newLine; msg += "TutorialsPoint.com"; alert(msg); } </script> <input type = "button" value = "Click" onclick = "DisplayAlert()" /> </body> </html>
[ { "code": null, "e": 1193, "s": 1062, "text": "To add line breaks to JavaScript alert, use “\\r\\n”. In the following example, we will see how to display text in JavaScript alert." }, { "code": null, "e": 1204, "s": 1193, "text": " Live Demo" }, { "code": null, "e": 1739, "s": 1204, "text": "<html>\n <body>\n <script>\n function DisplayAlert() {\n var newLine = \"\\r\\n\"\n var msg = \"Showing how to add line break.\"\n msg += newLine;\n msg += \"Line Break can be easily added in JavaScript.\";\n msg += newLine;\n msg += \"Simply Easy Learning\";\n msg+= newLine;\n msg += \"TutorialsPoint.com\";\n alert(msg);\n }\n </script>\n <input type = \"button\" value = \"Click\" onclick = \"DisplayAlert()\" />\n </body>\n</html>" } ]
How to change MySQL timezone?
To change the timezone in MySQL, we can use the SET command. The following is the syntax. SET time_zone=’someValue’; Let us now use the above syntax and apply it in the below query. mysql > SET time_zone = '+8:00'; Query OK, 0 rows affected (0.00 sec) Above, the time_zone is changed by a value equivalent to 8. To change the timezone globally, use the GLOBAL command. Here is the syntax. SET GLOBAL time_zone = 'someValue'; Here is an example. mysql> SET GLOBAL time_zone = '+8:00'; Query OK, 0 rows affected (0.00 sec) The above query will change the timezone globally.
[ { "code": null, "e": 1152, "s": 1062, "text": "To change the timezone in MySQL, we can use the SET command. The following is the syntax." }, { "code": null, "e": 1180, "s": 1152, "text": "SET time_zone=’someValue’;\n" }, { "code": null, "e": 1245, "s": 1180, "text": "Let us now use the above syntax and apply it in the below query." }, { "code": null, "e": 1315, "s": 1245, "text": "mysql > SET time_zone = '+8:00';\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1452, "s": 1315, "text": "Above, the time_zone is changed by a value equivalent to 8. To change the timezone globally, use the GLOBAL command. Here is the syntax." }, { "code": null, "e": 1489, "s": 1452, "text": "SET GLOBAL time_zone = 'someValue';\n" }, { "code": null, "e": 1509, "s": 1489, "text": "Here is an example." }, { "code": null, "e": 1585, "s": 1509, "text": "mysql> SET GLOBAL time_zone = '+8:00';\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1636, "s": 1585, "text": "The above query will change the timezone globally." } ]
Introduction to PyMC3: A Python package for probabilistic programming | by Tung T. Nguyen | Towards Data Science
Introduction We often hear something like this on weather forecast programs: the chance of raining tomorrow is 80%. What does that mean? It is often hard to give meaning to this kind of statement, especially from a frequentist perspective: there is no reasonable way to repeat the raining/not raining experiment an infinite (or very big) number of times. The Bayesian approach provides a solution for this type of statement. The following sentence, taken from the book Probabilistic Programming & Bayesian Methods for Hackers, perfectly summarizes one of the key ideas of the Bayesian perspective. The Bayesian world-view interprets probability as measure of believability in an event, that is, how confident we are in an event occurring. In other words, in the Bayesian approach, we can never be absolutely sure about our *beliefs*, but can definitely say how confident we are about the relevant events. Furthermore, as more data is collected, we can become more confident about our beliefs. As a scientist, I am trained to believe in the data and always be critical about almost everything. Naturally, I find Bayesian inference to be rather intuitive. However, it is often computationally and conceptually challenging to work with Bayesian inference. Often, a lot of long and complicated mathematical computations are required to get things done. Even as a mathematician, I occasionally find these computations tedious; especially when I need a quick overview of the problem that I want to solve. Luckily, my mentor Austin Rochford recently introduced me to a wonderful package called PyMC3 that allows us to do numerical Bayesian inference. In this article, I will give a quick introduction to PyMC3 through a concrete example. A concrete example Let’s assume that we have a coin. We flip it three times and the result is: [0, 1, 1] where 0 means that the coin lands in a tail and 1 means that the coin lands in a head. Are we confident in saying that this is a fair coin? In other words, if we let θ be the probability that the coin will return the head, is the evidence strong enough to support the statement that θ=12? Well, as we do not know anything about the coin other than the result of the above experiment, it is hard to say anything for sure. From the frequentist-perspective, a point estimation for θ would be While this number makes sense, the frequentist approach does not really provide a certain level of confidence about it. In particular, if we do more trials, we are likely to get different point estimations for θ. This is where the Bayesian approach could offer some improvement. The idea is simple, as we do not know anything about θ, we can assume that θ could be any value on [0,1]. Mathematically, our prior belief is that θ follows a Uniform(0,1) distribution. For those who need a refresh in maths, the pdf of Uniform(0,1) is given by We can then use evidence/our observations to update our belief about the distribution of θ. Let us formally call D to be the evidence (in our case, it is the result of our coin toss.) By the Bayesian rule, the posterior distribution is computed by where p(D|θ) is the likelihood function, p(θ) is the prior distribution (Uniform(0,1) in this case.) There are two ways to go from here. The explicit approach In this particular example, we can do everything by hand. More precisely, given θ, the probability that we get 2 heads out of three coin tosses is given by By assumption, p(θ)=1. Next, we evaluate the dominator By some simple algebra, we can see that the above integral is equal to 1/4 and hence Remark: By the same computation, we can also see that if the prior distribution of θ is a Beta distribution with parameters α,β, i.e p(θ)=B(α,β), and the sample size is N with k of them are head, then the posterior distribution of θ is given by B(α+k,β+N−k). In our case, α=β=1,N=3,k=2. The numerical approach In the explicit approach, we are able to explicitly compute the posterior distribution of θ by using conjugate priors. However, sometimes conjugate priors are used for computational simplicity and they might not reflect the reality. Furthermore, it is not always feasible to find conjugate priors. We can overcome this problem by using the Markov Chain Monte Carlo (MCMC) method to approximate the posterior distributions. The math here is pretty beautiful but for the sole purpose of this article, we will not dive into it. Instead, we will explain how to implement this method using PyMC3. To run our codes, we import the following packages. import pymc3 as pmimport scipy.stats as statsimport pandas as pdimport matplotlib.pyplot as pltimport numpy as np%matplotlib inlinefrom IPython.core.pylabtools import figsize First, we need to initiate the prior distribution for θ. In PyMC3, we can do so by the following lines of code. with pm.Model() as model: theta=pm.Uniform('theta', lower=0, upper=1) We then fit our model with the observed data. This can be done by the following lines of code. occurrences=np.array([1,1,0]) #our observation with model: obs=pm.Bernoulli("obs", p, observed=occurrences) #input the observations step=pm.Metropolis() trace=pm.sample(18000, step=step) burned_trace=trace[1000:] Internally, PyMC3 uses the Metropolis-Hastings algorithm to approximate the posterior distribution. The trace function determines the number of samples withdrawn from the posterior distribution. Finally, as the algorithm might be unstable at the beginning, it is useful to only withdraw samples after a certain period of iterations. That is the purpose of the last line in our code. We can then plot the histogram of our samples obtained from the posterior distribution and compare it with the true density function. from IPython.core.pylabtools import figsizep_true=0.5figsize(12.5, 4)plt.title(r"Posterior distribution of $\theta$")plt.vlines(p_true,0, 2, linestyle='--', label=r"true $\theta$ (unknown)", color='red')plt.hist(burned_trace["theta"], bins=25, histtype='stepfilled', density=True, color='#348ABD')x=np.arange(0,1.04,0.04)plt.plot(x, 12*x*x*(1-x), color='black')plt.legend()plt.show() As we can clearly see, the numerical approximation is pretty close to the true posterior distribution. What happens if we increase the sample size? As we mentioned earlier, the more data we get, the more confident we are about the true value of θ. Let us test our hypothesis by a simple simulation. We will randomly toss a coin 1000 times. We then use PyMC3 to approximate the posterior distribution of θ. We then plot the histogram of samples obtained from this distribution. All of these steps can be done by the following lines of code N=1000 #the number of samplesoccurences=np.random.binomial(1, p=0.5, size=N)k=occurences.sum() #the number of head#fit the observed data with pm.Model() as model1: theta=pm.Uniform('theta', lower=0, upper=1)with model1: obs=pm.Bernoulli("obs", theta, observed=occurrences) step=pm.Metropolis() trace=pm.sample(18000, step=step) burned_trace1=trace[1000:]#plot the posterior distribution of theta. p_true=0.5figsize(12.5, 4)plt.title(r"Posterior distribution of $\theta for sample size N=1000$")plt.vlines(p_true,0, 25, linestyle='--', label="true $\theta$ (unknown)", color='red')plt.hist(burned_trace1["theta"], bins=25, histtype='stepfilled', density=True, color='#348ABD')plt.legend()plt.show() Here is what we get. As we can see, the posterior distribution is now centered around the true value of θ. We can estimate θ by taking the mean of our samples. burned_trace1['theta'].mean()0.4997847718651745 We see that this is really close to the true answer. Conclusion As we can see, PyMC3 performs statistical inference tasks pretty well. Furthermore, it makes probabilistic programming rather painless.
[ { "code": null, "e": 185, "s": 172, "text": "Introduction" }, { "code": null, "e": 527, "s": 185, "text": "We often hear something like this on weather forecast programs: the chance of raining tomorrow is 80%. What does that mean? It is often hard to give meaning to this kind of statement, especially from a frequentist perspective: there is no reasonable way to repeat the raining/not raining experiment an infinite (or very big) number of times." }, { "code": null, "e": 770, "s": 527, "text": "The Bayesian approach provides a solution for this type of statement. The following sentence, taken from the book Probabilistic Programming & Bayesian Methods for Hackers, perfectly summarizes one of the key ideas of the Bayesian perspective." }, { "code": null, "e": 911, "s": 770, "text": "The Bayesian world-view interprets probability as measure of believability in an event, that is, how confident we are in an event occurring." }, { "code": null, "e": 1165, "s": 911, "text": "In other words, in the Bayesian approach, we can never be absolutely sure about our *beliefs*, but can definitely say how confident we are about the relevant events. Furthermore, as more data is collected, we can become more confident about our beliefs." }, { "code": null, "e": 1326, "s": 1165, "text": "As a scientist, I am trained to believe in the data and always be critical about almost everything. Naturally, I find Bayesian inference to be rather intuitive." }, { "code": null, "e": 1671, "s": 1326, "text": "However, it is often computationally and conceptually challenging to work with Bayesian inference. Often, a lot of long and complicated mathematical computations are required to get things done. Even as a mathematician, I occasionally find these computations tedious; especially when I need a quick overview of the problem that I want to solve." }, { "code": null, "e": 1903, "s": 1671, "text": "Luckily, my mentor Austin Rochford recently introduced me to a wonderful package called PyMC3 that allows us to do numerical Bayesian inference. In this article, I will give a quick introduction to PyMC3 through a concrete example." }, { "code": null, "e": 1922, "s": 1903, "text": "A concrete example" }, { "code": null, "e": 1998, "s": 1922, "text": "Let’s assume that we have a coin. We flip it three times and the result is:" }, { "code": null, "e": 2008, "s": 1998, "text": "[0, 1, 1]" }, { "code": null, "e": 2297, "s": 2008, "text": "where 0 means that the coin lands in a tail and 1 means that the coin lands in a head. Are we confident in saying that this is a fair coin? In other words, if we let θ be the probability that the coin will return the head, is the evidence strong enough to support the statement that θ=12?" }, { "code": null, "e": 2497, "s": 2297, "text": "Well, as we do not know anything about the coin other than the result of the above experiment, it is hard to say anything for sure. From the frequentist-perspective, a point estimation for θ would be" }, { "code": null, "e": 2710, "s": 2497, "text": "While this number makes sense, the frequentist approach does not really provide a certain level of confidence about it. In particular, if we do more trials, we are likely to get different point estimations for θ." }, { "code": null, "e": 3037, "s": 2710, "text": "This is where the Bayesian approach could offer some improvement. The idea is simple, as we do not know anything about θ, we can assume that θ could be any value on [0,1]. Mathematically, our prior belief is that θ follows a Uniform(0,1) distribution. For those who need a refresh in maths, the pdf of Uniform(0,1) is given by" }, { "code": null, "e": 3129, "s": 3037, "text": "We can then use evidence/our observations to update our belief about the distribution of θ." }, { "code": null, "e": 3285, "s": 3129, "text": "Let us formally call D to be the evidence (in our case, it is the result of our coin toss.) By the Bayesian rule, the posterior distribution is computed by" }, { "code": null, "e": 3422, "s": 3285, "text": "where p(D|θ) is the likelihood function, p(θ) is the prior distribution (Uniform(0,1) in this case.) There are two ways to go from here." }, { "code": null, "e": 3444, "s": 3422, "text": "The explicit approach" }, { "code": null, "e": 3600, "s": 3444, "text": "In this particular example, we can do everything by hand. More precisely, given θ, the probability that we get 2 heads out of three coin tosses is given by" }, { "code": null, "e": 3655, "s": 3600, "text": "By assumption, p(θ)=1. Next, we evaluate the dominator" }, { "code": null, "e": 3740, "s": 3655, "text": "By some simple algebra, we can see that the above integral is equal to 1/4 and hence" }, { "code": null, "e": 4027, "s": 3740, "text": "Remark: By the same computation, we can also see that if the prior distribution of θ is a Beta distribution with parameters α,β, i.e p(θ)=B(α,β), and the sample size is N with k of them are head, then the posterior distribution of θ is given by B(α+k,β+N−k). In our case, α=β=1,N=3,k=2." }, { "code": null, "e": 4050, "s": 4027, "text": "The numerical approach" }, { "code": null, "e": 4348, "s": 4050, "text": "In the explicit approach, we are able to explicitly compute the posterior distribution of θ by using conjugate priors. However, sometimes conjugate priors are used for computational simplicity and they might not reflect the reality. Furthermore, it is not always feasible to find conjugate priors." }, { "code": null, "e": 4642, "s": 4348, "text": "We can overcome this problem by using the Markov Chain Monte Carlo (MCMC) method to approximate the posterior distributions. The math here is pretty beautiful but for the sole purpose of this article, we will not dive into it. Instead, we will explain how to implement this method using PyMC3." }, { "code": null, "e": 4694, "s": 4642, "text": "To run our codes, we import the following packages." }, { "code": null, "e": 4869, "s": 4694, "text": "import pymc3 as pmimport scipy.stats as statsimport pandas as pdimport matplotlib.pyplot as pltimport numpy as np%matplotlib inlinefrom IPython.core.pylabtools import figsize" }, { "code": null, "e": 4981, "s": 4869, "text": "First, we need to initiate the prior distribution for θ. In PyMC3, we can do so by the following lines of code." }, { "code": null, "e": 5054, "s": 4981, "text": "with pm.Model() as model: theta=pm.Uniform('theta', lower=0, upper=1)" }, { "code": null, "e": 5149, "s": 5054, "text": "We then fit our model with the observed data. This can be done by the following lines of code." }, { "code": null, "e": 5374, "s": 5149, "text": "occurrences=np.array([1,1,0]) #our observation with model: obs=pm.Bernoulli(\"obs\", p, observed=occurrences) #input the observations step=pm.Metropolis() trace=pm.sample(18000, step=step) burned_trace=trace[1000:]" }, { "code": null, "e": 5757, "s": 5374, "text": "Internally, PyMC3 uses the Metropolis-Hastings algorithm to approximate the posterior distribution. The trace function determines the number of samples withdrawn from the posterior distribution. Finally, as the algorithm might be unstable at the beginning, it is useful to only withdraw samples after a certain period of iterations. That is the purpose of the last line in our code." }, { "code": null, "e": 5891, "s": 5757, "text": "We can then plot the histogram of our samples obtained from the posterior distribution and compare it with the true density function." }, { "code": null, "e": 6275, "s": 5891, "text": "from IPython.core.pylabtools import figsizep_true=0.5figsize(12.5, 4)plt.title(r\"Posterior distribution of $\\theta$\")plt.vlines(p_true,0, 2, linestyle='--', label=r\"true $\\theta$ (unknown)\", color='red')plt.hist(burned_trace[\"theta\"], bins=25, histtype='stepfilled', density=True, color='#348ABD')x=np.arange(0,1.04,0.04)plt.plot(x, 12*x*x*(1-x), color='black')plt.legend()plt.show()" }, { "code": null, "e": 6378, "s": 6275, "text": "As we can clearly see, the numerical approximation is pretty close to the true posterior distribution." }, { "code": null, "e": 6423, "s": 6378, "text": "What happens if we increase the sample size?" }, { "code": null, "e": 6574, "s": 6423, "text": "As we mentioned earlier, the more data we get, the more confident we are about the true value of θ. Let us test our hypothesis by a simple simulation." }, { "code": null, "e": 6814, "s": 6574, "text": "We will randomly toss a coin 1000 times. We then use PyMC3 to approximate the posterior distribution of θ. We then plot the histogram of samples obtained from this distribution. All of these steps can be done by the following lines of code" }, { "code": null, "e": 7527, "s": 6814, "text": "N=1000 #the number of samplesoccurences=np.random.binomial(1, p=0.5, size=N)k=occurences.sum() #the number of head#fit the observed data with pm.Model() as model1: theta=pm.Uniform('theta', lower=0, upper=1)with model1: obs=pm.Bernoulli(\"obs\", theta, observed=occurrences) step=pm.Metropolis() trace=pm.sample(18000, step=step) burned_trace1=trace[1000:]#plot the posterior distribution of theta. p_true=0.5figsize(12.5, 4)plt.title(r\"Posterior distribution of $\\theta for sample size N=1000$\")plt.vlines(p_true,0, 25, linestyle='--', label=\"true $\\theta$ (unknown)\", color='red')plt.hist(burned_trace1[\"theta\"], bins=25, histtype='stepfilled', density=True, color='#348ABD')plt.legend()plt.show()" }, { "code": null, "e": 7548, "s": 7527, "text": "Here is what we get." }, { "code": null, "e": 7634, "s": 7548, "text": "As we can see, the posterior distribution is now centered around the true value of θ." }, { "code": null, "e": 7687, "s": 7634, "text": "We can estimate θ by taking the mean of our samples." }, { "code": null, "e": 7735, "s": 7687, "text": "burned_trace1['theta'].mean()0.4997847718651745" }, { "code": null, "e": 7788, "s": 7735, "text": "We see that this is really close to the true answer." }, { "code": null, "e": 7799, "s": 7788, "text": "Conclusion" } ]
Java | Inheritance | Question 4
28 Jun, 2021 Which of the following is true about inheritance in Java? 1) Private methods are final. 2) Protected members are accessible within a package and inherited classes outside the package. 3) Protected methods are final. 4) We cannot override private methods. (A) 1, 2 and 4(B) Only 1 and 2(C) 1, 2 and 3(D) 2, 3 and 4Answer: (A)Explanation: See https://www.geeksforgeeks.org/can-override-private-methods-java/ and https://www.geeksforgeeks.org/comparison-of-inheritance-in-c-and-java/Quiz of this Question Inheritance java-inheritance Java Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Java | Constructors | Question 3 Java | Exception Handling | Question 2 Java | Functions | Question 1 Java | Exception Handling | Question 3 Java | Exception Handling | Question 8 Java | Exception Handling | Question 4 Java | Abstract Class and Interface | Question 2 Java | Exception Handling | Question 7 Java | Exception Handling | Question 6 Java | Class and Object | Question 1
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 110, "s": 52, "text": "Which of the following is true about inheritance in Java?" }, { "code": null, "e": 313, "s": 110, "text": "\n1) Private methods are final.\n2) Protected members are accessible within a package and \n inherited classes outside the package.\n3) Protected methods are final.\n4) We cannot override private methods. " }, { "code": null, "e": 560, "s": 313, "text": "(A) 1, 2 and 4(B) Only 1 and 2(C) 1, 2 and 3(D) 2, 3 and 4Answer: (A)Explanation: See https://www.geeksforgeeks.org/can-override-private-methods-java/ and https://www.geeksforgeeks.org/comparison-of-inheritance-in-c-and-java/Quiz of this Question" }, { "code": null, "e": 572, "s": 560, "text": "Inheritance" }, { "code": null, "e": 589, "s": 572, "text": "java-inheritance" }, { "code": null, "e": 599, "s": 589, "text": "Java Quiz" }, { "code": null, "e": 697, "s": 599, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 730, "s": 697, "text": "Java | Constructors | Question 3" }, { "code": null, "e": 769, "s": 730, "text": "Java | Exception Handling | Question 2" }, { "code": null, "e": 799, "s": 769, "text": "Java | Functions | Question 1" }, { "code": null, "e": 838, "s": 799, "text": "Java | Exception Handling | Question 3" }, { "code": null, "e": 877, "s": 838, "text": "Java | Exception Handling | Question 8" }, { "code": null, "e": 916, "s": 877, "text": "Java | Exception Handling | Question 4" }, { "code": null, "e": 965, "s": 916, "text": "Java | Abstract Class and Interface | Question 2" }, { "code": null, "e": 1004, "s": 965, "text": "Java | Exception Handling | Question 7" }, { "code": null, "e": 1043, "s": 1004, "text": "Java | Exception Handling | Question 6" } ]
How to Install and Configure Nginx from Source on Linux
21 Jul, 2021 Nginx is written in C language by Igor Sysoev to overcome the C10K problem (i.e. Concurrently handling 10k(ten thousand) connections). The problem was how to optimize the network socket to handle numerous clients at the same time. Nginx is a solution to that problem. It is a free and open-source software for reverse proxying, load balancer, web serving, media streaming, etc. It is pronounced as “Engine X”, by eliminating the letter “e” from this, the name becomes “Nginx”. In this article, we are going to see a step-by-step guide on how to install and configure the Nginx server from the source. It supports reverse proxy with caching.It supports WebSockets, load balancing, and fault tolerance.It supports FastCGI with caching.It can be used for handling static files, index files, and auto-indexing.It supports SSL.Both name-based and IP-based virtual servers can be configured in Nginx.HTTP basic authenticationAll the main mail proxy server features are supported in Nginx. It supports reverse proxy with caching. It supports WebSockets, load balancing, and fault tolerance. It supports FastCGI with caching. It can be used for handling static files, index files, and auto-indexing. It supports SSL. Both name-based and IP-based virtual servers can be configured in Nginx. HTTP basic authentication All the main mail proxy server features are supported in Nginx. Step 1: Download the Nginx archive from this link and save the archive file on your desktop. Nginx Download page Or, you can download the Nginx web server archive file by running the following command in the terminal. wget http://nginx.org/download/nginx-1.21.1.tar.gz Downloading the Nginx server wget will fetch the archive file and save it to the location where you have opened the terminal. Step 2: After downloading the archive, we need to navigate the folder where we have downloaded that archive and have to extract the archive using any archive utility. You can run the following command to extract the Nginx archive file. tar -xf nginx-1.21.1.tar.gz After this, the folder structure should look like this. Nginx folder Step 3: Now, to begin the installation of Nginx, navigate to the extracted folder and open the terminal here, then run the following command. Navigate to the directory by running the following command: cd ~/Desktop/nginx-1.21.1 Start the configuration installer of the Nginx. ./configure Here below is a summary of the configuration file: Configuration summary + using system PCRE library + OpenSSL library is not used + md5: using system crypto library + sha1: using system crypto library + using system zlib library nginx path prefix: "/usr/local/nginx" nginx binary file: "/usr/local/nginx/sbin/nginx" nginx configuration prefix: "/usr/local/nginx/conf" nginx configuration file: "/usr/local/nginx/conf/nginx.conf" nginx pid file: "/usr/local/nginx/logs/nginx.pid" nginx error log file: "/usr/local/nginx/logs/error.log" nginx http access log file: "/usr/local/nginx/logs/access.log" nginx http client request body temporary files: "client_body_temp" nginx http proxy temporary files: "proxy_temp" nginx http fastcgi temporary files: "fastcgi_temp" nginx http uwsgi temporary files: "uwsgi_temp" nginx http scgi temporary files: "scgi_temp" Build the Nginx package from the source using the make command. make Run the make install command to install the built package. sudo make install This command will install Nginx in the /usr/local/nginx directory. Step 4: Confirm the installation and check the installed version of Nginx by running the following command: Navigate to /usr/local/nginx using the cd command (change directory): cd /usr/local/nginx/sbin To check what is the current installed version of the Nginx. ./nginx -v Successfully installed Nginx Follow the following steps to start an Nginx server. Navigate to the default location where Nginx is installed by running the following command in the terminal. Navigate to the default location where Nginx is installed by running the following command in the terminal. cd /usr/local/nginx/sbin 2. Now, we can start the Nginx server by running the following command: sudo ./nginx To see if it’s working, go to the local host or your URL. Nginx start (Welcome page) By default, the Nginx is configured to listen on port 80. If you want to change the default Nginx listening port, you can do that by reconfiguring the nginx.conf file located under /usr/local/nginx/conf. Steps to change the default Nginx Listen Port. Step 1: Open the nginx.conf file by running the following command: sudo nano /usr/local/nginx/conf Step 2: After opening, the nginx.conf file should look like this: configuring listen port Navigate to this server section and change listen 80; port to any other port number, e.g. 5555, etc. Step 3: Save the file and run open the localhost with port 5555 as follows. custom listen port To stop the Nginx server, we just need to add the flag -s to stop the Nginx command as follows. sudo ./nginx -s stop This will stop the Nginx server, you can refresh the localhost page and see. Nginx stop To uninstall Nginx, run the following command in the terminal with superuser permissions, i.e. sudo : sudo rm -f -R /usr/local/nginx && rm -f /usr/local/sbin/nginx This will completely remove Nginx from your machine. Here, we are using rm command to remove the directories and subdirectories using -f and -R flags. -f is used to remove the directories, and -R will recursively remove all the directories within directories. Using &&, we can write multiple commands in a single line. Linux-Tools Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 mv command in Linux with examples nohup Command in Linux with Examples chmod command in Linux with examples Introduction to Linux Operating System Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jul, 2021" }, { "code": null, "e": 629, "s": 28, "text": "Nginx is written in C language by Igor Sysoev to overcome the C10K problem (i.e. Concurrently handling 10k(ten thousand) connections). The problem was how to optimize the network socket to handle numerous clients at the same time. Nginx is a solution to that problem. It is a free and open-source software for reverse proxying, load balancer, web serving, media streaming, etc. It is pronounced as “Engine X”, by eliminating the letter “e” from this, the name becomes “Nginx”. In this article, we are going to see a step-by-step guide on how to install and configure the Nginx server from the source." }, { "code": null, "e": 1012, "s": 629, "text": "It supports reverse proxy with caching.It supports WebSockets, load balancing, and fault tolerance.It supports FastCGI with caching.It can be used for handling static files, index files, and auto-indexing.It supports SSL.Both name-based and IP-based virtual servers can be configured in Nginx.HTTP basic authenticationAll the main mail proxy server features are supported in Nginx." }, { "code": null, "e": 1052, "s": 1012, "text": "It supports reverse proxy with caching." }, { "code": null, "e": 1113, "s": 1052, "text": "It supports WebSockets, load balancing, and fault tolerance." }, { "code": null, "e": 1148, "s": 1113, "text": "It supports FastCGI with caching." }, { "code": null, "e": 1222, "s": 1148, "text": "It can be used for handling static files, index files, and auto-indexing." }, { "code": null, "e": 1239, "s": 1222, "text": "It supports SSL." }, { "code": null, "e": 1312, "s": 1239, "text": "Both name-based and IP-based virtual servers can be configured in Nginx." }, { "code": null, "e": 1338, "s": 1312, "text": "HTTP basic authentication" }, { "code": null, "e": 1402, "s": 1338, "text": "All the main mail proxy server features are supported in Nginx." }, { "code": null, "e": 1495, "s": 1402, "text": "Step 1: Download the Nginx archive from this link and save the archive file on your desktop." }, { "code": null, "e": 1515, "s": 1495, "text": "Nginx Download page" }, { "code": null, "e": 1620, "s": 1515, "text": "Or, you can download the Nginx web server archive file by running the following command in the terminal." }, { "code": null, "e": 1671, "s": 1620, "text": "wget http://nginx.org/download/nginx-1.21.1.tar.gz" }, { "code": null, "e": 1700, "s": 1671, "text": "Downloading the Nginx server" }, { "code": null, "e": 1797, "s": 1700, "text": "wget will fetch the archive file and save it to the location where you have opened the terminal." }, { "code": null, "e": 2033, "s": 1797, "text": "Step 2: After downloading the archive, we need to navigate the folder where we have downloaded that archive and have to extract the archive using any archive utility. You can run the following command to extract the Nginx archive file." }, { "code": null, "e": 2061, "s": 2033, "text": "tar -xf nginx-1.21.1.tar.gz" }, { "code": null, "e": 2117, "s": 2061, "text": "After this, the folder structure should look like this." }, { "code": null, "e": 2130, "s": 2117, "text": "Nginx folder" }, { "code": null, "e": 2272, "s": 2130, "text": "Step 3: Now, to begin the installation of Nginx, navigate to the extracted folder and open the terminal here, then run the following command." }, { "code": null, "e": 2332, "s": 2272, "text": "Navigate to the directory by running the following command:" }, { "code": null, "e": 2358, "s": 2332, "text": "cd ~/Desktop/nginx-1.21.1" }, { "code": null, "e": 2406, "s": 2358, "text": "Start the configuration installer of the Nginx." }, { "code": null, "e": 2418, "s": 2406, "text": "./configure" }, { "code": null, "e": 2469, "s": 2418, "text": "Here below is a summary of the configuration file:" }, { "code": null, "e": 3309, "s": 2469, "text": "Configuration summary\n + using system PCRE library\n + OpenSSL library is not used\n + md5: using system crypto library\n + sha1: using system crypto library\n + using system zlib library\n\n nginx path prefix: \"/usr/local/nginx\"\n nginx binary file: \"/usr/local/nginx/sbin/nginx\"\n nginx configuration prefix: \"/usr/local/nginx/conf\"\n nginx configuration file: \"/usr/local/nginx/conf/nginx.conf\"\n nginx pid file: \"/usr/local/nginx/logs/nginx.pid\"\n nginx error log file: \"/usr/local/nginx/logs/error.log\"\n nginx http access log file: \"/usr/local/nginx/logs/access.log\"\n nginx http client request body temporary files: \"client_body_temp\"\n nginx http proxy temporary files: \"proxy_temp\"\n nginx http fastcgi temporary files: \"fastcgi_temp\"\n nginx http uwsgi temporary files: \"uwsgi_temp\"\n nginx http scgi temporary files: \"scgi_temp\"" }, { "code": null, "e": 3373, "s": 3309, "text": "Build the Nginx package from the source using the make command." }, { "code": null, "e": 3378, "s": 3373, "text": "make" }, { "code": null, "e": 3437, "s": 3378, "text": "Run the make install command to install the built package." }, { "code": null, "e": 3455, "s": 3437, "text": "sudo make install" }, { "code": null, "e": 3522, "s": 3455, "text": "This command will install Nginx in the /usr/local/nginx directory." }, { "code": null, "e": 3630, "s": 3522, "text": "Step 4: Confirm the installation and check the installed version of Nginx by running the following command:" }, { "code": null, "e": 3700, "s": 3630, "text": "Navigate to /usr/local/nginx using the cd command (change directory):" }, { "code": null, "e": 3725, "s": 3700, "text": "cd /usr/local/nginx/sbin" }, { "code": null, "e": 3786, "s": 3725, "text": "To check what is the current installed version of the Nginx." }, { "code": null, "e": 3797, "s": 3786, "text": "./nginx -v" }, { "code": null, "e": 3826, "s": 3797, "text": "Successfully installed Nginx" }, { "code": null, "e": 3879, "s": 3826, "text": "Follow the following steps to start an Nginx server." }, { "code": null, "e": 3987, "s": 3879, "text": "Navigate to the default location where Nginx is installed by running the following command in the terminal." }, { "code": null, "e": 4095, "s": 3987, "text": "Navigate to the default location where Nginx is installed by running the following command in the terminal." }, { "code": null, "e": 4120, "s": 4095, "text": "cd /usr/local/nginx/sbin" }, { "code": null, "e": 4201, "s": 4120, "text": " 2. Now, we can start the Nginx server by running the following command:" }, { "code": null, "e": 4214, "s": 4201, "text": "sudo ./nginx" }, { "code": null, "e": 4272, "s": 4214, "text": "To see if it’s working, go to the local host or your URL." }, { "code": null, "e": 4299, "s": 4272, "text": "Nginx start (Welcome page)" }, { "code": null, "e": 4503, "s": 4299, "text": "By default, the Nginx is configured to listen on port 80. If you want to change the default Nginx listening port, you can do that by reconfiguring the nginx.conf file located under /usr/local/nginx/conf." }, { "code": null, "e": 4550, "s": 4503, "text": "Steps to change the default Nginx Listen Port." }, { "code": null, "e": 4617, "s": 4550, "text": "Step 1: Open the nginx.conf file by running the following command:" }, { "code": null, "e": 4649, "s": 4617, "text": "sudo nano /usr/local/nginx/conf" }, { "code": null, "e": 4715, "s": 4649, "text": "Step 2: After opening, the nginx.conf file should look like this:" }, { "code": null, "e": 4739, "s": 4715, "text": "configuring listen port" }, { "code": null, "e": 4840, "s": 4739, "text": "Navigate to this server section and change listen 80; port to any other port number, e.g. 5555, etc." }, { "code": null, "e": 4916, "s": 4840, "text": "Step 3: Save the file and run open the localhost with port 5555 as follows." }, { "code": null, "e": 4935, "s": 4916, "text": "custom listen port" }, { "code": null, "e": 5032, "s": 4935, "text": "To stop the Nginx server, we just need to add the flag -s to stop the Nginx command as follows." }, { "code": null, "e": 5053, "s": 5032, "text": "sudo ./nginx -s stop" }, { "code": null, "e": 5130, "s": 5053, "text": "This will stop the Nginx server, you can refresh the localhost page and see." }, { "code": null, "e": 5141, "s": 5130, "text": "Nginx stop" }, { "code": null, "e": 5243, "s": 5141, "text": "To uninstall Nginx, run the following command in the terminal with superuser permissions, i.e. sudo :" }, { "code": null, "e": 5305, "s": 5243, "text": "sudo rm -f -R /usr/local/nginx && rm -f /usr/local/sbin/nginx" }, { "code": null, "e": 5624, "s": 5305, "text": "This will completely remove Nginx from your machine. Here, we are using rm command to remove the directories and subdirectories using -f and -R flags. -f is used to remove the directories, and -R will recursively remove all the directories within directories. Using &&, we can write multiple commands in a single line." }, { "code": null, "e": 5636, "s": 5624, "text": "Linux-Tools" }, { "code": null, "e": 5643, "s": 5636, "text": "Picked" }, { "code": null, "e": 5654, "s": 5643, "text": "Linux-Unix" }, { "code": null, "e": 5752, "s": 5654, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5778, "s": 5752, "text": "Docker - COPY Instruction" }, { "code": null, "e": 5813, "s": 5778, "text": "scp command in Linux with Examples" }, { "code": null, "e": 5850, "s": 5813, "text": "chown command in Linux with Examples" }, { "code": null, "e": 5879, "s": 5850, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 5913, "s": 5879, "text": "mv command in Linux with examples" }, { "code": null, "e": 5950, "s": 5913, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 5987, "s": 5950, "text": "chmod command in Linux with examples" }, { "code": null, "e": 6026, "s": 5987, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 6066, "s": 6026, "text": "Array Basics in Shell Scripting | Set 1" } ]
Let’s Play Blackjack (with Python) | by Tony Yiu | Towards Data Science
This post is in NO way an attempt to promote blackjack or the act of gambling. Any time you gamble at a casino, the odds are stacked against you — and over time you WILL lose money. Don’t risk what you cannot afford to lose! Corrections: I realized (thanks to a friendly tip from @DonBeham) that under certain conditions, my total_up function was handling multiple aces incorrectly. I have updated both the code below and on my GitHub. My apologies! I haven’t coded anything for the blog lately so I wanted to do a programming related post. One of the classic applications of probability and statistics is the study of games of chance (gambling). Games of chance (card games, dice games, etc.) are a favorite of statisticians because they exhibit both randomness and a certain inevitability: Random in that you don’t know what the result will be game to game. And inevitable in that you know what the average result of a large number of games will be. Today, we will study blackjack by writing up a blackjack simulator in Python, simulating a bunch of games, and then studying how our player did. I will assume some basic familiarity with the game of Blackjack, but here is a quick refresher for how the game is played: Players make their bets.Players are dealt 2 cards.Dealer is dealt 2 cards where the second card is hidden from the players.The objective of the game is to have a higher point total than the dealer (but no more than 21, anything over 21 is an automatic loss called a bust) — if you beat the dealer in this way, you win from the casino what you bet (you also win if the dealer busts). Aces can be worth either 1 or 11; every other card is worth its face amount (face cards are worth 10).An initial 2 card hand composed of an ace and a face card is called a blackjack and is the best possible hand.After the first round of dealing, each player has the option to hit (receive more cards) or stay (no more cards). If hitting results in the player busting (total going over 21), then his or her bet is lost.After all the players are done hitting/staying, the dealer flips over his hidden card. If the dealer’s total is less than 17, then he or she needs to hit (receive a new card). This process repeats until the dealer’s hand either totals to 17 or more or busts (goes above 21).After the dealer is done, the final results are decided — if the dealer busts, then any player who did not bust earlier wins his or her bet. If the dealer does not bust, then the dealer’s total is compared to each player’s. For any player whose total is greater than the dealer’s, he or she wins money (in the amount that was bet). For any player whose total is less than the dealer’s, he or she loses money. No money is exchanged in the event of a tie. Players make their bets. Players are dealt 2 cards. Dealer is dealt 2 cards where the second card is hidden from the players. The objective of the game is to have a higher point total than the dealer (but no more than 21, anything over 21 is an automatic loss called a bust) — if you beat the dealer in this way, you win from the casino what you bet (you also win if the dealer busts). Aces can be worth either 1 or 11; every other card is worth its face amount (face cards are worth 10). An initial 2 card hand composed of an ace and a face card is called a blackjack and is the best possible hand. After the first round of dealing, each player has the option to hit (receive more cards) or stay (no more cards). If hitting results in the player busting (total going over 21), then his or her bet is lost. After all the players are done hitting/staying, the dealer flips over his hidden card. If the dealer’s total is less than 17, then he or she needs to hit (receive a new card). This process repeats until the dealer’s hand either totals to 17 or more or busts (goes above 21). After the dealer is done, the final results are decided — if the dealer busts, then any player who did not bust earlier wins his or her bet. If the dealer does not bust, then the dealer’s total is compared to each player’s. For any player whose total is greater than the dealer’s, he or she wins money (in the amount that was bet). For any player whose total is less than the dealer’s, he or she loses money. No money is exchanged in the event of a tie. If you would like to read up more on blackjack rules, check out this website. Time to start coding! You can find the code in its entirety on my GitHub here. It probably would have been a good idea to use object oriented programming. But at this point, I am not yet used to writing code in that way. I will probably revise my code at some point in the future to be object oriented; but that is a project for another day. To start, let’s get our input statements out of the way: import numpy as npimport pandas as pdimport randomimport matplotlib.pyplot as pltimport seaborn as sns Now let’s make a few functions to help us out. First, we need a function that creates a new deck of cards for us to play with. The make_decks function does just that — it adds four of each card type (ace, 2, 3, 4, etc.) to the list new_deck, shuffles new_deck, and returns the newly created list (deck) for us to play with. Also note that we can specify via num_decks how many decks we want the function to create. # Make a deckdef make_decks(num_decks, card_types): new_deck = [] for i in range(num_decks): for j in range(4): new_deck.extend(card_types) random.shuffle(new_deck) return new_deck We also need a function that can add up the value of the cards in our hand. It is slightly more complicated than simple summation because aces can be worth either 1 or 11, depending on whichever is most advantageous to its holder. So our function first tallies up the value of each non-ace card in the hand (I represent all face cards with the number 10 as they are all functionally the same in blackjack). Then it counts up the number of aces. Finally, it determines how much each ace should be worth depending on the value of the rest of your cards. Corrections: In my previous version of the code below, there was an error. To fix it, I added the helper function ace_values which takes as input the number of aces in your hand as an integer and outputs a list of unique values that your aces could be worth. Figuring out the permutations (and their sums) for a given number of aces was more work than I thought and I needed to write the following 2 helper functions to get it done (fore more details, please refer to my comments in the following code block): # This function lists out all permutations of ace values in the# array sum_array.# For example, if you have 2 aces, there are 4 permutations:# [[1,1], [1,11], [11,1], [11,11]]# These permutations lead to 3 unique sums: [2, 12, 22]# Of these 3, only 2 are <=21 so they are returned: [2, 12]def get_ace_values(temp_list): sum_array = np.zeros((2**len(temp_list), len(temp_list))) # This loop gets the permutations for i in range(len(temp_list)): n = len(temp_list) - i half_len = int(2**n * 0.5) for rep in range(int(sum_array.shape[0]/half_len/2)): sum_array[rep*2**n : rep*2**n+half_len, i]=1 sum_array[rep*2**n+half_len : rep*2**n+half_len*2, i]=11 # Only return values that are valid (<=21) return list(set([int(s) for s in np.sum(sum_array, axis=1)\ if s<=21]))# Convert num_aces, an int to a list of lists# For example if num_aces=2, the output should be [[1,11],[1,11]]# I require this format for the get_ace_values functiondef ace_values(num_aces): temp_list = [] for i in range(num_aces): temp_list.append([1,11]) return get_ace_values(temp_list) The above two functions can now be used by the function total_up, which like I mentioned above, calculates the value of the cards in our hand (including the correct handling of any aces): # Total up value of handdef total_up(hand): aces = 0 total = 0 for card in hand: if card != 'A': total += card else: aces += 1 # Call function ace_values to produce list of possible values # for aces in hand ace_value_list = ace_values(aces) final_totals = [i+total for i in ace_value_list if i+total<=21] if final_totals == []: return min(ace_value_list) + total else: return max(final_totals) Now that our helper functions are out of the way, let’s move on to the main loop. First, I define my key variables: stacks is the number of card stacks (where each card stack can be one or more decks) we will simulate. players is the number of players in each simulated game. num_decks is the number of decks in each stack. card_types is a list of all 13 card types. stacks = 50000players = 1num_decks = 1card_types = ['A',2,3,4,5,6,7,8,9,10,10,10,10] Now begins the main loops of our simulator. There are two: A for loop that iterates through the 50,000 stacks of cards that we want to simulate.A while loop, that for each stack of cards, plays blackjack until there are 20 or fewer cards in the stack. At that point it moves onto the next stack. A for loop that iterates through the 50,000 stacks of cards that we want to simulate. A while loop, that for each stack of cards, plays blackjack until there are 20 or fewer cards in the stack. At that point it moves onto the next stack. The numpy array, curr_player_results, is an important variable where I store the game result for each player — 1 for a win, 0 for a tie, and -1 for a loss. Each element in this array corresponds to one player at the blackjack table. Within the while loop, we deal a card to each player and then the dealer (where the Python comment says “Deal FIRST card”), and then we do it again so that everyone has 2 cards. In order to deal the cards, I take advantage of the pop function with an input of 0 — this returns the first element of a list while simultaneously removing it from that list (perfect for dealing cards from a stack). When the number of cards left in the dealer’s stack drops to 20 or below, a new stack of cards is used to replace the old one (moves to the next iteration of our for loop). for stack in range(stacks): blackjack = set(['A',10]) dealer_cards = make_decks(num_decks, card_types) while len(dealer_cards) > 20: curr_player_results = np.zeros((1,players)) dealer_hand = [] player_hands = [[] for player in range(players)] # Deal FIRST card for player, hand in enumerate(player_hands): player_hands[player].append(dealer_cards.pop(0)) dealer_hand.append(dealer_cards.pop(0)) # Deal SECOND card for player, hand in enumerate(player_hands): player_hands[player].append(dealer_cards.pop(0)) dealer_hand.append(dealer_cards.pop(0)) Next the dealer checks if he or she has a blackjack (an ace and a 10). Notice that in the previous code block, I defined blackjack as a set that includes an ace and a 10. If the dealer has a blackjack, then the players lose (and get assigned a -1 in curr_player_results) unless they too have a blackjack (in which case it is a tie). # Dealer checks for 21 if set(dealer_hand) == blackjack: for player in range(players): if set(player_hands[player]) != blackjack: curr_player_results[0,player] = -1 else: curr_player_results[0,player] = 0 If the dealer does not have a blackjack, then play continues. The players do their own blackjack checks — if they have one, they win (in some casinos blackjack pays 1.5 to 1, in other words if your bet was $100 then you win $150). I record a win by setting the element corresponding to that player in the array curr_player_results to 1. For the players without blackjack, they now have the option to hit, stay, etc. For this simulation, my objective was to capture all kinds of player decisions — smart ones, lucky ones, and stupid ones. So I based the decision for the player on a coin flip (if random.random() generates a value higher than 0.5 the player hits, otherwise the player stays). Deciding via coin flip might sound silly, but by making the hit/stay decision uncorrelated to what is actually happening in the game, we can observe all types of situations and ultimately generate a rich dataset for analysis. I am not trying to figure out the optimal strategy right this instance. Rather, I want to use this simulator to generate training data, with which I can eventually train a neural network to play blackjack optimally (in a future post). For Python, the \ character denotes line continuation and can be used to format extra long lines of code for better readability — you will see me use it in the following code block. else: for player in range(players): # Players check for 21 if set(player_hands[player]) == blackjack: curr_player_results[0,player] = 1 else: # Hit randomly, check for busts while (random.random() >= 0.5) and \ (total_up(player_hands[player]) <= 11): player_hands[player].append] (dealer_cards.pop(0)) if total_up(player_hands[player]) > 21: curr_player_results[0,player] = -1 break In the final section of our loop (almost there!), it’s the dealer’s turn. The dealer must hit until either he or she busts or has a hand that sums to at least 17. So the while loop deals cards to the dealer until 17 is reached, then we check if our dealer busted. If a dealer bust occurs, then every player that has not already lost (via busting) wins and we record a 1 for them in curr_player_results. # Dealer hits based on the rules while total_up(dealer_hand) < 17: dealer_hand.append(dealer_cards.pop(0)) # Compare dealer hand to players hand # but first check if dealer busted if total_up(dealer_hand) > 21: for player in range(players): if curr_player_results[0,player] != -1: curr_player_results[0,player] = 1 If the dealer does not bust, then each player compares his or her hand to the dealer’s — the higher hand wins. else: for player in range(players): if total_up(player_hands[player]) > \ total_up(dealer_hand): if total_up(player_hands[player]) <= 21: curr_player_results[0,player] = 1 elif total_up(player_hands[player]) == \ total_up(dealer_hand): curr_player_results[0,player] = 0 else: curr_player_results[0,player] = -1 Finally, at the conclusion of each blackjack game, we append the game results along with other variables that we care about to the lists that we will use to track our overall simulation results: # Track features dealer_card_feature.append(dealer_hand[0]) player_card_feature.append(player_hands) player_results.append(list(curr_player_results[0])) Nice, we can examine some results now. I ran the simulator for 50,000 decks. With this many decks being used, there ended up being: 312,459 blackjack games played. The player lost in 199,403 of the games (64% of the time). The player won in 99,324 of the games (32% of the time). The player tied in 13,732 of the games (4% of the time). We can take a look at how the win/tie probability (the probability of not losing money to the casino) changes due to key observable factors. For example, here is the win/tie probability for all the possible dealer cards (recall that players can only see one of the dealer’s cards when they are deciding what to do): From 2 to 6, the probability of win/tie increases. But then after 6, the probability declines dramatically. That’s interesting. Let’s think about why this occurs: If the dealer is showing a low card, then all things equal it is more likely that he has a lower total hand value — which is easier for the players to beat. This partially explains why the probabilities from 2 to 6 are on average higher than those from 7 to ace. Also, remember the rule for the dealer — if his total is less than 17, he must hit. And if he must hit, there is a decent chance that he will bust. This explains why the probability increases from 2 to 6. Think of it this way — what’s the most common card value? It’s 10 because there are 16 of them per each 52 card deck (four 10 cards, Jacks, Queens, and Kings). So if the dealer is showing a 6, (assuming we are not card counting) the most likely preliminary total for our dealer is 16. Since 16 is less than 17, he must hit. And there are many cards that could cause him to bust — anything worth 6 or more. The same logic holds true if the dealer is showing a 5, just that there is one fewer card that would cause him to bust (has to be 7 or more now). Now let’s think what about what happens when the dealer is showing a 7. In this case, odds are that the other hidden card is worth 10. Then the players who have 16 or less will feel compelled to hit. If they don’t, the probability of losing is material. But if they do hit, then they face a high probability of busting (due to all the 10s). That, in a nutshell, is the advantage that casinos hold over blackjack players — by hiding one of the dealer’s cards while the players act (and forcing the players to act before the dealer), casinos force blackjack players to assume the worst and expose themselves to the risk of busting (which are significant). So if you are at a casino and the hand you are dealt totals somewhere between 12 and 16, good luck to you — because you have become the casino’s mark and the odds are now stacked heavily against you. Let’s take a look at how the player’s initial hand value (the value of his or her initial two cards) affects his or her win/tie probability: As expected, the win/tie probability is lowest for initial player hand values between 12 and 16. These are the players that are frequently forced into the lose-lose situation of “if I hit I bust, if I stay I lose”. It also makes sense why initial player hand values of 4 and 5 have the next lowest probabilities. Let’s say you have a 5, then you need to hit (there is no reason not to) — but if you do hit, then the most likely result is that your hand now totals 15. And now you’ve fallen into the same dilemma as the players whose initial hands totaled between 12 and 16 (where if you hit, your next card is likely to cause you to bust). Now that we’ve explored the risks of blackjack, what’s next? In an upcoming post, I will use the training data that I generated above to train a neural network to play blackjack. That way I can examine what the machine chooses as the optimal strategy. But for today, let’s see if we can use a simple heuristic to improve our odds. Recall two things: A major disadvantage that players face is that they are forced to act first (and face the risk of busting before the dealer). So the casino’s strategy is to force the players to act under uncertainty in hopes that they will hit and bust. The player in our simulator chooses to hit or stay based on a coin flip regardless of the value of his or her hand (unless he or she is at 21). So even if he or she is at 20, there is still a 50% chance of hitting. So let’s see whether we can improve our odds merely by choosing to hit only when we know there is zero chance of busting. So instead of a coin flip, our new decision rule is to keep hitting only if our total hand value is 11 or less. It’s not the optimal strategy I know, but it is simple. And because it prevents us from ever busting, we have effectively shifted the risk of busting from ourselves to the dealer/casino. The following chart compares our new “smart” strategy (in blue) to our original strategy (the coin flip, in red): Wow, the simple decision to never risk busting improves our odds of winning across the board. While the old trends are still there, no matter what card the dealer shows, our probability of not losing money has increased. Let’s take a look at how the win/tie probabilities of our new strategy look when we bucket by our initial hand value: It’s more clear what is going on from looking at this plot. We have improved our probability of winning for all initial hand values besides 12 through 16. Those hand values are relatively unaffected because by choosing to stay (in order to eliminate the risk of busting), we make it easier for the dealer to beat our hand (because the dealer can only stop hitting when he or she reaches a hand value of 17 or more). But for all other hand values, it looks like our strategy of avoiding busts is pretty helpful. I hope you enjoyed reading, and stay tuned for the next post where we see if a neural network can beat our naive strategy. Cheers and remember — NEVER bet what you cannot afford to lose! A selection of my recent posts that I hope you will check out: Is Your Company Truly Data Driven? Are Data Scientists at Risk of Automation How Much Do Data Scientists Make? How Much Do Data Scientists Make Part 2 How Much Do Software Engineers Make? A Better Way to Skill Up
[ { "code": null, "e": 397, "s": 172, "text": "This post is in NO way an attempt to promote blackjack or the act of gambling. Any time you gamble at a casino, the odds are stacked against you — and over time you WILL lose money. Don’t risk what you cannot afford to lose!" }, { "code": null, "e": 622, "s": 397, "text": "Corrections: I realized (thanks to a friendly tip from @DonBeham) that under certain conditions, my total_up function was handling multiple aces incorrectly. I have updated both the code below and on my GitHub. My apologies!" }, { "code": null, "e": 964, "s": 622, "text": "I haven’t coded anything for the blog lately so I wanted to do a programming related post. One of the classic applications of probability and statistics is the study of games of chance (gambling). Games of chance (card games, dice games, etc.) are a favorite of statisticians because they exhibit both randomness and a certain inevitability:" }, { "code": null, "e": 1032, "s": 964, "text": "Random in that you don’t know what the result will be game to game." }, { "code": null, "e": 1124, "s": 1032, "text": "And inevitable in that you know what the average result of a large number of games will be." }, { "code": null, "e": 1392, "s": 1124, "text": "Today, we will study blackjack by writing up a blackjack simulator in Python, simulating a bunch of games, and then studying how our player did. I will assume some basic familiarity with the game of Blackjack, but here is a quick refresher for how the game is played:" }, { "code": null, "e": 2921, "s": 1392, "text": "Players make their bets.Players are dealt 2 cards.Dealer is dealt 2 cards where the second card is hidden from the players.The objective of the game is to have a higher point total than the dealer (but no more than 21, anything over 21 is an automatic loss called a bust) — if you beat the dealer in this way, you win from the casino what you bet (you also win if the dealer busts). Aces can be worth either 1 or 11; every other card is worth its face amount (face cards are worth 10).An initial 2 card hand composed of an ace and a face card is called a blackjack and is the best possible hand.After the first round of dealing, each player has the option to hit (receive more cards) or stay (no more cards). If hitting results in the player busting (total going over 21), then his or her bet is lost.After all the players are done hitting/staying, the dealer flips over his hidden card. If the dealer’s total is less than 17, then he or she needs to hit (receive a new card). This process repeats until the dealer’s hand either totals to 17 or more or busts (goes above 21).After the dealer is done, the final results are decided — if the dealer busts, then any player who did not bust earlier wins his or her bet. If the dealer does not bust, then the dealer’s total is compared to each player’s. For any player whose total is greater than the dealer’s, he or she wins money (in the amount that was bet). For any player whose total is less than the dealer’s, he or she loses money. No money is exchanged in the event of a tie." }, { "code": null, "e": 2946, "s": 2921, "text": "Players make their bets." }, { "code": null, "e": 2973, "s": 2946, "text": "Players are dealt 2 cards." }, { "code": null, "e": 3047, "s": 2973, "text": "Dealer is dealt 2 cards where the second card is hidden from the players." }, { "code": null, "e": 3410, "s": 3047, "text": "The objective of the game is to have a higher point total than the dealer (but no more than 21, anything over 21 is an automatic loss called a bust) — if you beat the dealer in this way, you win from the casino what you bet (you also win if the dealer busts). Aces can be worth either 1 or 11; every other card is worth its face amount (face cards are worth 10)." }, { "code": null, "e": 3521, "s": 3410, "text": "An initial 2 card hand composed of an ace and a face card is called a blackjack and is the best possible hand." }, { "code": null, "e": 3728, "s": 3521, "text": "After the first round of dealing, each player has the option to hit (receive more cards) or stay (no more cards). If hitting results in the player busting (total going over 21), then his or her bet is lost." }, { "code": null, "e": 4003, "s": 3728, "text": "After all the players are done hitting/staying, the dealer flips over his hidden card. If the dealer’s total is less than 17, then he or she needs to hit (receive a new card). This process repeats until the dealer’s hand either totals to 17 or more or busts (goes above 21)." }, { "code": null, "e": 4457, "s": 4003, "text": "After the dealer is done, the final results are decided — if the dealer busts, then any player who did not bust earlier wins his or her bet. If the dealer does not bust, then the dealer’s total is compared to each player’s. For any player whose total is greater than the dealer’s, he or she wins money (in the amount that was bet). For any player whose total is less than the dealer’s, he or she loses money. No money is exchanged in the event of a tie." }, { "code": null, "e": 4557, "s": 4457, "text": "If you would like to read up more on blackjack rules, check out this website. Time to start coding!" }, { "code": null, "e": 4614, "s": 4557, "text": "You can find the code in its entirety on my GitHub here." }, { "code": null, "e": 4877, "s": 4614, "text": "It probably would have been a good idea to use object oriented programming. But at this point, I am not yet used to writing code in that way. I will probably revise my code at some point in the future to be object oriented; but that is a project for another day." }, { "code": null, "e": 4934, "s": 4877, "text": "To start, let’s get our input statements out of the way:" }, { "code": null, "e": 5037, "s": 4934, "text": "import numpy as npimport pandas as pdimport randomimport matplotlib.pyplot as pltimport seaborn as sns" }, { "code": null, "e": 5452, "s": 5037, "text": "Now let’s make a few functions to help us out. First, we need a function that creates a new deck of cards for us to play with. The make_decks function does just that — it adds four of each card type (ace, 2, 3, 4, etc.) to the list new_deck, shuffles new_deck, and returns the newly created list (deck) for us to play with. Also note that we can specify via num_decks how many decks we want the function to create." }, { "code": null, "e": 5663, "s": 5452, "text": "# Make a deckdef make_decks(num_decks, card_types): new_deck = [] for i in range(num_decks): for j in range(4): new_deck.extend(card_types) random.shuffle(new_deck) return new_deck" }, { "code": null, "e": 6215, "s": 5663, "text": "We also need a function that can add up the value of the cards in our hand. It is slightly more complicated than simple summation because aces can be worth either 1 or 11, depending on whichever is most advantageous to its holder. So our function first tallies up the value of each non-ace card in the hand (I represent all face cards with the number 10 as they are all functionally the same in blackjack). Then it counts up the number of aces. Finally, it determines how much each ace should be worth depending on the value of the rest of your cards." }, { "code": null, "e": 6725, "s": 6215, "text": "Corrections: In my previous version of the code below, there was an error. To fix it, I added the helper function ace_values which takes as input the number of aces in your hand as an integer and outputs a list of unique values that your aces could be worth. Figuring out the permutations (and their sums) for a given number of aces was more work than I thought and I needed to write the following 2 helper functions to get it done (fore more details, please refer to my comments in the following code block):" }, { "code": null, "e": 7877, "s": 6725, "text": "# This function lists out all permutations of ace values in the# array sum_array.# For example, if you have 2 aces, there are 4 permutations:# [[1,1], [1,11], [11,1], [11,11]]# These permutations lead to 3 unique sums: [2, 12, 22]# Of these 3, only 2 are <=21 so they are returned: [2, 12]def get_ace_values(temp_list): sum_array = np.zeros((2**len(temp_list), len(temp_list))) # This loop gets the permutations for i in range(len(temp_list)): n = len(temp_list) - i half_len = int(2**n * 0.5) for rep in range(int(sum_array.shape[0]/half_len/2)): sum_array[rep*2**n : rep*2**n+half_len, i]=1 sum_array[rep*2**n+half_len : rep*2**n+half_len*2, i]=11 # Only return values that are valid (<=21) return list(set([int(s) for s in np.sum(sum_array, axis=1)\\ if s<=21]))# Convert num_aces, an int to a list of lists# For example if num_aces=2, the output should be [[1,11],[1,11]]# I require this format for the get_ace_values functiondef ace_values(num_aces): temp_list = [] for i in range(num_aces): temp_list.append([1,11]) return get_ace_values(temp_list)" }, { "code": null, "e": 8065, "s": 7877, "text": "The above two functions can now be used by the function total_up, which like I mentioned above, calculates the value of the cards in our hand (including the correct handling of any aces):" }, { "code": null, "e": 8549, "s": 8065, "text": "# Total up value of handdef total_up(hand): aces = 0 total = 0 for card in hand: if card != 'A': total += card else: aces += 1 # Call function ace_values to produce list of possible values # for aces in hand ace_value_list = ace_values(aces) final_totals = [i+total for i in ace_value_list if i+total<=21] if final_totals == []: return min(ace_value_list) + total else: return max(final_totals)" }, { "code": null, "e": 8665, "s": 8549, "text": "Now that our helper functions are out of the way, let’s move on to the main loop. First, I define my key variables:" }, { "code": null, "e": 8768, "s": 8665, "text": "stacks is the number of card stacks (where each card stack can be one or more decks) we will simulate." }, { "code": null, "e": 8825, "s": 8768, "text": "players is the number of players in each simulated game." }, { "code": null, "e": 8873, "s": 8825, "text": "num_decks is the number of decks in each stack." }, { "code": null, "e": 8916, "s": 8873, "text": "card_types is a list of all 13 card types." }, { "code": null, "e": 9001, "s": 8916, "text": "stacks = 50000players = 1num_decks = 1card_types = ['A',2,3,4,5,6,7,8,9,10,10,10,10]" }, { "code": null, "e": 9060, "s": 9001, "text": "Now begins the main loops of our simulator. There are two:" }, { "code": null, "e": 9297, "s": 9060, "text": "A for loop that iterates through the 50,000 stacks of cards that we want to simulate.A while loop, that for each stack of cards, plays blackjack until there are 20 or fewer cards in the stack. At that point it moves onto the next stack." }, { "code": null, "e": 9383, "s": 9297, "text": "A for loop that iterates through the 50,000 stacks of cards that we want to simulate." }, { "code": null, "e": 9535, "s": 9383, "text": "A while loop, that for each stack of cards, plays blackjack until there are 20 or fewer cards in the stack. At that point it moves onto the next stack." }, { "code": null, "e": 9768, "s": 9535, "text": "The numpy array, curr_player_results, is an important variable where I store the game result for each player — 1 for a win, 0 for a tie, and -1 for a loss. Each element in this array corresponds to one player at the blackjack table." }, { "code": null, "e": 10336, "s": 9768, "text": "Within the while loop, we deal a card to each player and then the dealer (where the Python comment says “Deal FIRST card”), and then we do it again so that everyone has 2 cards. In order to deal the cards, I take advantage of the pop function with an input of 0 — this returns the first element of a list while simultaneously removing it from that list (perfect for dealing cards from a stack). When the number of cards left in the dealer’s stack drops to 20 or below, a new stack of cards is used to replace the old one (moves to the next iteration of our for loop)." }, { "code": null, "e": 10994, "s": 10336, "text": "for stack in range(stacks): blackjack = set(['A',10]) dealer_cards = make_decks(num_decks, card_types) while len(dealer_cards) > 20: curr_player_results = np.zeros((1,players)) dealer_hand = [] player_hands = [[] for player in range(players)] # Deal FIRST card for player, hand in enumerate(player_hands): player_hands[player].append(dealer_cards.pop(0)) dealer_hand.append(dealer_cards.pop(0)) # Deal SECOND card for player, hand in enumerate(player_hands): player_hands[player].append(dealer_cards.pop(0)) dealer_hand.append(dealer_cards.pop(0))" }, { "code": null, "e": 11165, "s": 10994, "text": "Next the dealer checks if he or she has a blackjack (an ace and a 10). Notice that in the previous code block, I defined blackjack as a set that includes an ace and a 10." }, { "code": null, "e": 11327, "s": 11165, "text": "If the dealer has a blackjack, then the players lose (and get assigned a -1 in curr_player_results) unless they too have a blackjack (in which case it is a tie)." }, { "code": null, "e": 11626, "s": 11327, "text": " # Dealer checks for 21 if set(dealer_hand) == blackjack: for player in range(players): if set(player_hands[player]) != blackjack: curr_player_results[0,player] = -1 else: curr_player_results[0,player] = 0" }, { "code": null, "e": 11963, "s": 11626, "text": "If the dealer does not have a blackjack, then play continues. The players do their own blackjack checks — if they have one, they win (in some casinos blackjack pays 1.5 to 1, in other words if your bet was $100 then you win $150). I record a win by setting the element corresponding to that player in the array curr_player_results to 1." }, { "code": null, "e": 12318, "s": 11963, "text": "For the players without blackjack, they now have the option to hit, stay, etc. For this simulation, my objective was to capture all kinds of player decisions — smart ones, lucky ones, and stupid ones. So I based the decision for the player on a coin flip (if random.random() generates a value higher than 0.5 the player hits, otherwise the player stays)." }, { "code": null, "e": 12544, "s": 12318, "text": "Deciding via coin flip might sound silly, but by making the hit/stay decision uncorrelated to what is actually happening in the game, we can observe all types of situations and ultimately generate a rich dataset for analysis." }, { "code": null, "e": 12779, "s": 12544, "text": "I am not trying to figure out the optimal strategy right this instance. Rather, I want to use this simulator to generate training data, with which I can eventually train a neural network to play blackjack optimally (in a future post)." }, { "code": null, "e": 12961, "s": 12779, "text": "For Python, the \\ character denotes line continuation and can be used to format extra long lines of code for better readability — you will see me use it in the following code block." }, { "code": null, "e": 13607, "s": 12961, "text": " else: for player in range(players): # Players check for 21 if set(player_hands[player]) == blackjack: curr_player_results[0,player] = 1 else: # Hit randomly, check for busts while (random.random() >= 0.5) and \\ (total_up(player_hands[player]) <= 11): player_hands[player].append] (dealer_cards.pop(0)) if total_up(player_hands[player]) > 21: curr_player_results[0,player] = -1 break" }, { "code": null, "e": 14010, "s": 13607, "text": "In the final section of our loop (almost there!), it’s the dealer’s turn. The dealer must hit until either he or she busts or has a hand that sums to at least 17. So the while loop deals cards to the dealer until 17 is reached, then we check if our dealer busted. If a dealer bust occurs, then every player that has not already lost (via busting) wins and we record a 1 for them in curr_player_results." }, { "code": null, "e": 14418, "s": 14010, "text": " # Dealer hits based on the rules while total_up(dealer_hand) < 17: dealer_hand.append(dealer_cards.pop(0)) # Compare dealer hand to players hand # but first check if dealer busted if total_up(dealer_hand) > 21: for player in range(players): if curr_player_results[0,player] != -1: curr_player_results[0,player] = 1" }, { "code": null, "e": 14529, "s": 14418, "text": "If the dealer does not bust, then each player compares his or her hand to the dealer’s — the higher hand wins." }, { "code": null, "e": 15014, "s": 14529, "text": " else: for player in range(players): if total_up(player_hands[player]) > \\ total_up(dealer_hand): if total_up(player_hands[player]) <= 21: curr_player_results[0,player] = 1 elif total_up(player_hands[player]) == \\ total_up(dealer_hand): curr_player_results[0,player] = 0 else: curr_player_results[0,player] = -1" }, { "code": null, "e": 15209, "s": 15014, "text": "Finally, at the conclusion of each blackjack game, we append the game results along with other variables that we care about to the lists that we will use to track our overall simulation results:" }, { "code": null, "e": 15391, "s": 15209, "text": " # Track features dealer_card_feature.append(dealer_hand[0]) player_card_feature.append(player_hands) player_results.append(list(curr_player_results[0]))" }, { "code": null, "e": 15523, "s": 15391, "text": "Nice, we can examine some results now. I ran the simulator for 50,000 decks. With this many decks being used, there ended up being:" }, { "code": null, "e": 15555, "s": 15523, "text": "312,459 blackjack games played." }, { "code": null, "e": 15614, "s": 15555, "text": "The player lost in 199,403 of the games (64% of the time)." }, { "code": null, "e": 15671, "s": 15614, "text": "The player won in 99,324 of the games (32% of the time)." }, { "code": null, "e": 15728, "s": 15671, "text": "The player tied in 13,732 of the games (4% of the time)." }, { "code": null, "e": 16044, "s": 15728, "text": "We can take a look at how the win/tie probability (the probability of not losing money to the casino) changes due to key observable factors. For example, here is the win/tie probability for all the possible dealer cards (recall that players can only see one of the dealer’s cards when they are deciding what to do):" }, { "code": null, "e": 16207, "s": 16044, "text": "From 2 to 6, the probability of win/tie increases. But then after 6, the probability declines dramatically. That’s interesting. Let’s think about why this occurs:" }, { "code": null, "e": 16470, "s": 16207, "text": "If the dealer is showing a low card, then all things equal it is more likely that he has a lower total hand value — which is easier for the players to beat. This partially explains why the probabilities from 2 to 6 are on average higher than those from 7 to ace." }, { "code": null, "e": 17227, "s": 16470, "text": "Also, remember the rule for the dealer — if his total is less than 17, he must hit. And if he must hit, there is a decent chance that he will bust. This explains why the probability increases from 2 to 6. Think of it this way — what’s the most common card value? It’s 10 because there are 16 of them per each 52 card deck (four 10 cards, Jacks, Queens, and Kings). So if the dealer is showing a 6, (assuming we are not card counting) the most likely preliminary total for our dealer is 16. Since 16 is less than 17, he must hit. And there are many cards that could cause him to bust — anything worth 6 or more. The same logic holds true if the dealer is showing a 5, just that there is one fewer card that would cause him to bust (has to be 7 or more now)." }, { "code": null, "e": 17568, "s": 17227, "text": "Now let’s think what about what happens when the dealer is showing a 7. In this case, odds are that the other hidden card is worth 10. Then the players who have 16 or less will feel compelled to hit. If they don’t, the probability of losing is material. But if they do hit, then they face a high probability of busting (due to all the 10s)." }, { "code": null, "e": 17881, "s": 17568, "text": "That, in a nutshell, is the advantage that casinos hold over blackjack players — by hiding one of the dealer’s cards while the players act (and forcing the players to act before the dealer), casinos force blackjack players to assume the worst and expose themselves to the risk of busting (which are significant)." }, { "code": null, "e": 18222, "s": 17881, "text": "So if you are at a casino and the hand you are dealt totals somewhere between 12 and 16, good luck to you — because you have become the casino’s mark and the odds are now stacked heavily against you. Let’s take a look at how the player’s initial hand value (the value of his or her initial two cards) affects his or her win/tie probability:" }, { "code": null, "e": 18862, "s": 18222, "text": "As expected, the win/tie probability is lowest for initial player hand values between 12 and 16. These are the players that are frequently forced into the lose-lose situation of “if I hit I bust, if I stay I lose”. It also makes sense why initial player hand values of 4 and 5 have the next lowest probabilities. Let’s say you have a 5, then you need to hit (there is no reason not to) — but if you do hit, then the most likely result is that your hand now totals 15. And now you’ve fallen into the same dilemma as the players whose initial hands totaled between 12 and 16 (where if you hit, your next card is likely to cause you to bust)." }, { "code": null, "e": 19114, "s": 18862, "text": "Now that we’ve explored the risks of blackjack, what’s next? In an upcoming post, I will use the training data that I generated above to train a neural network to play blackjack. That way I can examine what the machine chooses as the optimal strategy." }, { "code": null, "e": 19212, "s": 19114, "text": "But for today, let’s see if we can use a simple heuristic to improve our odds. Recall two things:" }, { "code": null, "e": 19450, "s": 19212, "text": "A major disadvantage that players face is that they are forced to act first (and face the risk of busting before the dealer). So the casino’s strategy is to force the players to act under uncertainty in hopes that they will hit and bust." }, { "code": null, "e": 19665, "s": 19450, "text": "The player in our simulator chooses to hit or stay based on a coin flip regardless of the value of his or her hand (unless he or she is at 21). So even if he or she is at 20, there is still a 50% chance of hitting." }, { "code": null, "e": 19899, "s": 19665, "text": "So let’s see whether we can improve our odds merely by choosing to hit only when we know there is zero chance of busting. So instead of a coin flip, our new decision rule is to keep hitting only if our total hand value is 11 or less." }, { "code": null, "e": 20086, "s": 19899, "text": "It’s not the optimal strategy I know, but it is simple. And because it prevents us from ever busting, we have effectively shifted the risk of busting from ourselves to the dealer/casino." }, { "code": null, "e": 20200, "s": 20086, "text": "The following chart compares our new “smart” strategy (in blue) to our original strategy (the coin flip, in red):" }, { "code": null, "e": 20421, "s": 20200, "text": "Wow, the simple decision to never risk busting improves our odds of winning across the board. While the old trends are still there, no matter what card the dealer shows, our probability of not losing money has increased." }, { "code": null, "e": 20539, "s": 20421, "text": "Let’s take a look at how the win/tie probabilities of our new strategy look when we bucket by our initial hand value:" }, { "code": null, "e": 20955, "s": 20539, "text": "It’s more clear what is going on from looking at this plot. We have improved our probability of winning for all initial hand values besides 12 through 16. Those hand values are relatively unaffected because by choosing to stay (in order to eliminate the risk of busting), we make it easier for the dealer to beat our hand (because the dealer can only stop hitting when he or she reaches a hand value of 17 or more)." }, { "code": null, "e": 21050, "s": 20955, "text": "But for all other hand values, it looks like our strategy of avoiding busts is pretty helpful." }, { "code": null, "e": 21237, "s": 21050, "text": "I hope you enjoyed reading, and stay tuned for the next post where we see if a neural network can beat our naive strategy. Cheers and remember — NEVER bet what you cannot afford to lose!" }, { "code": null, "e": 21300, "s": 21237, "text": "A selection of my recent posts that I hope you will check out:" }, { "code": null, "e": 21335, "s": 21300, "text": "Is Your Company Truly Data Driven?" }, { "code": null, "e": 21377, "s": 21335, "text": "Are Data Scientists at Risk of Automation" }, { "code": null, "e": 21411, "s": 21377, "text": "How Much Do Data Scientists Make?" }, { "code": null, "e": 21451, "s": 21411, "text": "How Much Do Data Scientists Make Part 2" }, { "code": null, "e": 21488, "s": 21451, "text": "How Much Do Software Engineers Make?" } ]
How to find and sort files based on modification date and time in linux
While working with computers, we have a habit of saving a lot of information in our computers such as files, folders, etc. Normally desktop looks like a mess but the problem arises when users want to search a modified file on a particular date or time. There are simple commands which are available in Linux to search a modified file. This article describes “How to Find and Sort Files Based on Modification Date and Time in Linux”. The list command shows a list of files, directories, information about date and time of modification or access, permissions, size, owner, group etc. The below command shows the list of files along with format, sorts files based on modification time and newest file first. $ ls -lt The sample output should be like this – total 322428 drwxr-xr-x 3 linux linux 4096 Mar 8 13:59 Downloads drwxr-xr-x 6 linux linux 4096 Mar 3 14:34 Desktop lrwxrwxrwx 1 linux linux 37 Feb 27 13:25 PlayOnLinux's virtual drives -> /home/linux/.PlayOnLinux//wineprefix/ -rw-r--r-- 1 root root 70706 Feb 23 14:52 Selection_007.png -rw-r--r-- 1 root root 108159 Feb 23 14:49 root@linux: ~_005.png -rw-r--r-- 1 root root 145629 Feb 23 14:47 Workspace 1_004.png drwxr-xr-x 2 linux linux 4096 Feb 23 14:30 Pictures -rw-rw-r-- 1 linux linux 87631 Feb 19 14:08 account.png -rw-rw-r-- 1 linux linux 72172 Feb 19 14:07 network.png -rw-rw-r-- 1 linux linux 98362 Feb 19 14:05 sample1.png drwxr-xr-x 8 root root 4096 Feb 19 11:38 linux-dash drwxr-xr-x 2 linux linux 4096 Feb 19 11:08 Documents drwxr-xr-x 2 linux linux 4096 Feb 19 11:08 Music drwxr-xr-x 2 linux linux 4096 Feb 19 11:08 Public drwxr-xr-x 2 linux linux 4096 Feb 19 11:08 Templates drwxr-xr-x 2 linux linux 4096 Feb 19 11:08 Videos -rw-r--r-- 1 linux linux 8980 Feb 19 10:55 examples.desktop To get the list of all files based on last access time, use the following command- $ ls -ltu The sample output should be like this – total 322428 drwxr-xr-x 3 linux linux 4096 Mar 8 14:00 Downloads drwxr-xr-x 8 root root 4096 Mar 8 11:18 linux-dash -rw-r--r-- 1 linux linux 8980 Mar 8 11:18 examples.desktop -rw-r--r-- 1 root root 70706 Mar 8 11:18 Selection_007.png -rw-r--r-- 1 root root 108159 Mar 8 11:18 root@linux: ~_005.png -rw-r--r-- 1 root root 145629 Mar 8 11:18 Workspace 1_004.png lrwxrwxrwx 1 linux linux 37 Mar 8 11:18 PlayOnLinux's virtual drives -> /home/linux/.PlayOnLinux//wineprefix/ drwxr-xr-x 2 linux linux 4096 Mar 8 11:18 Public drwxr-xr-x 2 linux linux 4096 Mar 8 11:18 Documents drwxr-xr-x 2 linux linux 4096 Mar 8 11:18 Music drwxr-xr-x 2 linux linux 4096 Mar 8 11:18 Pictures drwxr-xr-x 2 linux linux 4096 Mar 8 11:18 Videos drwxr-xr-x 2 linux linux 4096 Mar 8 11:15 Templates drwxr-xr-x 6 linux linux 4096 Mar 8 11:15 Desktop To get the last modified files, use the following command – $ ls -ltc The sample output should be like this – total 322428 drwxr-xr-x 3 linux linux 4096 Mar 8 13:59 Downloads drwxr-xr-x 6 linux linux 4096 Mar 3 14:34 Desktop lrwxrwxrwx 1 linux linux 37 Feb 27 13:25 PlayOnLinux's virtual drives -> /home/linux/.PlayOnLinux//wineprefix/ -rw-r--r-- 1 root root 70706 Feb 23 14:52 Selection_007.png -rw-r--r-- 1 root root 108159 Feb 23 14:49 root@linux: ~_005.png -rw-r--r-- 1 root root 145629 Feb 23 14:47 Workspace 1_004.png drwxr-xr-x 2 linux linux 4096 Feb 23 14:30 Pictures -rw-rw-r-- 1 linux linux 87631 Feb 19 14:08 account.png -rw-rw-r-- 1 linux linux 72172 Feb 19 14:07 network.png -rw-rw-r-- 1 linux linux 98362 Feb 19 14:05 sample1.png drwxr-xr-x 8 root root 4096 Feb 19 11:38 linux-dash drwxr-xr-x 2 linux linux 4096 Feb 19 11:08 Documents drwxr-xr-x 2 linux linux 4096 Feb 19 11:08 Music drwxr-xr-x 2 linux linux 4096 Feb 19 11:08 Public drwxr-xr-x 2 linux linux 4096 Feb 19 11:08 Templates drwxr-xr-x 2 linux linux 4096 Feb 19 11:08 Videos -rw-r--r-- 1 linux linux 8980 Feb 19 10:55 examples.desktop This command sorts the output of ‘ls -l’ command based on 1th field of month. Use the following command – ls -l | sort -k1M The sample ouput should be like this – drwxr-xr-x 9 tutorialspoint 2000 4096 Feb 23 10:37 psensor-1.1.3 -rw-r--r-- 1 root root 108159 Feb 23 14:49 root@linux: ~_005.png -rw-r--r-- 1 root root 124850 Feb 23 14:52 root@linux: ~_006.png -rw-r--r-- 1 root root 145629 Feb 23 14:46 Workspace 1_004.png -rw-r--r-- 1 root root 145658 Feb 23 14:43 Workspace 1_003.png -rw-r--r-- 1 root root 146010 Feb 23 14:39 Workspace 1_002.png -rw-r--r-- 1 root root 178005 Feb 23 14:39 Workspace 1_001.png -rw-r--r-- 1 root root 200505 Aug 29 2015 Tutorialspoint ad-DADCpj8sFCE.mp3 -rw-r--r-- 1 root root 215 Mar 3 10:28 dead.letter ................ For more in-depth sorting, use the following commands- Find command is used to search and locate a list of files and directories based on conditions which are specified by the user. To find the sorted root files based on month, use the following command – # find / -type f -printf "\n%Ab %p" | head -n 11 The above command gives a complete list of top 11 entries which were accessed based on month. May /etc/newt/palette.ubuntu May /etc/newt/palette.original May /etc/ltrace.conf Mar /etc/pulse/daemon.conf Mar /etc/pulse/default.pa Jan /etc/pulse/system.pa Mar /etc/pulse/client.conf Mar /etc/gtk-3.0/settings.ini Jul /etc/gtk-3.0/im-multipress.conf Feb /etc/subgid- To find the sorted root files using the first key with month, use -k1M option as shown below – # find / -type f -printf "\n%Ab %p" | head -n 11 | sort -k1M The sample output should be like this – Jan /etc/pulse/system.pa Feb /etc/subgid- Mar /etc/gtk-3.0/settings.ini Mar /etc/pulse/client.conf Mar /etc/pulse/daemon.conf Mar /etc/pulse/default.pa May /etc/ltrace.conf May /etc/newt/palette.original May /etc/newt/palette.ubuntu Jul /etc/gtk-3.0/im-multipress.conf The above command has sorted according to the month. To find the sorted root files based on date, use the following command – # find / -type f -printf "\n%AD %AT %p" | head -n 11 The above command gives the result according to date as shown below – 05/14/13 22:26:41.0000000000 /etc/newt/palette.ubuntu 05/14/13 22:26:41.0000000000 /etc/newt/palette.original 05/10/14 05:20:35.0000000000 /etc/ltrace.conf 03/08/16 11:14:01.9113136790 /etc/pulse/daemon.conf 03/08/16 11:14:01.9193136790 /etc/pulse/default.pa 01/29/15 04:17:39.0000000000 /etc/pulse/system.pa 03/08/16 11:14:01.3433136590 /etc/pulse/client.conf 03/08/16 11:14:00.0873136140 /etc/gtk-3.0/settings.ini 07/01/15 08:44:19.0000000000 /etc/gtk-3.0/im-multipress.conf 02/22/16 10:49:09.0000000000 /etc/subgid- To find the sorted root files based on time, use the following command – # find / -type f -printf "\n%AT %p" | head -n 11 The sample output should be like this – 22:26:41.0000000000 /etc/newt/palette.ubuntu 22:26:41.0000000000 /etc/newt/palette.original 05:20:35.0000000000 /etc/ltrace.conf 11:14:01.9113136790 /etc/pulse/daemon.conf 11:14:01.9193136790 /etc/pulse/default.pa 04:17:39.0000000000 /etc/pulse/system.pa 11:14:01.3433136590 /etc/pulse/client.conf 11:14:00.0873136140 /etc/gtk-3.0/settings.ini 08:44:19.0000000000 /etc/gtk-3.0/im-multipress.conf 10:49:09.0000000000 /etc/subgid- Congratulations! Now, you know “How to Find and Sort Files Based on Modification Date and Time in Linux”. We’ll learn more about these types of commands in our next Linux post. Keep reading!
[ { "code": null, "e": 1495, "s": 1062, "text": "While working with computers, we have a habit of saving a lot of information in our computers such as files, folders, etc. Normally desktop looks like a mess but the problem arises when users want to search a modified file on a particular date or time. There are simple commands which are available in Linux to search a modified file. This article describes “How to Find and Sort Files Based on Modification Date and Time in Linux”." }, { "code": null, "e": 1767, "s": 1495, "text": "The list command shows a list of files, directories, information about date and time of modification or access, permissions, size, owner, group etc. The below command shows the list of files along with format, sorts files based on modification time and newest file first." }, { "code": null, "e": 1776, "s": 1767, "text": "$ ls -lt" }, { "code": null, "e": 1816, "s": 1776, "text": "The sample output should be like this –" }, { "code": null, "e": 2871, "s": 1816, "text": "total 322428\ndrwxr-xr-x 3 linux linux 4096 Mar 8 13:59 Downloads\ndrwxr-xr-x 6 linux linux 4096 Mar 3 14:34 Desktop\nlrwxrwxrwx 1 linux linux 37 Feb 27 13:25 PlayOnLinux's virtual drives -> /home/linux/.PlayOnLinux//wineprefix/\n-rw-r--r-- 1 root root 70706 Feb 23 14:52 Selection_007.png\n-rw-r--r-- 1 root root 108159 Feb 23 14:49 root@linux: ~_005.png\n-rw-r--r-- 1 root root 145629 Feb 23 14:47 Workspace 1_004.png\ndrwxr-xr-x 2 linux linux 4096 Feb 23 14:30 Pictures\n-rw-rw-r-- 1 linux linux 87631 Feb 19 14:08 account.png\n-rw-rw-r-- 1 linux linux 72172 Feb 19 14:07 network.png\n-rw-rw-r-- 1 linux linux 98362 Feb 19 14:05 sample1.png\ndrwxr-xr-x 8 root root 4096 Feb 19 11:38 linux-dash\ndrwxr-xr-x 2 linux linux 4096 Feb 19 11:08 Documents\ndrwxr-xr-x 2 linux linux 4096 Feb 19 11:08 Music\ndrwxr-xr-x 2 linux linux 4096 Feb 19 11:08 Public\ndrwxr-xr-x 2 linux linux 4096 Feb 19 11:08 Templates\ndrwxr-xr-x 2 linux linux 4096 Feb 19 11:08 Videos\n-rw-r--r-- 1 linux linux 8980 Feb 19 10:55 examples.desktop" }, { "code": null, "e": 2954, "s": 2871, "text": "To get the list of all files based on last access time, use the following command-" }, { "code": null, "e": 2964, "s": 2954, "text": "$ ls -ltu" }, { "code": null, "e": 3004, "s": 2964, "text": "The sample output should be like this –" }, { "code": null, "e": 3876, "s": 3004, "text": "total 322428\ndrwxr-xr-x 3 linux linux 4096 Mar 8 14:00 Downloads\ndrwxr-xr-x 8 root root 4096 Mar 8 11:18 linux-dash\n-rw-r--r-- 1 linux linux 8980 Mar 8 11:18 examples.desktop\n-rw-r--r-- 1 root root 70706 Mar 8 11:18 Selection_007.png\n-rw-r--r-- 1 root root 108159 Mar 8 11:18 root@linux: ~_005.png\n-rw-r--r-- 1 root root 145629 Mar 8 11:18 Workspace 1_004.png\nlrwxrwxrwx 1 linux linux 37 Mar 8 11:18 PlayOnLinux's virtual drives -> /home/linux/.PlayOnLinux//wineprefix/\ndrwxr-xr-x 2 linux linux 4096 Mar 8 11:18 Public\ndrwxr-xr-x 2 linux linux 4096 Mar 8 11:18 Documents\ndrwxr-xr-x 2 linux linux 4096 Mar 8 11:18 Music\ndrwxr-xr-x 2 linux linux 4096 Mar 8 11:18 Pictures\ndrwxr-xr-x 2 linux linux 4096 Mar 8 11:18 Videos\ndrwxr-xr-x 2 linux linux 4096 Mar 8 11:15 Templates\ndrwxr-xr-x 6 linux linux 4096 Mar 8 11:15 Desktop" }, { "code": null, "e": 3936, "s": 3876, "text": "To get the last modified files, use the following command –" }, { "code": null, "e": 3946, "s": 3936, "text": "$ ls -ltc" }, { "code": null, "e": 3986, "s": 3946, "text": "The sample output should be like this –" }, { "code": null, "e": 5037, "s": 3986, "text": "total 322428\ndrwxr-xr-x 3 linux linux 4096 Mar 8 13:59 Downloads\ndrwxr-xr-x 6 linux linux 4096 Mar 3 14:34 Desktop\nlrwxrwxrwx 1 linux linux 37 Feb 27 13:25 PlayOnLinux's virtual drives -> /home/linux/.PlayOnLinux//wineprefix/\n-rw-r--r-- 1 root root 70706 Feb 23 14:52 Selection_007.png\n-rw-r--r-- 1 root root 108159 Feb 23 14:49 root@linux: ~_005.png\n-rw-r--r-- 1 root root 145629 Feb 23 14:47 Workspace 1_004.png\ndrwxr-xr-x 2 linux linux 4096 Feb 23 14:30 Pictures\n-rw-rw-r-- 1 linux linux 87631 Feb 19 14:08 account.png\n-rw-rw-r-- 1 linux linux 72172 Feb 19 14:07 network.png\n-rw-rw-r-- 1 linux linux 98362 Feb 19 14:05 sample1.png\ndrwxr-xr-x 8 root root 4096 Feb 19 11:38 linux-dash\ndrwxr-xr-x 2 linux linux 4096 Feb 19 11:08 Documents\ndrwxr-xr-x 2 linux linux 4096 Feb 19 11:08 Music\ndrwxr-xr-x 2 linux linux 4096 Feb 19 11:08 Public\ndrwxr-xr-x 2 linux linux 4096 Feb 19 11:08 Templates\ndrwxr-xr-x 2 linux linux 4096 Feb 19 11:08 Videos\n-rw-r--r-- 1 linux linux 8980 Feb 19 10:55 examples.desktop" }, { "code": null, "e": 5115, "s": 5037, "text": "This command sorts the output of ‘ls -l’ command based on 1th field of month." }, { "code": null, "e": 5143, "s": 5115, "text": "Use the following command –" }, { "code": null, "e": 5161, "s": 5143, "text": "ls -l | sort -k1M" }, { "code": null, "e": 5200, "s": 5161, "text": "The sample ouput should be like this –" }, { "code": null, "e": 5815, "s": 5200, "text": "drwxr-xr-x 9 tutorialspoint 2000 4096 Feb 23 10:37 psensor-1.1.3\n-rw-r--r-- 1 root root 108159 Feb 23 14:49 root@linux: ~_005.png\n-rw-r--r-- 1 root root 124850 Feb 23 14:52 root@linux: ~_006.png\n-rw-r--r-- 1 root root 145629 Feb 23 14:46 Workspace 1_004.png\n-rw-r--r-- 1 root root 145658 Feb 23 14:43 Workspace 1_003.png\n-rw-r--r-- 1 root root 146010 Feb 23 14:39 Workspace 1_002.png\n-rw-r--r-- 1 root root 178005 Feb 23 14:39 Workspace 1_001.png\n-rw-r--r-- 1 root root 200505 Aug 29 2015 Tutorialspoint ad-DADCpj8sFCE.mp3\n-rw-r--r-- 1 root root 215 Mar 3 10:28 dead.letter\n................" }, { "code": null, "e": 5870, "s": 5815, "text": "For more in-depth sorting, use the following commands-" }, { "code": null, "e": 5997, "s": 5870, "text": "Find command is used to search and locate a list of files and directories based on conditions which are specified by the user." }, { "code": null, "e": 6071, "s": 5997, "text": "To find the sorted root files based on month, use the following command –" }, { "code": null, "e": 6120, "s": 6071, "text": "# find / -type f -printf \"\\n%Ab %p\" | head -n 11" }, { "code": null, "e": 6214, "s": 6120, "text": "The above command gives a complete list of top 11 entries which were accessed based on month." }, { "code": null, "e": 6483, "s": 6214, "text": "May /etc/newt/palette.ubuntu\nMay /etc/newt/palette.original\nMay /etc/ltrace.conf\nMar /etc/pulse/daemon.conf\nMar /etc/pulse/default.pa\nJan /etc/pulse/system.pa\nMar /etc/pulse/client.conf\nMar /etc/gtk-3.0/settings.ini\nJul /etc/gtk-3.0/im-multipress.conf\nFeb /etc/subgid-" }, { "code": null, "e": 6578, "s": 6483, "text": "To find the sorted root files using the first key with month, use -k1M option as shown below –" }, { "code": null, "e": 6639, "s": 6578, "text": "# find / -type f -printf \"\\n%Ab %p\" | head -n 11 | sort -k1M" }, { "code": null, "e": 6679, "s": 6639, "text": "The sample output should be like this –" }, { "code": null, "e": 6948, "s": 6679, "text": "Jan /etc/pulse/system.pa\nFeb /etc/subgid-\nMar /etc/gtk-3.0/settings.ini\nMar /etc/pulse/client.conf\nMar /etc/pulse/daemon.conf\nMar /etc/pulse/default.pa\nMay /etc/ltrace.conf\nMay /etc/newt/palette.original\nMay /etc/newt/palette.ubuntu\nJul /etc/gtk-3.0/im-multipress.conf" }, { "code": null, "e": 7001, "s": 6948, "text": "The above command has sorted according to the month." }, { "code": null, "e": 7074, "s": 7001, "text": "To find the sorted root files based on date, use the following command –" }, { "code": null, "e": 7127, "s": 7074, "text": "# find / -type f -printf \"\\n%AD %AT %p\" | head -n 11" }, { "code": null, "e": 7197, "s": 7127, "text": "The above command gives the result according to date as shown below –" }, { "code": null, "e": 7716, "s": 7197, "text": "05/14/13 22:26:41.0000000000 /etc/newt/palette.ubuntu\n05/14/13 22:26:41.0000000000 /etc/newt/palette.original\n05/10/14 05:20:35.0000000000 /etc/ltrace.conf\n03/08/16 11:14:01.9113136790 /etc/pulse/daemon.conf\n03/08/16 11:14:01.9193136790 /etc/pulse/default.pa\n01/29/15 04:17:39.0000000000 /etc/pulse/system.pa\n03/08/16 11:14:01.3433136590 /etc/pulse/client.conf\n03/08/16 11:14:00.0873136140 /etc/gtk-3.0/settings.ini\n07/01/15 08:44:19.0000000000 /etc/gtk-3.0/im-multipress.conf\n02/22/16 10:49:09.0000000000 /etc/subgid-" }, { "code": null, "e": 7789, "s": 7716, "text": "To find the sorted root files based on time, use the following command –" }, { "code": null, "e": 7838, "s": 7789, "text": "# find / -type f -printf \"\\n%AT %p\" | head -n 11" }, { "code": null, "e": 7878, "s": 7838, "text": "The sample output should be like this –" }, { "code": null, "e": 8307, "s": 7878, "text": "22:26:41.0000000000 /etc/newt/palette.ubuntu\n22:26:41.0000000000 /etc/newt/palette.original\n05:20:35.0000000000 /etc/ltrace.conf\n11:14:01.9113136790 /etc/pulse/daemon.conf\n11:14:01.9193136790 /etc/pulse/default.pa\n04:17:39.0000000000 /etc/pulse/system.pa\n11:14:01.3433136590 /etc/pulse/client.conf\n11:14:00.0873136140 /etc/gtk-3.0/settings.ini\n08:44:19.0000000000 /etc/gtk-3.0/im-multipress.conf\n10:49:09.0000000000 /etc/subgid-" }, { "code": null, "e": 8498, "s": 8307, "text": "Congratulations! Now, you know “How to Find and Sort Files Based on Modification Date and Time in Linux”. We’ll learn more about these types of commands in our next Linux post. Keep reading!" } ]
JavaFX - 2D Shapes Polygon
A closed shape formed by a number of coplanar line segments connected end to end. A polygon is described by two parameters, namely, the length of its sides and the measures of its interior angles. In JavaFX, a polygon is represented by a class named Polygon. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create a polygon node in JavaFX. You need to pass the x, y coordinates of the points by which the polygon should be defined in the form of a double array. You can pass the double array as a parameter of the constructor of this class as shown below − Polygon polygon = new Polygon(doubleArray); Or, by using the getPoints() method as follows − polygon.getPoints().addAll(new Double[]{ List of XY coordinates separated by commas }); To draw a polygon in JavaFX, follow the steps given below. Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows− public class ClassName extends Application { @Override public void start(Stage primaryStage) throws Exception { } } You can create a polygon in JavaFX by instantiating the class named Polygon which belongs to a package javafx.scene.shape. You can instantiate this class as follows. //Creating an object of the class Polygon Polygon hexagon = new Polygon(); Specify a double array holding the XY coordinates of the points of the required polygon (hexagon in this example) separated by commas, using the getPoints() method of the Polygon class, as follows. //Adding coordinates to the hexagon hexagon.getPoints().addAll(new Double[]{ 200.0, 50.0, 400.0, 50.0, 450.0, 150.0, 400.0, 250.0, 200.0, 250.0, 150.0, 150.0, }) In the start() method, create a group object by instantiating the class named Group, which belongs to the package javafx.scene. Pass the polygon node (hexagon) object, created in the previous step, as a parameter to the constructor of the Group class, in order to add it to the group as follows − Group root = new Group(hexagon); Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class pass the Group object (root), created in the previous step. Scene scene = new Scene(group ,600, 300); You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is the Stage object which is passed to the start method of the scene class as a parameter. Using the primaryStage object, set the title of the scene as Sample Application as follows. primaryStage.setTitle("Sample Application"); You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous step using the method as shown below. primaryStage.setScene(scene); Display the contents of the scene using the method named show() of the Stage class as follows. primaryStage.show(); Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows. public static void main(String args[]){ launch(args); } Following is a program which generates a Polygon (hexagon) using JavaFX. Save this code in a file with the name PolygonExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Polygon; import javafx.stage.Stage; public class PolygonExample extends Application { @Override public void start(Stage stage) { //Creating a Polygon Polygon polygon = new Polygon(); //Adding coordinates to the polygon polygon.getPoints().addAll(new Double[]{ 300.0, 50.0, 450.0, 150.0, 300.0, 250.0, 150.0, 150.0, }); //Creating a Group object Group root = new Group(polygon); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle("Drawing a Polygon"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac PolygonExample.java java PolygonExample On executing, the above program generates a JavaFX window displaying a polygon as shown below. 33 Lectures 7.5 hours Syed Raza 64 Lectures 12.5 hours Emenwa Global, Ejike IfeanyiChukwu 20 Lectures 4 hours Emenwa Global, Ejike IfeanyiChukwu Print Add Notes Bookmark this page
[ { "code": null, "e": 1982, "s": 1900, "text": "A closed shape formed by a number of coplanar line segments connected end to end." }, { "code": null, "e": 2097, "s": 1982, "text": "A polygon is described by two parameters, namely, the length of its sides and the measures of its interior angles." }, { "code": null, "e": 2213, "s": 2097, "text": "In JavaFX, a polygon is represented by a class named Polygon. This class belongs to the package javafx.scene.shape." }, { "code": null, "e": 2405, "s": 2213, "text": "By instantiating this class, you can create a polygon node in JavaFX. You need to pass the x, y coordinates of the points by which the polygon should be defined in the form of a double array." }, { "code": null, "e": 2500, "s": 2405, "text": "You can pass the double array as a parameter of the constructor of this class as shown below −" }, { "code": null, "e": 2545, "s": 2500, "text": "Polygon polygon = new Polygon(doubleArray);\n" }, { "code": null, "e": 2594, "s": 2545, "text": "Or, by using the getPoints() method as follows −" }, { "code": null, "e": 2683, "s": 2594, "text": "polygon.getPoints().addAll(new Double[]{ List of XY coordinates separated by commas });\n" }, { "code": null, "e": 2742, "s": 2683, "text": "To draw a polygon in JavaFX, follow the steps given below." }, { "code": null, "e": 2889, "s": 2742, "text": "Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows−" }, { "code": null, "e": 3029, "s": 2889, "text": "public class ClassName extends Application { \n @Override \n public void start(Stage primaryStage) throws Exception { \n } \n}" }, { "code": null, "e": 3195, "s": 3029, "text": "You can create a polygon in JavaFX by instantiating the class named Polygon which belongs to a package javafx.scene.shape. You can instantiate this class as follows." }, { "code": null, "e": 3272, "s": 3195, "text": "//Creating an object of the class Polygon \nPolygon hexagon = new Polygon();\n" }, { "code": null, "e": 3470, "s": 3272, "text": "Specify a double array holding the XY coordinates of the points of the required polygon (hexagon in this example) separated by commas, using the getPoints() method of the Polygon class, as follows." }, { "code": null, "e": 3692, "s": 3470, "text": "//Adding coordinates to the hexagon \nhexagon.getPoints().addAll(new Double[]{ \n 200.0, 50.0, \n 400.0, 50.0, \n 450.0, 150.0, \n 400.0, 250.0, \n 200.0, 250.0, \n 150.0, 150.0, \n})" }, { "code": null, "e": 3820, "s": 3692, "text": "In the start() method, create a group object by instantiating the class named Group, which belongs to the package javafx.scene." }, { "code": null, "e": 3989, "s": 3820, "text": "Pass the polygon node (hexagon) object, created in the previous step, as a parameter to the constructor of the Group class, in order to add it to the group as follows −" }, { "code": null, "e": 4023, "s": 3989, "text": "Group root = new Group(hexagon);\n" }, { "code": null, "e": 4194, "s": 4023, "text": "Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class pass the Group object (root), created in the previous step." }, { "code": null, "e": 4237, "s": 4194, "text": "Scene scene = new Scene(group ,600, 300);\n" }, { "code": null, "e": 4428, "s": 4237, "text": "You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is the Stage object which is passed to the start method of the scene class as a parameter." }, { "code": null, "e": 4520, "s": 4428, "text": "Using the primaryStage object, set the title of the scene as Sample Application as follows." }, { "code": null, "e": 4566, "s": 4520, "text": "primaryStage.setTitle(\"Sample Application\");\n" }, { "code": null, "e": 4744, "s": 4566, "text": "You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous step using the method as shown below." }, { "code": null, "e": 4775, "s": 4744, "text": "primaryStage.setScene(scene);\n" }, { "code": null, "e": 4870, "s": 4775, "text": "Display the contents of the scene using the method named show() of the Stage class as follows." }, { "code": null, "e": 4892, "s": 4870, "text": "primaryStage.show();\n" }, { "code": null, "e": 5019, "s": 4892, "text": "Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows." }, { "code": null, "e": 5087, "s": 5019, "text": "public static void main(String args[]){ \n launch(args); \n}" }, { "code": null, "e": 5220, "s": 5087, "text": "Following is a program which generates a Polygon (hexagon) using JavaFX. Save this code in a file with the name PolygonExample.java." }, { "code": null, "e": 6257, "s": 5220, "text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.scene.shape.Polygon; \nimport javafx.stage.Stage; \n\npublic class PolygonExample extends Application { \n @Override \n public void start(Stage stage) { \n //Creating a Polygon \n Polygon polygon = new Polygon(); \n \n //Adding coordinates to the polygon \n polygon.getPoints().addAll(new Double[]{ \n 300.0, 50.0, \n 450.0, 150.0, \n 300.0, 250.0, \n 150.0, 150.0, \n }); \n \n //Creating a Group object \n Group root = new Group(polygon); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage \n stage.setTitle(\"Drawing a Polygon\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n}" }, { "code": null, "e": 6351, "s": 6257, "text": "Compile and execute the saved java file from the command prompt using the following commands." }, { "code": null, "e": 6399, "s": 6351, "text": "javac PolygonExample.java \njava PolygonExample\n" }, { "code": null, "e": 6494, "s": 6399, "text": "On executing, the above program generates a JavaFX window displaying a polygon as shown below." }, { "code": null, "e": 6529, "s": 6494, "text": "\n 33 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6540, "s": 6529, "text": " Syed Raza" }, { "code": null, "e": 6576, "s": 6540, "text": "\n 64 Lectures \n 12.5 hours \n" }, { "code": null, "e": 6612, "s": 6576, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 6645, "s": 6612, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 6681, "s": 6645, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 6688, "s": 6681, "text": " Print" }, { "code": null, "e": 6699, "s": 6688, "text": " Add Notes" } ]
Taking Seasonality into Consideration for Time Series Analysis | by Zijing Zhu | Towards Data Science
Seasonality, as its name suggested, refers to the seasonal characteristics of the time series data. It is the predictable pattern that repeats at a certain frequency within one year, such as weekly, monthly, quarterly, etc. The most straightforward example to demonstrate seasonality is to look at the temperature data. We always expect the temperature to be higher in the summer while lower in the winter in most places on Earth. Taking seasonality into consideration is very important in time series forecasting, such as demand forecasting. For example, we may expect ice cream sales to have seasonality since the sales will be higher in the summer every year. The model that considers the seasonal effects of the sales will be more accurate in time series forecasting. In general, the goal of time series analysis is to take advantage of the data's temporal nature to make more sophisticated models. To properly forecast events, we need to implement techniques to find and model the long-term trends, seasonality, and residual noise in our data. This article will focus on discussing how to detect seasonality in the data and how to incorporate seasonality in forecasting. Before putting seasonality into the models, we need to know how the data is repeated and on what frequency. Detect seasonality can be straightforward if you understand the context of the data very well. For example, we know the temperature will be higher in the summer and lower in the winter in a year. To discover the seasonality of the data you are not familiar with the context, the simple way is to plot the data and observe the periodic signals along with the time series: The graph above shows the repeated pattern every year. Even though the height at which each summer reaches differ from each other, we can still see the pattern that the temperature are at its highest during the summer, and are at its lowest during the winter. There is also seasonality within a day for temperature data, and we may not know exactly how temperature fluctuate in a day. We could plot the data in a lower frequency, or use an algorithm called fast Fourier transform (FFT) to detect the repeated frequency. Any periodic signal can be represented as the sum of several sine waves with varying amplitude, phase, and frequency. A time series can be converted into its frequency components with the mathematical tool known as the Fourier transform. The output of a FFT can be thought of as a representation of all the frequency components of your data. In some sense it is a histogram with each “frequency bin” corresponding to a particular frequency in your signal. Each frequency component has both an amplitude and phase and is represented as a complex number. Generally, we care only about the amplitude to determine what is the highest “frequency bin” in your data. I won’t go much detail in math here, but if you are interested, this article by Cory Maklin explains it very well. To perform FFT in a dataset, we can use the FFT module from Scipy. Take the temperature dataset (temps) that has 13 years of hourly temperature as an example. The dataset looks like this: Perform the following code on the dataset: from scipy.fftpack import fftimport numpy as npimport matplotlib.pyplot as pltfft = fft((temps.Temperature — temps.Temperature.mean()).values)plt.plot(np.abs(fft))plt.title("FFT of temperature data")plt.xlabel('# Cycles in full window of data (~13 years)'); Not that in the first step we subtract the mean of the temperature to avoid a large zero-frequency component. Plotting the whole dataset with 13 years of data may not show the pattern well as the graph shows: A Fourier transform of a real signal, no imaginary part, is symmetric about the center of the frequency range. Plotting FFT in a long time range may not give the most relevant information we are looking for. Thus we can zoom in to check the “frequency bin” at different frequency level. We would expect the temperature to have daily seasonality so that we zoom in to check the “histogram” from day 0 to day 5: plt.plot(1./13 * np.arange(len(fft)), np.abs(fft))plt.title("FFT of temperature data (Low Frequencies zoom)")plt.xlim([0,5])plt.xlabel('Frequency ($y^{-1}$)'); The graph below shows the daily seasonality because the “frequency bin” is very high at the “day 1” frequency: Similarly, we can zoom in to the frequency around day 365 to check for yearly seasonality: plt.plot(1./13 * np.arange(len(fft)), np.abs(fft))plt.title(“FFT of temperature data (High Frequencies zoom)”)plt.ylim([0,120000])plt.xlim([365–30, 365 + 30])plt.xlabel(‘Frequency ($y^{-1}$)’); The graph below shows the yearly seasonality as the day 365 peaks. FFT is an excellent tool to transform the time series data for it to be plotted as “frequency histogram”. The graph will show what is the frequency of the data’s repeated pattern thus detects the seasonality in data. After detecting seasonality, there are several ways to incorporate seasonality in the model to better perform time series forecasting. This article will introduce using seasonal indicators, Fourier analysis and SARIMA model to add seasonalities in time series forecasting. 1, Add Seasonal Indicators The most straightforward way of adding seasonalities into the model is to add seasonal indicators. Seasonal indicators are categorical variables describing the “season” of each observation. Taking temperature prediction as an example. To indicate daily seasonality, when training the model, you may use “hour” of the observation as a feature. This feature will take the fixed effect from the hour of the day in predicting the temperature just as any other features do. To include yearly seasonality, we should add “month” and “quarter” as features in the model with the same intuition. Using the dataset listed above, each observation should include the following features: The “Hour”, “Month”, “Quarter” variables are the features we should include to capture seasonalities in the data. Even though they are in numerical form, they are actually categorical variables rather than numerical variables. Note that if we are use linear models for prediction, to include these categorical variables, we need to first transform these variables using transformers like one-hot encoding. After transformation, the “Hour” variable should look like this: The five observations of the “Hour” variable are transformed into four columns, showing different values of hour. You can say that we do not include Hour_4 as a column here to avoid multicollinearity. If Hour only has five values, not being in the first four values automatically indicating that this observation takes the fifth value. A simple way to do one-hot encoding using Pandas is to use the function get_dummies(): pandas.get_dummies(data, drop_first=True) The function will transform categorical variables into dummy variables, thus ready to put in linear models. These dummy variables are call seasonal indicators. If your prediction model doesn’t assume linear relations, you do not need to do one-hot encoding. For example, if you are using tree models, simply put the categorical variables into the model as features. If the categorical variable is in textual form, assign numerical numbers to each category before putting into the model. (change “January” into “1”) 2, Fourier Analysis Any signal can be represented as a linear combination of sines and cosines of varying frequencies fn and amplitudes An and Bn: The Fourier transform decomposes a signal into a set of frequencies, allowing for us to determine the dominant frequencies that make up a time series. Take the temperature data as an example. From the plots above, we know that temperature is roughly sinusoidal. Thus we know that a reasonable model might be: Where y0 and t0 are parameters to be learned. T is usually one year for seasonal variation. While this function is linear in y0, it is not linear in t0. However, using Fourier analysis, that the above is equivalent to: This function is linear in A and B. Thus, we can create a model containing sinusoidal terms on one or more time scales, and fit it to the data using a linear regression. The following code shows the process of constructing yearly, half year and daily seasonalities as features, and using them in a linear regression model to predict temperature: df['sin(year)'] = np.sin(df['julian'] / 365.25 * 2 * np.pi)df['cos(year)'] = np.cos(df['julian'] / 365.25 * 2 * np.pi)df['sin(6mo)'] = np.sin(df['julian'] / (365.25 / 2) * 2 * np.pi)df['cos(6mo)'] = np.cos(df['julian'] / (365.25 / 2) * 2 * np.pi)df['sin(day)'] = np.sin(df.index.hour / 24.0 * 2* np.pi)df['cos(day)'] = np.cos(df.index.hour / 24.0 * 2* np.pi)regress = LinearRegression().fit(X=train[['sin(year)', 'cos(year)', 'sin(6mo)','cos(6mo)','sin(day)','cos(day)']], y=train['temp']) The FFT figure above is very useful in determining what kind of seasonalities should be included in the regression. Note that rather than using the regular date here, we are using Julian date as the t variable here. Julian date is the number of days since the beginning of the Julian Period (January 1, 4713 BC), thus it is a continuous number. Besides adding seasonal indicators or using Fourier Analysis, we can also use SARIMA model, which is adding seasonal components to ARIMA (Autoregressive Integrated Moving Average) model. This tutorial describes SARIMA model in detail if you are interested. Thank you for reading this article. Here is the list of all my blog posts. Check them out if you are interested!
[ { "code": null, "e": 603, "s": 172, "text": "Seasonality, as its name suggested, refers to the seasonal characteristics of the time series data. It is the predictable pattern that repeats at a certain frequency within one year, such as weekly, monthly, quarterly, etc. The most straightforward example to demonstrate seasonality is to look at the temperature data. We always expect the temperature to be higher in the summer while lower in the winter in most places on Earth." }, { "code": null, "e": 1348, "s": 603, "text": "Taking seasonality into consideration is very important in time series forecasting, such as demand forecasting. For example, we may expect ice cream sales to have seasonality since the sales will be higher in the summer every year. The model that considers the seasonal effects of the sales will be more accurate in time series forecasting. In general, the goal of time series analysis is to take advantage of the data's temporal nature to make more sophisticated models. To properly forecast events, we need to implement techniques to find and model the long-term trends, seasonality, and residual noise in our data. This article will focus on discussing how to detect seasonality in the data and how to incorporate seasonality in forecasting." }, { "code": null, "e": 1827, "s": 1348, "text": "Before putting seasonality into the models, we need to know how the data is repeated and on what frequency. Detect seasonality can be straightforward if you understand the context of the data very well. For example, we know the temperature will be higher in the summer and lower in the winter in a year. To discover the seasonality of the data you are not familiar with the context, the simple way is to plot the data and observe the periodic signals along with the time series:" }, { "code": null, "e": 2087, "s": 1827, "text": "The graph above shows the repeated pattern every year. Even though the height at which each summer reaches differ from each other, we can still see the pattern that the temperature are at its highest during the summer, and are at its lowest during the winter." }, { "code": null, "e": 3310, "s": 2087, "text": "There is also seasonality within a day for temperature data, and we may not know exactly how temperature fluctuate in a day. We could plot the data in a lower frequency, or use an algorithm called fast Fourier transform (FFT) to detect the repeated frequency. Any periodic signal can be represented as the sum of several sine waves with varying amplitude, phase, and frequency. A time series can be converted into its frequency components with the mathematical tool known as the Fourier transform. The output of a FFT can be thought of as a representation of all the frequency components of your data. In some sense it is a histogram with each “frequency bin” corresponding to a particular frequency in your signal. Each frequency component has both an amplitude and phase and is represented as a complex number. Generally, we care only about the amplitude to determine what is the highest “frequency bin” in your data. I won’t go much detail in math here, but if you are interested, this article by Cory Maklin explains it very well. To perform FFT in a dataset, we can use the FFT module from Scipy. Take the temperature dataset (temps) that has 13 years of hourly temperature as an example. The dataset looks like this:" }, { "code": null, "e": 3353, "s": 3310, "text": "Perform the following code on the dataset:" }, { "code": null, "e": 3611, "s": 3353, "text": "from scipy.fftpack import fftimport numpy as npimport matplotlib.pyplot as pltfft = fft((temps.Temperature — temps.Temperature.mean()).values)plt.plot(np.abs(fft))plt.title(\"FFT of temperature data\")plt.xlabel('# Cycles in full window of data (~13 years)');" }, { "code": null, "e": 3820, "s": 3611, "text": "Not that in the first step we subtract the mean of the temperature to avoid a large zero-frequency component. Plotting the whole dataset with 13 years of data may not show the pattern well as the graph shows:" }, { "code": null, "e": 4230, "s": 3820, "text": "A Fourier transform of a real signal, no imaginary part, is symmetric about the center of the frequency range. Plotting FFT in a long time range may not give the most relevant information we are looking for. Thus we can zoom in to check the “frequency bin” at different frequency level. We would expect the temperature to have daily seasonality so that we zoom in to check the “histogram” from day 0 to day 5:" }, { "code": null, "e": 4390, "s": 4230, "text": "plt.plot(1./13 * np.arange(len(fft)), np.abs(fft))plt.title(\"FFT of temperature data (Low Frequencies zoom)\")plt.xlim([0,5])plt.xlabel('Frequency ($y^{-1}$)');" }, { "code": null, "e": 4501, "s": 4390, "text": "The graph below shows the daily seasonality because the “frequency bin” is very high at the “day 1” frequency:" }, { "code": null, "e": 4592, "s": 4501, "text": "Similarly, we can zoom in to the frequency around day 365 to check for yearly seasonality:" }, { "code": null, "e": 4786, "s": 4592, "text": "plt.plot(1./13 * np.arange(len(fft)), np.abs(fft))plt.title(“FFT of temperature data (High Frequencies zoom)”)plt.ylim([0,120000])plt.xlim([365–30, 365 + 30])plt.xlabel(‘Frequency ($y^{-1}$)’);" }, { "code": null, "e": 4853, "s": 4786, "text": "The graph below shows the yearly seasonality as the day 365 peaks." }, { "code": null, "e": 5070, "s": 4853, "text": "FFT is an excellent tool to transform the time series data for it to be plotted as “frequency histogram”. The graph will show what is the frequency of the data’s repeated pattern thus detects the seasonality in data." }, { "code": null, "e": 5343, "s": 5070, "text": "After detecting seasonality, there are several ways to incorporate seasonality in the model to better perform time series forecasting. This article will introduce using seasonal indicators, Fourier analysis and SARIMA model to add seasonalities in time series forecasting." }, { "code": null, "e": 5370, "s": 5343, "text": "1, Add Seasonal Indicators" }, { "code": null, "e": 6044, "s": 5370, "text": "The most straightforward way of adding seasonalities into the model is to add seasonal indicators. Seasonal indicators are categorical variables describing the “season” of each observation. Taking temperature prediction as an example. To indicate daily seasonality, when training the model, you may use “hour” of the observation as a feature. This feature will take the fixed effect from the hour of the day in predicting the temperature just as any other features do. To include yearly seasonality, we should add “month” and “quarter” as features in the model with the same intuition. Using the dataset listed above, each observation should include the following features:" }, { "code": null, "e": 6515, "s": 6044, "text": "The “Hour”, “Month”, “Quarter” variables are the features we should include to capture seasonalities in the data. Even though they are in numerical form, they are actually categorical variables rather than numerical variables. Note that if we are use linear models for prediction, to include these categorical variables, we need to first transform these variables using transformers like one-hot encoding. After transformation, the “Hour” variable should look like this:" }, { "code": null, "e": 6938, "s": 6515, "text": "The five observations of the “Hour” variable are transformed into four columns, showing different values of hour. You can say that we do not include Hour_4 as a column here to avoid multicollinearity. If Hour only has five values, not being in the first four values automatically indicating that this observation takes the fifth value. A simple way to do one-hot encoding using Pandas is to use the function get_dummies():" }, { "code": null, "e": 6980, "s": 6938, "text": "pandas.get_dummies(data, drop_first=True)" }, { "code": null, "e": 7140, "s": 6980, "text": "The function will transform categorical variables into dummy variables, thus ready to put in linear models. These dummy variables are call seasonal indicators." }, { "code": null, "e": 7495, "s": 7140, "text": "If your prediction model doesn’t assume linear relations, you do not need to do one-hot encoding. For example, if you are using tree models, simply put the categorical variables into the model as features. If the categorical variable is in textual form, assign numerical numbers to each category before putting into the model. (change “January” into “1”)" }, { "code": null, "e": 7515, "s": 7495, "text": "2, Fourier Analysis" }, { "code": null, "e": 7642, "s": 7515, "text": "Any signal can be represented as a linear combination of sines and cosines of varying frequencies fn and amplitudes An and Bn:" }, { "code": null, "e": 7951, "s": 7642, "text": "The Fourier transform decomposes a signal into a set of frequencies, allowing for us to determine the dominant frequencies that make up a time series. Take the temperature data as an example. From the plots above, we know that temperature is roughly sinusoidal. Thus we know that a reasonable model might be:" }, { "code": null, "e": 8170, "s": 7951, "text": "Where y0 and t0 are parameters to be learned. T is usually one year for seasonal variation. While this function is linear in y0, it is not linear in t0. However, using Fourier analysis, that the above is equivalent to:" }, { "code": null, "e": 8516, "s": 8170, "text": "This function is linear in A and B. Thus, we can create a model containing sinusoidal terms on one or more time scales, and fit it to the data using a linear regression. The following code shows the process of constructing yearly, half year and daily seasonalities as features, and using them in a linear regression model to predict temperature:" }, { "code": null, "e": 9006, "s": 8516, "text": "df['sin(year)'] = np.sin(df['julian'] / 365.25 * 2 * np.pi)df['cos(year)'] = np.cos(df['julian'] / 365.25 * 2 * np.pi)df['sin(6mo)'] = np.sin(df['julian'] / (365.25 / 2) * 2 * np.pi)df['cos(6mo)'] = np.cos(df['julian'] / (365.25 / 2) * 2 * np.pi)df['sin(day)'] = np.sin(df.index.hour / 24.0 * 2* np.pi)df['cos(day)'] = np.cos(df.index.hour / 24.0 * 2* np.pi)regress = LinearRegression().fit(X=train[['sin(year)', 'cos(year)', 'sin(6mo)','cos(6mo)','sin(day)','cos(day)']], y=train['temp'])" }, { "code": null, "e": 9351, "s": 9006, "text": "The FFT figure above is very useful in determining what kind of seasonalities should be included in the regression. Note that rather than using the regular date here, we are using Julian date as the t variable here. Julian date is the number of days since the beginning of the Julian Period (January 1, 4713 BC), thus it is a continuous number." }, { "code": null, "e": 9608, "s": 9351, "text": "Besides adding seasonal indicators or using Fourier Analysis, we can also use SARIMA model, which is adding seasonal components to ARIMA (Autoregressive Integrated Moving Average) model. This tutorial describes SARIMA model in detail if you are interested." } ]
Dynamic Programming | Wildcard Pattern Matching | Linear Time and Constant Space - GeeksforGeeks
28 Feb, 2022 Given a text and a wildcard pattern, find if wildcard pattern is matched with text. The matching should cover the entire text (not partial text).The wildcard pattern can include the characters ‘?’ and ‘*’: ‘?’ – matches any single character ‘*’ – Matches any sequence of characters (including the empty sequence) Pre-requisite: Dynamic Programming | Wildcard Pattern MatchingExamples: Text = "baaabab", Pattern = “*****ba*****ab", output : true Pattern = "baaa?ab", output : true Pattern = "ba*a?", output : true Pattern = "a*ab", output : false Each occurrence of ‘?’ character in wildcard pattern can be replaced with any other character and each occurrence of ‘*’ with a sequence of characters such that the wildcard pattern becomes identical to the input string after replacement. We have discussed a solution here which has O(m x n) time and O(m x n) space complexity.For applying the optimization, we will at the first note the BASE CASE which says, if the length of the pattern is zero then answer will be true only if the length of the text with which we have to match the pattern is also zero.Algorithm: Let i be the marker to point at the current character of the text. Let j be the marker to point at the current character of the pattern. Let index_txt be the marker to point at the character of text on which we encounter ‘*’ in the pattern. Let index_pat be the marker to point at the position of ‘*’ in the pattern.At any instant, if we observe that txt[i] == pat[j], then we increment both i and j as no operation needs to be performed in this case.If we encounter pat[j] == ‘?’, then it resembles the case mentioned in step – (2) as ‘?’ has the property to match with any single character.If we encounter pat[j] == ‘*’, then we update the value of index_txt and index_pat as ‘*’ has the property to match any sequence of characters (including the empty sequence) and we will increment the value of j to compare next character of pattern with the current character of the text. (As character represented by i has not been answered yet).Now if txt[i] == pat[j], and we have encountered a ‘*’ before, then it means that ‘*’ included the empty sequence, else if txt[i] != pat[j], a character needs to be provided by ‘*’ so that current character matching takes place, then i needs to be incremented as it is answered now but the character represented by j still needs to be answered, therefore, j = index_pat + 1, i = index_txt + 1 (as ‘*’ can capture other characters as well), index_txt++ (as current character in text is matched).If step – (5) is not valid, that means txt[i] != pat[j], also we have not encountered a ‘*’ that means it is not possible for the pattern to match the string. (return false).Check whether j reached its final value or not, then return the final answer. Let i be the marker to point at the current character of the text. Let j be the marker to point at the current character of the pattern. Let index_txt be the marker to point at the character of text on which we encounter ‘*’ in the pattern. Let index_pat be the marker to point at the position of ‘*’ in the pattern. At any instant, if we observe that txt[i] == pat[j], then we increment both i and j as no operation needs to be performed in this case. If we encounter pat[j] == ‘?’, then it resembles the case mentioned in step – (2) as ‘?’ has the property to match with any single character. If we encounter pat[j] == ‘*’, then we update the value of index_txt and index_pat as ‘*’ has the property to match any sequence of characters (including the empty sequence) and we will increment the value of j to compare next character of pattern with the current character of the text. (As character represented by i has not been answered yet). Now if txt[i] == pat[j], and we have encountered a ‘*’ before, then it means that ‘*’ included the empty sequence, else if txt[i] != pat[j], a character needs to be provided by ‘*’ so that current character matching takes place, then i needs to be incremented as it is answered now but the character represented by j still needs to be answered, therefore, j = index_pat + 1, i = index_txt + 1 (as ‘*’ can capture other characters as well), index_txt++ (as current character in text is matched). If step – (5) is not valid, that means txt[i] != pat[j], also we have not encountered a ‘*’ that means it is not possible for the pattern to match the string. (return false). Check whether j reached its final value or not, then return the final answer. Let us see the above algorithm in action, then we will move to the coding section:text = “baaabab” pattern = “*****ba*****ab”NOW APPLYING THE ALGORITHM Step – (1) : i = 0 (i –> ‘b’) j = 0 (j –> ‘*’) index_txt = -1 index_pat = -1NOTE: LOOP WILL RUN TILL i REACHES ITS FINAL VALUE OR THE ANSWER BECOMES FALSE MIDWAY. FIRST COMPARISON :- As we see here that pat[j] == ‘*’, therefore directly jumping on to step – (4). Step – (4) : index_txt = i (index_txt –> ‘b’) index_pat = j (index_pat –> ‘*’) j++ (j –> ‘*’)After four more comparisons : i = 0 (i –> ‘b’) j = 5 (j –> ‘b’) index_txt = 0 (index_txt –> ‘b’) index_pat = 4 (index_pat –> ‘*’)SIXTH COMPARISON :- As we see here that txt[i] == pat[j], but we already encountered ‘*’ therefore using step – (5). Step – (5) : i = 1 (i –> ‘a’) j = 6 (j –> ‘a’) index_txt = 0 (index_txt –> ‘b’) index_pat = 4 (index_pat –> ‘*’)SEVENTH COMPARISON :- Step – (5) : i = 2 (i –> ‘a’) j = 7 (j –> ‘*’) index_txt = 0 (index_txt –> ‘b’) index_pat = 4 (index_pat –> ‘*’)EIGHT COMPARISON :- Step – (4) : i = 2 (i –> ‘a’) j = 8 (j –> ‘*’) index_txt = 2 (index_txt –> ‘a’) index_pat = 7 (index_pat –> ‘*’)After four more comparisons : i = 2 (i –> ‘a’) j = 12 (j –> ‘a’) index_txt = 2 (index_txt –> ‘a’) index_pat = 11 (index_pat –> ‘*’)THIRTEENTH COMPARISON :- Step – (5) : i = 3 (i –> ‘a’) j = 13 (j –> ‘b’) index_txt = 2 (index_txt –> ‘a’) index_pat = 11 (index_pat –> ‘*’)FOURTEENTH COMPARISON :- Step – (5) : i = 3 (i –> ‘a’) j = 12 (j –> ‘a’) index_txt = 3 (index_txt –> ‘a’) index_pat = 11 (index_pat –> ‘*’)FIFTEENTH COMPARISON :- Step – (5) : i = 4 (i –> ‘b’) j = 13 (j –> ‘b’) index_txt = 3 (index_txt –> ‘a’) index_pat = 11 (index_pat –> ‘*’)SIXTEENTH COMPARISON :- Step – (5) : i = 5 (i –> ‘a’) j = 14 (j –> end) index_txt = 3 (index_txt –> ‘a’) index_pat = 11 (index_pat –> ‘*’)SEVENTEENTH COMPARISON :- Step – (5) : i = 4 (i –> ‘b’) j = 12 (j –> ‘a’) index_txt = 4 (index_txt –> ‘b’) index_pat = 11 (index_pat –> ‘*’)EIGHTEENTH COMPARISON :- Step – (5) : i = 5 (i –> ‘a’) j = 12 (j –> ‘a’) index_txt = 5 (index_txt –> ‘a’) index_pat = 11 (index_pat –> ‘*’)NINETEENTH COMPARISON :- Step – (5) : i = 6 (i –> ‘b’) j = 13 (j –> ‘b’) index_txt = 5 (index_txt –> ‘a’) index_pat = 11 (index_pat –> ‘*’)TWENTIETH COMPARISON :- Step – (5) : i = 7 (i –> end) j = 14 (j –> end) index_txt = 5 (index_txt –> ‘a’) index_pat = 11 (index_pat –> ‘*’)NOTE : NOW WE WILL COME OUT OF LOOP TO RUN STEP – 7. Step – (7) : j is already present at its end position, therefore answer is true. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement wildcard// pattern matching algorithm#include <bits/stdc++.h>using namespace std; // Function that matches input text// with given wildcard patternbool strmatch(char txt[], char pat[], int n, int m){ // empty pattern can only // match with empty string. // Base Case : if (m == 0) return (n == 0); // step-1 : // initialize markers : int i = 0, j = 0, index_txt = -1, index_pat = -1; while (i < n) { // For step - (2, 5) if (j < m && txt[i] == pat[j]) { i++; j++; } // For step - (3) else if (j < m && pat[j] == '?') { i++; j++; } // For step - (4) else if (j < m && pat[j] == '*') { index_txt = i; index_pat = j; j++; } // For step - (5) else if (index_pat != -1) { j = index_pat + 1; i = index_txt + 1; index_txt++; } // For step - (6) else { return false; } } // For step - (7) while (j < m && pat[j] == '*') { j++; } // Final Check if (j == m) { return true; } return false;} // Driver codeint main(){ char str[] = "baaabab"; char pattern[] = "*****ba*****ab"; // char pattern[] = "ba*****ab"; // char pattern[] = "ba*ab"; // char pattern[] = "a*ab"; if (strmatch(str, pattern, strlen(str), strlen(pattern))) cout << "Yes" << endl; else cout << "No" << endl; char pattern2[] = "a*****ab"; if (strmatch(str, pattern2, strlen(str), strlen(pattern2))) cout << "Yes" << endl; else cout << "No" << endl; return 0;} // Java program to implement wildcard// pattern matching algorithmclass GFG { // Function that matches input text // with given wildcard pattern static boolean strmatch(char txt[], char pat[], int n, int m) { // empty pattern can only // match with empty string. // Base Case : if (m == 0) return (n == 0); // step-1 : // initialize markers : int i = 0, j = 0, index_txt = -1, index_pat = -1; while (i < n) { // For step - (2, 5) if (j < m && txt[i] == pat[j]) { i++; j++; } // For step - (3) else if (j < m && pat[j] == '?') { i++; j++; } // For step - (4) else if (j < m && pat[j] == '*') { index_txt = i; index_pat = j; j++; } // For step - (5) else if (index_pat != -1) { j = index_pat + 1; i = index_txt + 1; index_txt++; } // For step - (6) else { return false; } } // For step - (7) while (j < m && pat[j] == '*') { j++; } // Final Check if (j == m) { return true; } return false; } // Driver code public static void main(String[] args) { char str[] = "baaabab".toCharArray(); char pattern[] = "*****ba*****ab".toCharArray(); // char pattern[] = "ba*****ab"; // char pattern[] = "ba*ab"; // char pattern[] = "a*ab"; if (strmatch(str, pattern, str.length, pattern.length)) System.out.println("Yes"); else System.out.println("No"); char pattern2[] = "a*****ab".toCharArray(); if (strmatch(str, pattern2, str.length, pattern2.length)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by Rajput-Ji # Python3 program to implement# wildcard pattern matching# algorithm # Function that matches input# txt with given wildcard patterndef stringmatch(txt, pat, n, m): # empty pattern can only # match with empty sting # Base case if (m == 0): return (n == 0) # step 1 # initialize markers : i = 0 j = 0 index_txt = -1 index_pat = -1 while(i < n - 2): # For step - (2, 5) if (j < m and txt[i] == pat[j]): i += 1 j += 1 # For step - (3) elif(j < m and pat[j] == '?'): i += 1 j += 1 # For step - (4) elif(j < m and pat[j] == '*'): index_txt = i index_pat = j j += 1 # For step - (5) elif(index_pat != -1): j = index_pat + 1 i = index_txt + 1 index_txt += 1 # For step - (6) else: return False # For step - (7) while (j < m and pat[j] == '*'): j += 1 # Final Check if(j == m): return True return False # Driver codestrr = "baaabab"pattern = "*****ba*****ab" # char pattern[] = "ba*****ab"# char pattern[] = "ba * ab"# char pattern[] = "a * ab"if (stringmatch(strr, pattern, len(strr), len(pattern))): print("Yes")else: print( "No") pattern2 = "a*****ab";if (stringmatch(strr, pattern2, len(strr), len(pattern2))): print("Yes")else: print( "No") # This code is contributed# by sahilhelangia // C# program to implement wildcard// pattern matching algorithmusing System; class GFG { // Function that matches input text // with given wildcard pattern static Boolean strmatch(char[] txt, char[] pat, int n, int m) { // empty pattern can only // match with empty string. // Base Case : if (m == 0) return (n == 0); // step-1 : // initialize markers : int i = 0, j = 0, index_txt = -1, index_pat = -1; while (i < n) { // For step - (2, 5) if (j < m && txt[i] == pat[j]) { i++; j++; } // For step - (3) else if (j < m && pat[j] == '?') { i++; j++; } // For step - (4) else if (j < m && pat[j] == '*') { index_txt = i; index_pat = j; j++; } // For step - (5) else if (index_pat != -1) { j = index_pat + 1; i = index_txt + 1; index_txt++; } // For step - (6) else { return false; } } // For step - (7) while (j < m && pat[j] == '*') { j++; } // Final Check if (j == m) { return true; } return false; } // Driver code public static void Main(String[] args) { char[] str = "baaabab".ToCharArray(); char[] pattern = "*****ba*****ab".ToCharArray(); // char pattern[] = "ba*****ab"; // char pattern[] = "ba*ab"; // char pattern[] = "a*ab"; if (strmatch(str, pattern, str.Length, pattern.Length)) Console.WriteLine("Yes"); else Console.WriteLine("No"); char[] pattern2 = "a*****ab".ToCharArray(); if (strmatch(str, pattern2, str.Length, pattern2.Length)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by Rajput-Ji <script> // Javascript program to implement wildcard // pattern matching algorithm // Function that matches input text // with given wildcard pattern function strmatch(txt, pat, n, m) { // empty pattern can only // match with empty string. // Base Case : if (m == 0) return (n == 0); // step-1 : // initialize markers : let i = 0, j = 0, index_txt = -1, index_pat = -1; while (i < n) { // For step - (2, 5) if (j < m && txt[i] == pat[j]) { i++; j++; } // For step - (3) else if (j < m && pat[j] == '?') { i++; j++; } // For step - (4) else if (j < m && pat[j] == '*') { index_txt = i; index_pat = j; j++; } // For step - (5) else if (index_pat != -1) { j = index_pat + 1; i = index_txt + 1; index_txt++; } // For step - (6) else { return false; } } // For step - (7) while (j < m && pat[j] == '*') { j++; } // Final Check if (j == m) { return true; } return false; } let str = "baaabab".split(''); let pattern = "*****ba*****ab".split(''); if (strmatch(str, pattern, str.length, pattern.length)) document.write("Yes" + "</br>"); else document.write("No" + "</br>"); let pattern2 = "a*****ab".split(''); if (strmatch(str, pattern2, str.length, pattern2.length)) document.write("Yes" + "</br>"); else document.write("No"); </script> Yes No Complexity Analysis: Time Complexity: O(m + n), where ‘m’ and ‘n’ are the lengths of text and pattern respectively. Auxiliary Space: O(1). No use of any data structure for storing values sahilshelangia aliassar Rajput-Ji bidibaaz123 jishantsingh rameshtravel07 gabaa406 rkbhola5 Competitive Programming Dynamic Programming Pattern Searching Strings Strings Dynamic Programming Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Prefix Sum Array - Implementation and Applications in Competitive Programming Ordered Set and GNU C++ PBDS Modulo 10^9+7 (1000000007) What is Competitive Programming and How to Prepare for It? Bits manipulation (Important tactics) 0-1 Knapsack Problem | DP-10 Largest Sum Contiguous Subarray Bellman–Ford Algorithm | DP-23 Longest Common Subsequence | DP-4 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 26199, "s": 26171, "text": "\n28 Feb, 2022" }, { "code": null, "e": 26405, "s": 26199, "text": "Given a text and a wildcard pattern, find if wildcard pattern is matched with text. The matching should cover the entire text (not partial text).The wildcard pattern can include the characters ‘?’ and ‘*’:" }, { "code": null, "e": 26440, "s": 26405, "text": "‘?’ – matches any single character" }, { "code": null, "e": 26512, "s": 26440, "text": "‘*’ – Matches any sequence of characters (including the empty sequence)" }, { "code": null, "e": 26584, "s": 26512, "text": "Pre-requisite: Dynamic Programming | Wildcard Pattern MatchingExamples:" }, { "code": null, "e": 26746, "s": 26584, "text": "Text = \"baaabab\",\nPattern = “*****ba*****ab\", output : true\nPattern = \"baaa?ab\", output : true\nPattern = \"ba*a?\", output : true\nPattern = \"a*ab\", output : false " }, { "code": null, "e": 26985, "s": 26746, "text": "Each occurrence of ‘?’ character in wildcard pattern can be replaced with any other character and each occurrence of ‘*’ with a sequence of characters such that the wildcard pattern becomes identical to the input string after replacement." }, { "code": null, "e": 27315, "s": 26985, "text": "We have discussed a solution here which has O(m x n) time and O(m x n) space complexity.For applying the optimization, we will at the first note the BASE CASE which says, if the length of the pattern is zero then answer will be true only if the length of the text with which we have to match the pattern is also zero.Algorithm: " }, { "code": null, "e": 28999, "s": 27315, "text": "Let i be the marker to point at the current character of the text. Let j be the marker to point at the current character of the pattern. Let index_txt be the marker to point at the character of text on which we encounter ‘*’ in the pattern. Let index_pat be the marker to point at the position of ‘*’ in the pattern.At any instant, if we observe that txt[i] == pat[j], then we increment both i and j as no operation needs to be performed in this case.If we encounter pat[j] == ‘?’, then it resembles the case mentioned in step – (2) as ‘?’ has the property to match with any single character.If we encounter pat[j] == ‘*’, then we update the value of index_txt and index_pat as ‘*’ has the property to match any sequence of characters (including the empty sequence) and we will increment the value of j to compare next character of pattern with the current character of the text. (As character represented by i has not been answered yet).Now if txt[i] == pat[j], and we have encountered a ‘*’ before, then it means that ‘*’ included the empty sequence, else if txt[i] != pat[j], a character needs to be provided by ‘*’ so that current character matching takes place, then i needs to be incremented as it is answered now but the character represented by j still needs to be answered, therefore, j = index_pat + 1, i = index_txt + 1 (as ‘*’ can capture other characters as well), index_txt++ (as current character in text is matched).If step – (5) is not valid, that means txt[i] != pat[j], also we have not encountered a ‘*’ that means it is not possible for the pattern to match the string. (return false).Check whether j reached its final value or not, then return the final answer." }, { "code": null, "e": 29316, "s": 28999, "text": "Let i be the marker to point at the current character of the text. Let j be the marker to point at the current character of the pattern. Let index_txt be the marker to point at the character of text on which we encounter ‘*’ in the pattern. Let index_pat be the marker to point at the position of ‘*’ in the pattern." }, { "code": null, "e": 29452, "s": 29316, "text": "At any instant, if we observe that txt[i] == pat[j], then we increment both i and j as no operation needs to be performed in this case." }, { "code": null, "e": 29594, "s": 29452, "text": "If we encounter pat[j] == ‘?’, then it resembles the case mentioned in step – (2) as ‘?’ has the property to match with any single character." }, { "code": null, "e": 29941, "s": 29594, "text": "If we encounter pat[j] == ‘*’, then we update the value of index_txt and index_pat as ‘*’ has the property to match any sequence of characters (including the empty sequence) and we will increment the value of j to compare next character of pattern with the current character of the text. (As character represented by i has not been answered yet)." }, { "code": null, "e": 30436, "s": 29941, "text": "Now if txt[i] == pat[j], and we have encountered a ‘*’ before, then it means that ‘*’ included the empty sequence, else if txt[i] != pat[j], a character needs to be provided by ‘*’ so that current character matching takes place, then i needs to be incremented as it is answered now but the character represented by j still needs to be answered, therefore, j = index_pat + 1, i = index_txt + 1 (as ‘*’ can capture other characters as well), index_txt++ (as current character in text is matched)." }, { "code": null, "e": 30611, "s": 30436, "text": "If step – (5) is not valid, that means txt[i] != pat[j], also we have not encountered a ‘*’ that means it is not possible for the pattern to match the string. (return false)." }, { "code": null, "e": 30689, "s": 30611, "text": "Check whether j reached its final value or not, then return the final answer." }, { "code": null, "e": 33196, "s": 30689, "text": "Let us see the above algorithm in action, then we will move to the coding section:text = “baaabab” pattern = “*****ba*****ab”NOW APPLYING THE ALGORITHM Step – (1) : i = 0 (i –> ‘b’) j = 0 (j –> ‘*’) index_txt = -1 index_pat = -1NOTE: LOOP WILL RUN TILL i REACHES ITS FINAL VALUE OR THE ANSWER BECOMES FALSE MIDWAY. FIRST COMPARISON :- As we see here that pat[j] == ‘*’, therefore directly jumping on to step – (4). Step – (4) : index_txt = i (index_txt –> ‘b’) index_pat = j (index_pat –> ‘*’) j++ (j –> ‘*’)After four more comparisons : i = 0 (i –> ‘b’) j = 5 (j –> ‘b’) index_txt = 0 (index_txt –> ‘b’) index_pat = 4 (index_pat –> ‘*’)SIXTH COMPARISON :- As we see here that txt[i] == pat[j], but we already encountered ‘*’ therefore using step – (5). Step – (5) : i = 1 (i –> ‘a’) j = 6 (j –> ‘a’) index_txt = 0 (index_txt –> ‘b’) index_pat = 4 (index_pat –> ‘*’)SEVENTH COMPARISON :- Step – (5) : i = 2 (i –> ‘a’) j = 7 (j –> ‘*’) index_txt = 0 (index_txt –> ‘b’) index_pat = 4 (index_pat –> ‘*’)EIGHT COMPARISON :- Step – (4) : i = 2 (i –> ‘a’) j = 8 (j –> ‘*’) index_txt = 2 (index_txt –> ‘a’) index_pat = 7 (index_pat –> ‘*’)After four more comparisons : i = 2 (i –> ‘a’) j = 12 (j –> ‘a’) index_txt = 2 (index_txt –> ‘a’) index_pat = 11 (index_pat –> ‘*’)THIRTEENTH COMPARISON :- Step – (5) : i = 3 (i –> ‘a’) j = 13 (j –> ‘b’) index_txt = 2 (index_txt –> ‘a’) index_pat = 11 (index_pat –> ‘*’)FOURTEENTH COMPARISON :- Step – (5) : i = 3 (i –> ‘a’) j = 12 (j –> ‘a’) index_txt = 3 (index_txt –> ‘a’) index_pat = 11 (index_pat –> ‘*’)FIFTEENTH COMPARISON :- Step – (5) : i = 4 (i –> ‘b’) j = 13 (j –> ‘b’) index_txt = 3 (index_txt –> ‘a’) index_pat = 11 (index_pat –> ‘*’)SIXTEENTH COMPARISON :- Step – (5) : i = 5 (i –> ‘a’) j = 14 (j –> end) index_txt = 3 (index_txt –> ‘a’) index_pat = 11 (index_pat –> ‘*’)SEVENTEENTH COMPARISON :- Step – (5) : i = 4 (i –> ‘b’) j = 12 (j –> ‘a’) index_txt = 4 (index_txt –> ‘b’) index_pat = 11 (index_pat –> ‘*’)EIGHTEENTH COMPARISON :- Step – (5) : i = 5 (i –> ‘a’) j = 12 (j –> ‘a’) index_txt = 5 (index_txt –> ‘a’) index_pat = 11 (index_pat –> ‘*’)NINETEENTH COMPARISON :- Step – (5) : i = 6 (i –> ‘b’) j = 13 (j –> ‘b’) index_txt = 5 (index_txt –> ‘a’) index_pat = 11 (index_pat –> ‘*’)TWENTIETH COMPARISON :- Step – (5) : i = 7 (i –> end) j = 14 (j –> end) index_txt = 5 (index_txt –> ‘a’) index_pat = 11 (index_pat –> ‘*’)NOTE : NOW WE WILL COME OUT OF LOOP TO RUN STEP – 7. Step – (7) : j is already present at its end position, therefore answer is true." }, { "code": null, "e": 33247, "s": 33196, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 33251, "s": 33247, "text": "C++" }, { "code": null, "e": 33256, "s": 33251, "text": "Java" }, { "code": null, "e": 33264, "s": 33256, "text": "Python3" }, { "code": null, "e": 33267, "s": 33264, "text": "C#" }, { "code": null, "e": 33278, "s": 33267, "text": "Javascript" }, { "code": "// C++ program to implement wildcard// pattern matching algorithm#include <bits/stdc++.h>using namespace std; // Function that matches input text// with given wildcard patternbool strmatch(char txt[], char pat[], int n, int m){ // empty pattern can only // match with empty string. // Base Case : if (m == 0) return (n == 0); // step-1 : // initialize markers : int i = 0, j = 0, index_txt = -1, index_pat = -1; while (i < n) { // For step - (2, 5) if (j < m && txt[i] == pat[j]) { i++; j++; } // For step - (3) else if (j < m && pat[j] == '?') { i++; j++; } // For step - (4) else if (j < m && pat[j] == '*') { index_txt = i; index_pat = j; j++; } // For step - (5) else if (index_pat != -1) { j = index_pat + 1; i = index_txt + 1; index_txt++; } // For step - (6) else { return false; } } // For step - (7) while (j < m && pat[j] == '*') { j++; } // Final Check if (j == m) { return true; } return false;} // Driver codeint main(){ char str[] = \"baaabab\"; char pattern[] = \"*****ba*****ab\"; // char pattern[] = \"ba*****ab\"; // char pattern[] = \"ba*ab\"; // char pattern[] = \"a*ab\"; if (strmatch(str, pattern, strlen(str), strlen(pattern))) cout << \"Yes\" << endl; else cout << \"No\" << endl; char pattern2[] = \"a*****ab\"; if (strmatch(str, pattern2, strlen(str), strlen(pattern2))) cout << \"Yes\" << endl; else cout << \"No\" << endl; return 0;}", "e": 35109, "s": 33278, "text": null }, { "code": "// Java program to implement wildcard// pattern matching algorithmclass GFG { // Function that matches input text // with given wildcard pattern static boolean strmatch(char txt[], char pat[], int n, int m) { // empty pattern can only // match with empty string. // Base Case : if (m == 0) return (n == 0); // step-1 : // initialize markers : int i = 0, j = 0, index_txt = -1, index_pat = -1; while (i < n) { // For step - (2, 5) if (j < m && txt[i] == pat[j]) { i++; j++; } // For step - (3) else if (j < m && pat[j] == '?') { i++; j++; } // For step - (4) else if (j < m && pat[j] == '*') { index_txt = i; index_pat = j; j++; } // For step - (5) else if (index_pat != -1) { j = index_pat + 1; i = index_txt + 1; index_txt++; } // For step - (6) else { return false; } } // For step - (7) while (j < m && pat[j] == '*') { j++; } // Final Check if (j == m) { return true; } return false; } // Driver code public static void main(String[] args) { char str[] = \"baaabab\".toCharArray(); char pattern[] = \"*****ba*****ab\".toCharArray(); // char pattern[] = \"ba*****ab\"; // char pattern[] = \"ba*ab\"; // char pattern[] = \"a*ab\"; if (strmatch(str, pattern, str.length, pattern.length)) System.out.println(\"Yes\"); else System.out.println(\"No\"); char pattern2[] = \"a*****ab\".toCharArray(); if (strmatch(str, pattern2, str.length, pattern2.length)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by Rajput-Ji", "e": 37343, "s": 35109, "text": null }, { "code": "# Python3 program to implement# wildcard pattern matching# algorithm # Function that matches input# txt with given wildcard patterndef stringmatch(txt, pat, n, m): # empty pattern can only # match with empty sting # Base case if (m == 0): return (n == 0) # step 1 # initialize markers : i = 0 j = 0 index_txt = -1 index_pat = -1 while(i < n - 2): # For step - (2, 5) if (j < m and txt[i] == pat[j]): i += 1 j += 1 # For step - (3) elif(j < m and pat[j] == '?'): i += 1 j += 1 # For step - (4) elif(j < m and pat[j] == '*'): index_txt = i index_pat = j j += 1 # For step - (5) elif(index_pat != -1): j = index_pat + 1 i = index_txt + 1 index_txt += 1 # For step - (6) else: return False # For step - (7) while (j < m and pat[j] == '*'): j += 1 # Final Check if(j == m): return True return False # Driver codestrr = \"baaabab\"pattern = \"*****ba*****ab\" # char pattern[] = \"ba*****ab\"# char pattern[] = \"ba * ab\"# char pattern[] = \"a * ab\"if (stringmatch(strr, pattern, len(strr), len(pattern))): print(\"Yes\")else: print( \"No\") pattern2 = \"a*****ab\";if (stringmatch(strr, pattern2, len(strr), len(pattern2))): print(\"Yes\")else: print( \"No\") # This code is contributed# by sahilhelangia", "e": 38935, "s": 37343, "text": null }, { "code": "// C# program to implement wildcard// pattern matching algorithmusing System; class GFG { // Function that matches input text // with given wildcard pattern static Boolean strmatch(char[] txt, char[] pat, int n, int m) { // empty pattern can only // match with empty string. // Base Case : if (m == 0) return (n == 0); // step-1 : // initialize markers : int i = 0, j = 0, index_txt = -1, index_pat = -1; while (i < n) { // For step - (2, 5) if (j < m && txt[i] == pat[j]) { i++; j++; } // For step - (3) else if (j < m && pat[j] == '?') { i++; j++; } // For step - (4) else if (j < m && pat[j] == '*') { index_txt = i; index_pat = j; j++; } // For step - (5) else if (index_pat != -1) { j = index_pat + 1; i = index_txt + 1; index_txt++; } // For step - (6) else { return false; } } // For step - (7) while (j < m && pat[j] == '*') { j++; } // Final Check if (j == m) { return true; } return false; } // Driver code public static void Main(String[] args) { char[] str = \"baaabab\".ToCharArray(); char[] pattern = \"*****ba*****ab\".ToCharArray(); // char pattern[] = \"ba*****ab\"; // char pattern[] = \"ba*ab\"; // char pattern[] = \"a*ab\"; if (strmatch(str, pattern, str.Length, pattern.Length)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); char[] pattern2 = \"a*****ab\".ToCharArray(); if (strmatch(str, pattern2, str.Length, pattern2.Length)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by Rajput-Ji", "e": 41092, "s": 38935, "text": null }, { "code": "<script> // Javascript program to implement wildcard // pattern matching algorithm // Function that matches input text // with given wildcard pattern function strmatch(txt, pat, n, m) { // empty pattern can only // match with empty string. // Base Case : if (m == 0) return (n == 0); // step-1 : // initialize markers : let i = 0, j = 0, index_txt = -1, index_pat = -1; while (i < n) { // For step - (2, 5) if (j < m && txt[i] == pat[j]) { i++; j++; } // For step - (3) else if (j < m && pat[j] == '?') { i++; j++; } // For step - (4) else if (j < m && pat[j] == '*') { index_txt = i; index_pat = j; j++; } // For step - (5) else if (index_pat != -1) { j = index_pat + 1; i = index_txt + 1; index_txt++; } // For step - (6) else { return false; } } // For step - (7) while (j < m && pat[j] == '*') { j++; } // Final Check if (j == m) { return true; } return false; } let str = \"baaabab\".split(''); let pattern = \"*****ba*****ab\".split(''); if (strmatch(str, pattern, str.length, pattern.length)) document.write(\"Yes\" + \"</br>\"); else document.write(\"No\" + \"</br>\"); let pattern2 = \"a*****ab\".split(''); if (strmatch(str, pattern2, str.length, pattern2.length)) document.write(\"Yes\" + \"</br>\"); else document.write(\"No\"); </script>", "e": 42917, "s": 41092, "text": null }, { "code": null, "e": 42924, "s": 42917, "text": "Yes\nNo" }, { "code": null, "e": 42948, "s": 42926, "text": "Complexity Analysis: " }, { "code": null, "e": 43043, "s": 42948, "text": "Time Complexity: O(m + n), where ‘m’ and ‘n’ are the lengths of text and pattern respectively." }, { "code": null, "e": 43114, "s": 43043, "text": "Auxiliary Space: O(1). No use of any data structure for storing values" }, { "code": null, "e": 43129, "s": 43114, "text": "sahilshelangia" }, { "code": null, "e": 43138, "s": 43129, "text": "aliassar" }, { "code": null, "e": 43148, "s": 43138, "text": "Rajput-Ji" }, { "code": null, "e": 43160, "s": 43148, "text": "bidibaaz123" }, { "code": null, "e": 43173, "s": 43160, "text": "jishantsingh" }, { "code": null, "e": 43188, "s": 43173, "text": "rameshtravel07" }, { "code": null, "e": 43197, "s": 43188, "text": "gabaa406" }, { "code": null, "e": 43206, "s": 43197, "text": "rkbhola5" }, { "code": null, "e": 43230, "s": 43206, "text": "Competitive Programming" }, { "code": null, "e": 43250, "s": 43230, "text": "Dynamic Programming" }, { "code": null, "e": 43268, "s": 43250, "text": "Pattern Searching" }, { "code": null, "e": 43276, "s": 43268, "text": "Strings" }, { "code": null, "e": 43284, "s": 43276, "text": "Strings" }, { "code": null, "e": 43304, "s": 43284, "text": "Dynamic Programming" }, { "code": null, "e": 43322, "s": 43304, "text": "Pattern Searching" }, { "code": null, "e": 43420, "s": 43322, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43498, "s": 43420, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 43527, "s": 43498, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 43554, "s": 43527, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 43613, "s": 43554, "text": "What is Competitive Programming and How to Prepare for It?" }, { "code": null, "e": 43651, "s": 43613, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 43680, "s": 43651, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 43712, "s": 43680, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 43743, "s": 43712, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 43777, "s": 43743, "text": "Longest Common Subsequence | DP-4" } ]
Tryit Editor v3.7
Tryit: HTML section element
[]
Function overloading and Overriding in PHP - GeeksforGeeks
18 Feb, 2022 Function overloading and overriding is the OOPs feature in PHP. In function overloading, more than one function can have same method signature but different number of arguments. But in case of function overriding, more than one functions will have same method signature and number of arguments. Function Overloading: Function overloading contains same function name and that function performs different task according to number of arguments. For example, find the area of certain shapes where radius are given then it should return area of circle if height and width are given then it should give area of rectangle and others. Like other OOP languages function overloading can not be done by native approach. In PHP function overloading is done with the help of magic function __call(). This function takes function name and arguments. Example: php <?php// PHP program to explain function// overloading in PHP // Creating a class of type shapeclass shape { // __call is magic function which accepts // function name and arguments function __call($name_of_function, $arguments) { // It will match the function name if($name_of_function == 'area') { switch (count($arguments)) { // If there is only one argument // area of circle case 1: return 3.14 * $arguments[0]; // IF two arguments then area is rectangle; case 2: return $arguments[0]*$arguments[1]; } } }} // Declaring a shape type object$s = new Shape; // Function callecho($s->area(2));echo "\n"; // calling area method for rectangleecho ($s->area(4, 2));?> 6.28 8 Function Overriding: Function overriding is same as other OOPs programming languages. In function overriding, both parent and child classes should have same function name with and number of arguments. It is used to replace parent method in child class. The purpose of overriding is to change the behavior of parent class method. The two methods with the same name and same parameter is called overriding.Example: php <?php// PHP program to implement// function overriding // This is parent classclass P { // Function geeks of parent class function geeks() { echo "Parent"; }} // This is child classclass C extends P { // Overriding geeks method function geeks() { echo "\nChild"; }} // Reference type of parent$p = new P; // Reference type of child$c= new C; // print Parent$p->geeks(); // Print child$c->geeks();?> Parent Child PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. adnanirshad158 anikaseth98 surinderdawra388 PHP-function PHP PHP Programs Technical Scripter Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime Split a comma delimited string into an array in PHP How to pass JavaScript variables to PHP ? How to get parameters from a URL string in PHP? How to convert array to string in PHP ? How to call PHP function on the click of a Button ? Split a comma delimited string into an array in PHP How to pass JavaScript variables to PHP ? How to get parameters from a URL string in PHP?
[ { "code": null, "e": 26231, "s": 26203, "text": "\n18 Feb, 2022" }, { "code": null, "e": 27078, "s": 26231, "text": "Function overloading and overriding is the OOPs feature in PHP. In function overloading, more than one function can have same method signature but different number of arguments. But in case of function overriding, more than one functions will have same method signature and number of arguments. Function Overloading: Function overloading contains same function name and that function performs different task according to number of arguments. For example, find the area of certain shapes where radius are given then it should return area of circle if height and width are given then it should give area of rectangle and others. Like other OOP languages function overloading can not be done by native approach. In PHP function overloading is done with the help of magic function __call(). This function takes function name and arguments. Example: " }, { "code": null, "e": 27082, "s": 27078, "text": "php" }, { "code": "<?php// PHP program to explain function// overloading in PHP // Creating a class of type shapeclass shape { // __call is magic function which accepts // function name and arguments function __call($name_of_function, $arguments) { // It will match the function name if($name_of_function == 'area') { switch (count($arguments)) { // If there is only one argument // area of circle case 1: return 3.14 * $arguments[0]; // IF two arguments then area is rectangle; case 2: return $arguments[0]*$arguments[1]; } } }} // Declaring a shape type object$s = new Shape; // Function callecho($s->area(2));echo \"\\n\"; // calling area method for rectangleecho ($s->area(4, 2));?>", "e": 28004, "s": 27082, "text": null }, { "code": null, "e": 28011, "s": 28004, "text": "6.28\n8" }, { "code": null, "e": 28428, "s": 28013, "text": "Function Overriding: Function overriding is same as other OOPs programming languages. In function overriding, both parent and child classes should have same function name with and number of arguments. It is used to replace parent method in child class. The purpose of overriding is to change the behavior of parent class method. The two methods with the same name and same parameter is called overriding.Example: " }, { "code": null, "e": 28432, "s": 28428, "text": "php" }, { "code": "<?php// PHP program to implement// function overriding // This is parent classclass P { // Function geeks of parent class function geeks() { echo \"Parent\"; }} // This is child classclass C extends P { // Overriding geeks method function geeks() { echo \"\\nChild\"; }} // Reference type of parent$p = new P; // Reference type of child$c= new C; // print Parent$p->geeks(); // Print child$c->geeks();?>", "e": 28873, "s": 28432, "text": null }, { "code": null, "e": 28886, "s": 28873, "text": "Parent\nChild" }, { "code": null, "e": 29057, "s": 28888, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 29072, "s": 29057, "text": "adnanirshad158" }, { "code": null, "e": 29084, "s": 29072, "text": "anikaseth98" }, { "code": null, "e": 29101, "s": 29084, "text": "surinderdawra388" }, { "code": null, "e": 29114, "s": 29101, "text": "PHP-function" }, { "code": null, "e": 29118, "s": 29114, "text": "PHP" }, { "code": null, "e": 29131, "s": 29118, "text": "PHP Programs" }, { "code": null, "e": 29150, "s": 29131, "text": "Technical Scripter" }, { "code": null, "e": 29167, "s": 29150, "text": "Web Technologies" }, { "code": null, "e": 29171, "s": 29167, "text": "PHP" }, { "code": null, "e": 29269, "s": 29171, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29309, "s": 29269, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 29354, "s": 29309, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 29406, "s": 29354, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 29448, "s": 29406, "text": "How to pass JavaScript variables to PHP ?" }, { "code": null, "e": 29496, "s": 29448, "text": "How to get parameters from a URL string in PHP?" }, { "code": null, "e": 29536, "s": 29496, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 29588, "s": 29536, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 29640, "s": 29588, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 29682, "s": 29640, "text": "How to pass JavaScript variables to PHP ?" } ]
Multiple Linear Regression. A complete study — Model Interpretation... | by Sangeet Aggarwal | Towards Data Science
Linear Regression, one of the most popular and discussed models, is certainly the gateway to go deeper into Machine Learning (ML). Such a simplistic, straightforward approach to modeling is worth learning as one of your first steps into ML. Before moving forward, let us recall that Linear Regression can be broadly classified into two categories. Simple Linear Regression: It’s the simplest form of Linear Regression that is used when there is a single input variable for the output variable. If you are new to regression, then I strongly suggest you first read about Simple Linear Regression from the link below, where you would understand the underlying maths behind and the approach to this model using interesting data and hands-on coding. towardsdatascience.com Multiple Linear Regression: It’s a form of linear regression that is used when there are two or more predictors. We will see how multiple input variables together influence the output variable, while also learning how the calculations differ from that of Simple LR model. We will also build a regression model using Python. At last, we will go deeper into Linear Regression and will learn things like Collinearity, Hypothesis Testing, Feature Selection, and much more. Now one might wonder, we could also use simple linear regression to study our output against all independent variables separately. That would have made lives much easier right? No, it wouldn’t. “ To predict the outcome from multiple input variables. Duh!”. But, is that it? Well, hold that thought. Consider this, suppose you have to estimate the price of a certain house you want to buy. You know the floor area, the age of the house, its distance from your workplace, the crime rate of the place, etc. Now, some of these factors will affect the price of the house positively. For example more the area, the more the price. On the other hand, factors like distance from the workplace, and the crime rate can influence your estimate of the house negatively (unless you are a rich criminal with interest in Machine Learning looking for a hideout, yeah I don’t think so). Disadvantages of Simple Linear Regression → Running separate simple linear regressions will lead to different outcomes when we are interested in just one. Besides that, there may be an input variable that is itself correlated with or dependent on some other predictor. This can cause wrong predictions and unsatisfactory results. This is where Multiple Linear Regression comes into the picture. Here, Y is the output variable, and X terms are the corresponding input variables. Notice that this equation is just an extension of Simple Linear Regression, and each predictor has a corresponding slope coefficient (β). The first β term (βo) is the intercept constant and is the value of Y in absence of all predictors (i.e when all X terms are 0). It may or may or may not hold any significance in a given regression problem. It’s generally there to give a relevant nudge to the line/plane of regression. Let’s now understand this with the help of some data. We are going to use Advertising data which is available on the site of USC Marshall School of Business. You can download it here. If you have read my post on Simple Linear Regression, then you are already familiar with this data. If you haven’t, let me give you a quick brief. The advertising data set consists of the sales of a product in 200 different markets, along with advertising budgets for three different media: TV, radio, and newspaper. Here’s how it looks like: The first row of the data says that the advertising budgets for TV, radio, and newspaper were $230.1k, $37.8k, and $69.2k respectively, and the corresponding number of units that were sold was 22.1k (or 22,100). In Simple Linear Regression, we can see how each advertising medium affects sales when applied without the other two media. However, in practice, all three might be working together to impact net sales. We did not consider the combined effect of these media on sales. Multiple Linear Regression solves the problem by taking account of all the variables in a single expression. Hence, our Linear Regression model can now be expressed as: Finding the values of these constants(β) is what regression model does by minimizing the error function and fitting the best line or hyperplane (depending on the number of input variables). This is done by minimizing the Residual Sum of Squares (RSS), which is obtained by squaring the differences between actual and predicted outcomes. Because this method finds the least sum of squares, it is also known as the Ordinary Least Squares (OLS) method. In Python, there are two primary ways to implement the OLS algorithm. SciKit Learn: Just import the Linear Regression module from the Sklearn package and fit the model on the data. This method is pretty straightforward and you can see how to use it below. from sklearn.linear_model import LinearRegressionmodel = LinearRegression()model.fit(data.drop('sales', axis=1), data.sales) StatsModels: Another way is to use the Statsmodels package to implement OLS. Statsmodels is a Python package that allows performing various statistical tests on the data. We will use it here so that you can learn about this great Python library, and because it will be helpful for us in the later sections. # Importing required librariesimport pandas as pdimport statsmodels.formula.api as sm# Loading data - You can give the complete path to your data heread = pd.read_csv("Advertising.csv")# Fitting the OLS on datamodel = sm.ols('sales ~ TV + radio + newspaper', ad).fit()print(model.params) You should get the following output. Intercept 2.938889TV 0.045765radio 0.188530newspaper -0.001037 I encourage you to run the regression model using Scikit Learn as well and find the above parameters using model.coef_ & model.intercept_. Did you see the same results? Now that we have these values, how to interpret them? Here’s how: If we fix the budget for TV & newspaper, then increasing the radio budget by $1000 will lead to an increase in sales by around 189 units(0.189*1000). Similarly, by fixing the radio & newspaper, we infer an approximate rise of 46 units of products per $1000 increase in the TV budget. However, for the newspaper budget, since the coefficient is quite negligible (close to zero), it’s evident that the newspaper is not affecting the sales. In fact, it’s on the negative side of zero(-0.001) which, if the magnitude was big enough, could have meant that this agent is rather causing the sales to fall. But we cannot make that kind of inference with such negligible value. Let me tell you an interesting thing here. If we run Simple Linear Regression using just the newspaper budget against sales, we’ll observe the coefficient value of around 0.055, which is quite significant in comparison to what we saw above. Now, why is that? To understand this, let’s see how these variables are correlated with each other. ad.corr() Let’s visualize these numbers using a heatmap. import matplotlib.pyplot as plt%matplotlib inline> plt.imshow(ad.corr(), cmap=plt.cm.GnBu, interpolation='nearest',data=True)> plt.colorbar()> tick_marks = [i for i in range(len(ad.columns))]> plt.xticks(tick_marks, data.columns, rotation=45)> plt.yticks(tick_marks, data.columns, rotation=45) Here the dark squares represent a strong correlation (close to 1) while the lighter ones represent the weaker correlation(close to 0). That’s the reason, all the diagonals are dark blue, as a variable is fully correlated with itself. Now, the thing worth noticing here is that the correlation between newspaper and radio is 0.35. This indicates a fair relationship between newspaper and radio budgets. Hence, it can be inferred that → when the radio budget is increased for a product, there’s a tendency to spend more on newspapers as well. This is called collinearity and is referred to as a situation in which two or more input variables are linearly related. Hence, even though the Multiple Regression model shows no impact on sales by the newspaper, the Simple Regression model still does due to this multicollinearity and the absence of other input variables. Sales & Radio → probable causation Newspaper & Radio → multicollinearity Sales & Newspaper → transitive correlation Alright! We understood Linear Regression, we built the model and even interpreted the results. What we learned so far were the fundamentals of Linear Regression. However, while dealing with real-world problems, we generally go beyond this point to statistically analyze our model and do the necessary changes if required. One of the fundamental questions that should be answered while running Multiple Linear Regression is, whether or not, at least one of the predictors is useful in predicting the output. We saw that the three predictors TV, radio and newspaper had a different degree of linear relationship with the sales. But what if the relationship is just by chance and there is no actual impact on sales due to any of the predictors? The model can only give us numbers to establish a close enough linear relationship between the response variable and the predictors. However, it cannot prove the credibility of these relationships. To have some confidence, we take help from statistics and do something known as a Hypothesis Test. We start by forming a Null Hypothesis and a corresponding Alternative Hypothesis. Since our goal is to find if at least one predictor is useful in predicting the output, we are in a way hoping that at least one of the coefficients(not intercept) is non-zero, not just by a random chance but due to actual cause. To do this, we start by forming a Null Hypothesis: All the coefficients are equal to zero. Hence the Alternative Hypothesis would be: At least one coefficient is not zero. It is proved by rejecting the Null Hypothesis by finding strong statistical evidence. The hypothesis test is performed by using F-Statistic. The formula for this statistic contains Residual Sum of Squares (RSS) and the Total Sum of Squares (TSS), which we don’t have to worry about because the Statsmodels package takes care of this. The summary of the OLS model that we fit above contains the summary of all such statistics and can be obtained with this simple line of code: print(model.summary2()) If the value of F-statistic is equal to or very close to 1, then the results are in favor of the Null Hypothesis and we fail to reject it. But as we can see that the F-statistic is many folds larger than 1, thus providing strong evidence against the Null Hypothesis (that all coefficients are zero). Hence, we reject the Null Hypothesis and are confident that at least one predictor is useful in predicting the output. Note that F-statistic is not suitable when the number of predictors(p) is large, or if p is greater than the number of data samples (n). Hence, we can say that at least one of the three advertising agents is useful in predicting sales. But which one or which two are important? Are all of them important? To find this out, we will perform Feature Selection or variable selection. Now one way of doing this is trying all possible combinations i.e. Only TV Only radio Only newspaper TV & radio TV & newspaper radio & newspaper TV, radio & newspaper Here, it still looks feasible to try all 7 combinations, but if there are more predictors, the number of combinations will increase exponentially. For example, by adding only one more predictor to our case study, the total combinations would become 15. Just imagine having a dozen predictors. Hence we need more efficient ways to perform Feature Selection. Two of the most popular approaches to do feature selection are: Forward Selection: We start with a model without any predictor and just the intercept term. We then perform simple linear regression for each predictor to find the best performer(lowest RSS). We then add another variable to it and check for the best 2-variable combination again by calculating the lowest RSS(Residual Sum of Squares). After that the best 3-variable combination is checked, and so on. The approach is stopped when some stopping rule is satisfied. Backward Selection: We start with all variables in the model, and remove the variable that is the least statistically significant (greater p-value: check the model summary above to find p-values of variables). This is repeated until a stopping rule is reached. For instance, we may stop when there is no further improvement in the model score. In this post, I’ll walk you through the forward selection method. To begin with, let’s understand how we are going to select or reject the added variable. We are going to use 2 measures to evaluate our new model after each addition: RSS and R2. We are already familiar with RSS which is the Residual Sum of Squares and is calculated by squaring the difference between actual outputs and predicted outcomes. It should be minimum for the model to perform well. R2 is the measure of the degree to which variance in data is explained by the model. Mathematically, it’s the square of the correlation between actual and predicted outcomes. R2 closer to 1 indicates that the model is good and explains the variance in data well. A value closer to zero indicates a poor model. Luckily, it’s calculated for us by the OLS module in Statsmodels. So let’s begin. # Defining a function to evaluate a modeldef evaluateModel(model): print("RSS = ", ((ad.sales - model.predict())**2).sum()) print("R2 = ", model.rsquared) Let’s first evaluate models with single predictors one by one, starting with TV. # For TVmodel_TV = sm.ols('sales ~ TV', ad).fit()evaluateModel(model_TV) RSS = 2102.5305831313512R^2 = 0.611875050850071 # For radiomodel_radio = sm.ols('sales ~ radio', ad).fit()evaluateModel(model_radio) RSS = 3618.479549025088R^2 = 0.33203245544529525 # For newspapermodel_newspaper = sm.ols('sales ~ newspaper', ad).fit()evaluateModel(model_newspaper) RSS = 5134.804544111939R^2 = 0.05212044544430516 We observe that for model_TV, the RSS is least and R2 value is the most among all the models. Hence we select model_TV as our base model to move forward. Now, we will add the radio and newspaper one by one and check the new values. # For TV & radiomodel_TV_radio = sm.ols('sales ~ TV + radio', ad).fit()evaluateModel(model_TV_radio) RSS = 556.9139800676184R^2 = 0.8971942610828957 As we can see that our values have improved tremendously. RSS has decreased and R2 has increased further, as compared to model_TV. It’s a good sign. Let’s now check the same for TV and newspaper. # For TV & newspapermodel_TV_radio = sm.ols('sales ~ TV + newspaper', ad).fit()evaluateModel(model_TV_newspaper) RSS = 1918.5618118968275R^2 = 0.6458354938293271 The values have improved by adding newspaper too, but not as much as with the radio. Hence, at this step, we will proceed with the TV & radio model and will observe the difference when we add newspaper to this model. # For TV, radio & newspapermodel_all = sm.ols('sales ~ TV + radio + newspaper', ad).fit()evaluateModel(model_all) RSS = 556.8252629021872R^2 = 0.8972106381789522 The values have not improved with any significance. Hence, it’s imperative to not add newspaper and finalize the model with TV and radio as selected features. So our final model can be expressed as below: Plotting the variables TV, radio, and sales in the 3D graph, we can visualize how our model has fit a regression plane to the data. That’s it for Multiple Linear Regression. You can find the full code behind this post here. I hope you had a good time reading and learning. For more, stay tuned. If you are new to Data Science and Machine Learning and wondering where to begin your journey from, do check the link below, where I have mentioned step by step method to learn Data Science, with lots of sources for you to choose from. towardsdatascience.com Can’t wait? If you want to dive right into a course, check out the career tracks in Data Science that suits you, from the link below.
[ { "code": null, "e": 413, "s": 172, "text": "Linear Regression, one of the most popular and discussed models, is certainly the gateway to go deeper into Machine Learning (ML). Such a simplistic, straightforward approach to modeling is worth learning as one of your first steps into ML." }, { "code": null, "e": 520, "s": 413, "text": "Before moving forward, let us recall that Linear Regression can be broadly classified into two categories." }, { "code": null, "e": 666, "s": 520, "text": "Simple Linear Regression: It’s the simplest form of Linear Regression that is used when there is a single input variable for the output variable." }, { "code": null, "e": 917, "s": 666, "text": "If you are new to regression, then I strongly suggest you first read about Simple Linear Regression from the link below, where you would understand the underlying maths behind and the approach to this model using interesting data and hands-on coding." }, { "code": null, "e": 940, "s": 917, "text": "towardsdatascience.com" }, { "code": null, "e": 1053, "s": 940, "text": "Multiple Linear Regression: It’s a form of linear regression that is used when there are two or more predictors." }, { "code": null, "e": 1264, "s": 1053, "text": "We will see how multiple input variables together influence the output variable, while also learning how the calculations differ from that of Simple LR model. We will also build a regression model using Python." }, { "code": null, "e": 1409, "s": 1264, "text": "At last, we will go deeper into Linear Regression and will learn things like Collinearity, Hypothesis Testing, Feature Selection, and much more." }, { "code": null, "e": 1586, "s": 1409, "text": "Now one might wonder, we could also use simple linear regression to study our output against all independent variables separately. That would have made lives much easier right?" }, { "code": null, "e": 1603, "s": 1586, "text": "No, it wouldn’t." }, { "code": null, "e": 1708, "s": 1603, "text": "“ To predict the outcome from multiple input variables. Duh!”. But, is that it? Well, hold that thought." }, { "code": null, "e": 1913, "s": 1708, "text": "Consider this, suppose you have to estimate the price of a certain house you want to buy. You know the floor area, the age of the house, its distance from your workplace, the crime rate of the place, etc." }, { "code": null, "e": 2279, "s": 1913, "text": "Now, some of these factors will affect the price of the house positively. For example more the area, the more the price. On the other hand, factors like distance from the workplace, and the crime rate can influence your estimate of the house negatively (unless you are a rich criminal with interest in Machine Learning looking for a hideout, yeah I don’t think so)." }, { "code": null, "e": 2609, "s": 2279, "text": "Disadvantages of Simple Linear Regression → Running separate simple linear regressions will lead to different outcomes when we are interested in just one. Besides that, there may be an input variable that is itself correlated with or dependent on some other predictor. This can cause wrong predictions and unsatisfactory results." }, { "code": null, "e": 2674, "s": 2609, "text": "This is where Multiple Linear Regression comes into the picture." }, { "code": null, "e": 2895, "s": 2674, "text": "Here, Y is the output variable, and X terms are the corresponding input variables. Notice that this equation is just an extension of Simple Linear Regression, and each predictor has a corresponding slope coefficient (β)." }, { "code": null, "e": 3181, "s": 2895, "text": "The first β term (βo) is the intercept constant and is the value of Y in absence of all predictors (i.e when all X terms are 0). It may or may or may not hold any significance in a given regression problem. It’s generally there to give a relevant nudge to the line/plane of regression." }, { "code": null, "e": 3235, "s": 3181, "text": "Let’s now understand this with the help of some data." }, { "code": null, "e": 3365, "s": 3235, "text": "We are going to use Advertising data which is available on the site of USC Marshall School of Business. You can download it here." }, { "code": null, "e": 3512, "s": 3365, "text": "If you have read my post on Simple Linear Regression, then you are already familiar with this data. If you haven’t, let me give you a quick brief." }, { "code": null, "e": 3708, "s": 3512, "text": "The advertising data set consists of the sales of a product in 200 different markets, along with advertising budgets for three different media: TV, radio, and newspaper. Here’s how it looks like:" }, { "code": null, "e": 3920, "s": 3708, "text": "The first row of the data says that the advertising budgets for TV, radio, and newspaper were $230.1k, $37.8k, and $69.2k respectively, and the corresponding number of units that were sold was 22.1k (or 22,100)." }, { "code": null, "e": 4188, "s": 3920, "text": "In Simple Linear Regression, we can see how each advertising medium affects sales when applied without the other two media. However, in practice, all three might be working together to impact net sales. We did not consider the combined effect of these media on sales." }, { "code": null, "e": 4357, "s": 4188, "text": "Multiple Linear Regression solves the problem by taking account of all the variables in a single expression. Hence, our Linear Regression model can now be expressed as:" }, { "code": null, "e": 4547, "s": 4357, "text": "Finding the values of these constants(β) is what regression model does by minimizing the error function and fitting the best line or hyperplane (depending on the number of input variables)." }, { "code": null, "e": 4694, "s": 4547, "text": "This is done by minimizing the Residual Sum of Squares (RSS), which is obtained by squaring the differences between actual and predicted outcomes." }, { "code": null, "e": 4877, "s": 4694, "text": "Because this method finds the least sum of squares, it is also known as the Ordinary Least Squares (OLS) method. In Python, there are two primary ways to implement the OLS algorithm." }, { "code": null, "e": 5063, "s": 4877, "text": "SciKit Learn: Just import the Linear Regression module from the Sklearn package and fit the model on the data. This method is pretty straightforward and you can see how to use it below." }, { "code": null, "e": 5188, "s": 5063, "text": "from sklearn.linear_model import LinearRegressionmodel = LinearRegression()model.fit(data.drop('sales', axis=1), data.sales)" }, { "code": null, "e": 5495, "s": 5188, "text": "StatsModels: Another way is to use the Statsmodels package to implement OLS. Statsmodels is a Python package that allows performing various statistical tests on the data. We will use it here so that you can learn about this great Python library, and because it will be helpful for us in the later sections." }, { "code": null, "e": 5783, "s": 5495, "text": "# Importing required librariesimport pandas as pdimport statsmodels.formula.api as sm# Loading data - You can give the complete path to your data heread = pd.read_csv(\"Advertising.csv\")# Fitting the OLS on datamodel = sm.ols('sales ~ TV + radio + newspaper', ad).fit()print(model.params)" }, { "code": null, "e": 5820, "s": 5783, "text": "You should get the following output." }, { "code": null, "e": 5905, "s": 5820, "text": "Intercept 2.938889TV 0.045765radio 0.188530newspaper -0.001037" }, { "code": null, "e": 6074, "s": 5905, "text": "I encourage you to run the regression model using Scikit Learn as well and find the above parameters using model.coef_ & model.intercept_. Did you see the same results?" }, { "code": null, "e": 6140, "s": 6074, "text": "Now that we have these values, how to interpret them? Here’s how:" }, { "code": null, "e": 6290, "s": 6140, "text": "If we fix the budget for TV & newspaper, then increasing the radio budget by $1000 will lead to an increase in sales by around 189 units(0.189*1000)." }, { "code": null, "e": 6424, "s": 6290, "text": "Similarly, by fixing the radio & newspaper, we infer an approximate rise of 46 units of products per $1000 increase in the TV budget." }, { "code": null, "e": 6809, "s": 6424, "text": "However, for the newspaper budget, since the coefficient is quite negligible (close to zero), it’s evident that the newspaper is not affecting the sales. In fact, it’s on the negative side of zero(-0.001) which, if the magnitude was big enough, could have meant that this agent is rather causing the sales to fall. But we cannot make that kind of inference with such negligible value." }, { "code": null, "e": 7068, "s": 6809, "text": "Let me tell you an interesting thing here. If we run Simple Linear Regression using just the newspaper budget against sales, we’ll observe the coefficient value of around 0.055, which is quite significant in comparison to what we saw above. Now, why is that?" }, { "code": null, "e": 7150, "s": 7068, "text": "To understand this, let’s see how these variables are correlated with each other." }, { "code": null, "e": 7160, "s": 7150, "text": "ad.corr()" }, { "code": null, "e": 7207, "s": 7160, "text": "Let’s visualize these numbers using a heatmap." }, { "code": null, "e": 7508, "s": 7207, "text": "import matplotlib.pyplot as plt%matplotlib inline> plt.imshow(ad.corr(), cmap=plt.cm.GnBu, interpolation='nearest',data=True)> plt.colorbar()> tick_marks = [i for i in range(len(ad.columns))]> plt.xticks(tick_marks, data.columns, rotation=45)> plt.yticks(tick_marks, data.columns, rotation=45)" }, { "code": null, "e": 7742, "s": 7508, "text": "Here the dark squares represent a strong correlation (close to 1) while the lighter ones represent the weaker correlation(close to 0). That’s the reason, all the diagonals are dark blue, as a variable is fully correlated with itself." }, { "code": null, "e": 8049, "s": 7742, "text": "Now, the thing worth noticing here is that the correlation between newspaper and radio is 0.35. This indicates a fair relationship between newspaper and radio budgets. Hence, it can be inferred that → when the radio budget is increased for a product, there’s a tendency to spend more on newspapers as well." }, { "code": null, "e": 8170, "s": 8049, "text": "This is called collinearity and is referred to as a situation in which two or more input variables are linearly related." }, { "code": null, "e": 8373, "s": 8170, "text": "Hence, even though the Multiple Regression model shows no impact on sales by the newspaper, the Simple Regression model still does due to this multicollinearity and the absence of other input variables." }, { "code": null, "e": 8408, "s": 8373, "text": "Sales & Radio → probable causation" }, { "code": null, "e": 8446, "s": 8408, "text": "Newspaper & Radio → multicollinearity" }, { "code": null, "e": 8489, "s": 8446, "text": "Sales & Newspaper → transitive correlation" }, { "code": null, "e": 8811, "s": 8489, "text": "Alright! We understood Linear Regression, we built the model and even interpreted the results. What we learned so far were the fundamentals of Linear Regression. However, while dealing with real-world problems, we generally go beyond this point to statistically analyze our model and do the necessary changes if required." }, { "code": null, "e": 8996, "s": 8811, "text": "One of the fundamental questions that should be answered while running Multiple Linear Regression is, whether or not, at least one of the predictors is useful in predicting the output." }, { "code": null, "e": 9231, "s": 8996, "text": "We saw that the three predictors TV, radio and newspaper had a different degree of linear relationship with the sales. But what if the relationship is just by chance and there is no actual impact on sales due to any of the predictors?" }, { "code": null, "e": 9429, "s": 9231, "text": "The model can only give us numbers to establish a close enough linear relationship between the response variable and the predictors. However, it cannot prove the credibility of these relationships." }, { "code": null, "e": 9610, "s": 9429, "text": "To have some confidence, we take help from statistics and do something known as a Hypothesis Test. We start by forming a Null Hypothesis and a corresponding Alternative Hypothesis." }, { "code": null, "e": 9840, "s": 9610, "text": "Since our goal is to find if at least one predictor is useful in predicting the output, we are in a way hoping that at least one of the coefficients(not intercept) is non-zero, not just by a random chance but due to actual cause." }, { "code": null, "e": 9931, "s": 9840, "text": "To do this, we start by forming a Null Hypothesis: All the coefficients are equal to zero." }, { "code": null, "e": 10098, "s": 9931, "text": "Hence the Alternative Hypothesis would be: At least one coefficient is not zero. It is proved by rejecting the Null Hypothesis by finding strong statistical evidence." }, { "code": null, "e": 10488, "s": 10098, "text": "The hypothesis test is performed by using F-Statistic. The formula for this statistic contains Residual Sum of Squares (RSS) and the Total Sum of Squares (TSS), which we don’t have to worry about because the Statsmodels package takes care of this. The summary of the OLS model that we fit above contains the summary of all such statistics and can be obtained with this simple line of code:" }, { "code": null, "e": 10512, "s": 10488, "text": "print(model.summary2())" }, { "code": null, "e": 10651, "s": 10512, "text": "If the value of F-statistic is equal to or very close to 1, then the results are in favor of the Null Hypothesis and we fail to reject it." }, { "code": null, "e": 10931, "s": 10651, "text": "But as we can see that the F-statistic is many folds larger than 1, thus providing strong evidence against the Null Hypothesis (that all coefficients are zero). Hence, we reject the Null Hypothesis and are confident that at least one predictor is useful in predicting the output." }, { "code": null, "e": 11068, "s": 10931, "text": "Note that F-statistic is not suitable when the number of predictors(p) is large, or if p is greater than the number of data samples (n)." }, { "code": null, "e": 11167, "s": 11068, "text": "Hence, we can say that at least one of the three advertising agents is useful in predicting sales." }, { "code": null, "e": 11378, "s": 11167, "text": "But which one or which two are important? Are all of them important? To find this out, we will perform Feature Selection or variable selection. Now one way of doing this is trying all possible combinations i.e." }, { "code": null, "e": 11386, "s": 11378, "text": "Only TV" }, { "code": null, "e": 11397, "s": 11386, "text": "Only radio" }, { "code": null, "e": 11412, "s": 11397, "text": "Only newspaper" }, { "code": null, "e": 11423, "s": 11412, "text": "TV & radio" }, { "code": null, "e": 11438, "s": 11423, "text": "TV & newspaper" }, { "code": null, "e": 11456, "s": 11438, "text": "radio & newspaper" }, { "code": null, "e": 11478, "s": 11456, "text": "TV, radio & newspaper" }, { "code": null, "e": 11771, "s": 11478, "text": "Here, it still looks feasible to try all 7 combinations, but if there are more predictors, the number of combinations will increase exponentially. For example, by adding only one more predictor to our case study, the total combinations would become 15. Just imagine having a dozen predictors." }, { "code": null, "e": 11835, "s": 11771, "text": "Hence we need more efficient ways to perform Feature Selection." }, { "code": null, "e": 11899, "s": 11835, "text": "Two of the most popular approaches to do feature selection are:" }, { "code": null, "e": 12362, "s": 11899, "text": "Forward Selection: We start with a model without any predictor and just the intercept term. We then perform simple linear regression for each predictor to find the best performer(lowest RSS). We then add another variable to it and check for the best 2-variable combination again by calculating the lowest RSS(Residual Sum of Squares). After that the best 3-variable combination is checked, and so on. The approach is stopped when some stopping rule is satisfied." }, { "code": null, "e": 12706, "s": 12362, "text": "Backward Selection: We start with all variables in the model, and remove the variable that is the least statistically significant (greater p-value: check the model summary above to find p-values of variables). This is repeated until a stopping rule is reached. For instance, we may stop when there is no further improvement in the model score." }, { "code": null, "e": 12861, "s": 12706, "text": "In this post, I’ll walk you through the forward selection method. To begin with, let’s understand how we are going to select or reject the added variable." }, { "code": null, "e": 12951, "s": 12861, "text": "We are going to use 2 measures to evaluate our new model after each addition: RSS and R2." }, { "code": null, "e": 13165, "s": 12951, "text": "We are already familiar with RSS which is the Residual Sum of Squares and is calculated by squaring the difference between actual outputs and predicted outcomes. It should be minimum for the model to perform well." }, { "code": null, "e": 13475, "s": 13165, "text": "R2 is the measure of the degree to which variance in data is explained by the model. Mathematically, it’s the square of the correlation between actual and predicted outcomes. R2 closer to 1 indicates that the model is good and explains the variance in data well. A value closer to zero indicates a poor model." }, { "code": null, "e": 13557, "s": 13475, "text": "Luckily, it’s calculated for us by the OLS module in Statsmodels. So let’s begin." }, { "code": null, "e": 13718, "s": 13557, "text": "# Defining a function to evaluate a modeldef evaluateModel(model): print(\"RSS = \", ((ad.sales - model.predict())**2).sum()) print(\"R2 = \", model.rsquared)" }, { "code": null, "e": 13799, "s": 13718, "text": "Let’s first evaluate models with single predictors one by one, starting with TV." }, { "code": null, "e": 13872, "s": 13799, "text": "# For TVmodel_TV = sm.ols('sales ~ TV', ad).fit()evaluateModel(model_TV)" }, { "code": null, "e": 13920, "s": 13872, "text": "RSS = 2102.5305831313512R^2 = 0.611875050850071" }, { "code": null, "e": 14005, "s": 13920, "text": "# For radiomodel_radio = sm.ols('sales ~ radio', ad).fit()evaluateModel(model_radio)" }, { "code": null, "e": 14054, "s": 14005, "text": "RSS = 3618.479549025088R^2 = 0.33203245544529525" }, { "code": null, "e": 14155, "s": 14054, "text": "# For newspapermodel_newspaper = sm.ols('sales ~ newspaper', ad).fit()evaluateModel(model_newspaper)" }, { "code": null, "e": 14204, "s": 14155, "text": "RSS = 5134.804544111939R^2 = 0.05212044544430516" }, { "code": null, "e": 14358, "s": 14204, "text": "We observe that for model_TV, the RSS is least and R2 value is the most among all the models. Hence we select model_TV as our base model to move forward." }, { "code": null, "e": 14436, "s": 14358, "text": "Now, we will add the radio and newspaper one by one and check the new values." }, { "code": null, "e": 14537, "s": 14436, "text": "# For TV & radiomodel_TV_radio = sm.ols('sales ~ TV + radio', ad).fit()evaluateModel(model_TV_radio)" }, { "code": null, "e": 14585, "s": 14537, "text": "RSS = 556.9139800676184R^2 = 0.8971942610828957" }, { "code": null, "e": 14781, "s": 14585, "text": "As we can see that our values have improved tremendously. RSS has decreased and R2 has increased further, as compared to model_TV. It’s a good sign. Let’s now check the same for TV and newspaper." }, { "code": null, "e": 14894, "s": 14781, "text": "# For TV & newspapermodel_TV_radio = sm.ols('sales ~ TV + newspaper', ad).fit()evaluateModel(model_TV_newspaper)" }, { "code": null, "e": 14943, "s": 14894, "text": "RSS = 1918.5618118968275R^2 = 0.6458354938293271" }, { "code": null, "e": 15160, "s": 14943, "text": "The values have improved by adding newspaper too, but not as much as with the radio. Hence, at this step, we will proceed with the TV & radio model and will observe the difference when we add newspaper to this model." }, { "code": null, "e": 15274, "s": 15160, "text": "# For TV, radio & newspapermodel_all = sm.ols('sales ~ TV + radio + newspaper', ad).fit()evaluateModel(model_all)" }, { "code": null, "e": 15322, "s": 15274, "text": "RSS = 556.8252629021872R^2 = 0.8972106381789522" }, { "code": null, "e": 15481, "s": 15322, "text": "The values have not improved with any significance. Hence, it’s imperative to not add newspaper and finalize the model with TV and radio as selected features." }, { "code": null, "e": 15527, "s": 15481, "text": "So our final model can be expressed as below:" }, { "code": null, "e": 15659, "s": 15527, "text": "Plotting the variables TV, radio, and sales in the 3D graph, we can visualize how our model has fit a regression plane to the data." }, { "code": null, "e": 15822, "s": 15659, "text": "That’s it for Multiple Linear Regression. You can find the full code behind this post here. I hope you had a good time reading and learning. For more, stay tuned." }, { "code": null, "e": 16058, "s": 15822, "text": "If you are new to Data Science and Machine Learning and wondering where to begin your journey from, do check the link below, where I have mentioned step by step method to learn Data Science, with lots of sources for you to choose from." }, { "code": null, "e": 16081, "s": 16058, "text": "towardsdatascience.com" } ]
Support Vector Machines — Soft Margin Formulation and Kernel Trick | by Rishabh Misra | Towards Data Science
Support Vector Machine (SVM) is one of the most popular classification techniques which aims to minimize the number of misclassification errors directly. There are many accessible resources to understand the basics of how Support Vector Machines (SVMs) work, however, in almost all the real-world applications (where the data is linearly inseparable), SVMs use some advanced concepts. The goal of this post is to explain the concepts of Soft Margin Formulation and Kernel Trick that SVMs employ to classify linearly inseparable data. If you want to get a refresher on the basics of SVM first, I’d recommend going through the following post. towardsdatascience.com Before we move on to the concepts of Soft Margin and Kernel trick, let us establish the need of them. Suppose we have some data and it can be depicted as following in the 2D space: From the figure, it is evident that there’s no specific linear decision boundary that can perfectly separate the data, i.e. the data is linearly inseparable. We can have a similar situation in higher-dimensional representations as well. This can be attributed to the fact that usually, the features we derive from the data don’t contain sufficient information so that we can clearly separate the two classes. This is usually the case in many real-world applications. Fortunately, researchers have already come up with techniques that can handle situations like these. Let’s see what they are and how they work. This idea is based on a simple premise: allow SVM to make a certain number of mistakes and keep margin as wide as possible so that other points can still be classified correctly. This can be done simply by modifying the objective of SVM. Let us briefly go over the motivation for having this kind of formulation. As mentioned earlier, almost all real-world applications have data that is linearly inseparable. In rare cases where the data is linearly separable, we might not want to choose a decision boundary that perfectly separates the data to avoid overfitting. For example, consider the following diagram: Here the red decision boundary perfectly separates all the training points. However, is it really a good idea of having a decision boundary with such less margin? Do you think such kind of decision boundary will generalize well on unseen data? The answer is: No. The green decision boundary has a wider margin that would allow it to generalize well on unseen data. In that sense, soft margin formulation would also help in avoiding the overfitting problem. Let us see how we can modify our objective to achieve the desired behavior. In this new setting, we would aim to minimize the following objective: This differs from the original objective in the second term. Here, C is a hyperparameter that decides the trade-off between maximizing the margin and minimizing the mistakes. When C is small, classification mistakes are given less importance and focus is more on maximizing the margin, whereas when C is large, the focus is more on avoiding misclassification at the expense of keeping the margin small. At this point, we should note, however, that not all mistakes are equal. Data points that are far away on the wrong side of the decision boundary should incur more penalty as compared to the ones that are closer. Let’s see how this could be incorporated with the help of the following diagram. The idea is: for every data point x_i, we introduce a slack variable ξ_i. The value of ξ_i is the distance of x_i from the corresponding class’s margin if x_i is on the wrong side of the margin, otherwise zero. Thus the points that are far away from the margin on the wrong side would get more penalty. With this idea, each data point x_i needs to satisfy the following constraint: Here, the left-hand side of the inequality could be thought of like the confidence of classification. Confidence score ≥ 1 suggests that classifier has classified the point correctly. However, if confidence score < 1, it means that classifier did not classify the point correctly and incurring a linear penalty of ξ_i. Given these constraints, our objective is to minimize the following function: where we have used the concepts of Lagrange Multiplier for optimizing loss function under constraints. Let us compare this with SVM’s objective that handles the linearly separable cases (as given below). We see that only ξ_i terms are extra in the modified objective and everything else is the same. Point to note: In the final solution, λ_is corresponding to points that are closest to the margin and on the wrong side of the margin (i.e. having non-zero ξ_i) would be non-zero as they play a key role in positioning of the decision boundary, essentially making them the support vectors. Now let us explore the second solution of using “Kernel Trick” to tackle the problem of linear inseparability. But first, we should learn what Kernel functions are. Kernel functions are generalized functions that take two vectors (of any dimension) as input and output a score that denotes how similar the input vectors are. A simple Kernel function you already know is the dot product function: if the dot product is small, we conclude that vectors are different and if the dot product is large, we conclude that vectors are more similar. If you are interested in knowing about other types of Kernel functions, this would be a good source. Let us look at the objective function for the linearly separable case: This is a modified form of the objective in equation 4. Here, we have substituted the optimal value of w and b. These optimal values can be calculated by differentiating equation 4 with respect to these parameters and equating it to 0. We can observe from equation 5 that objective depends on the dot product of input vector pairs (x_i . x_j), which is nothing but a Kernel function. Now here’s a good thing: we don’t have to be restricted to a simple Kernel function like dot product. We can use any fancy Kernel function in place of dot product that has the capability of measuring similarity in higher dimensions (where it could be more accurate; more on this later), without increasing the computational costs much. This is essentially known as the Kernel Trick. A Kernel function can be written mathematically as follows: Here x and y are input vectors, φ is a transformation function and < , > denotes dot product operation. In the case of dot product function, φ just maps the input vector to itself. Kernel functions essentially take the dot product of transformed input vectors. Now let us consider the case depicted in figure 4 below. We see that there is no linear decision boundary in 2d space that could perfectly separate the data points. A circular (or quadratic) decision boundary might do the job, however, linear classifiers are not capable of coming up with these types of decision boundaries. In figure 4, each point P is represented by the features of form (x,y) in 2D space. Looking at the desirable decision boundary, we can define a transformation function φ for a point P as φ(P) = (x^2, y^2, √2xy) (why we came up with such a transformation would be clear in just a moment). Let’s see what the Kernel function looks like for this type of transformation for two points P_1 and P_2. If we observe the final form of the Kernel function, it’s nothing but a circle! This means we have changed our notion of similarity: instead of measuring similarity by how close the points are (using the dot product), we are measuring similarity based on whether points are within a circle. In this sense, defining such a transformation allowed us to have a non-linear decision boundary in 2D space (it is still linear in the original 3D space). It could be a lot to keep track of, so following is a brief summary of the decisions we have taken: 1 - Each point P is represented by (x,y) coordinates in 2D space.2 - We project the points to 3D space by transforming their coordinates to (x^2, y^2, √2xy)3 - Points which have high value of x.y would move upwards along the z-axis (in this case, mostly the red circles). This video provides a good visualization of the same.4 - We find a hyperplane in 3D space that would perfectly separate the classes.5 - The form of Kernel function indicates that this hyperplane would form a circle in 2D space, thus giving us a non-linear decision boundary. And the main takeaway is: By embedding the data in a higher-dimensional feature space, we can keep using a linear classifier! A caveat here is that these transformations could increase the feature space drastically and that increases the computational costs. Is there any way we can reap the aforementioned benefits while not increasing the computational costs much? Turns out there is! Let us try to rewrite the Kernel function in equation 7: Whoa! So the value of Kernel function (thus, the similarity between points in 3D space) is just the square of the dot product between points in 2D space. Pretty great, right?! But how did this happen? The reason for this is that we chose our transformation function φ wisely. And as long as we continue to do that, we can circumvent the transformation step and calculate the value of Kernel function directly from the similarity between points in 2D space. This, in turn, would also curb the computational costs. We have many popular Kernel functions which have this nice property and can be used out of the box (we don’t need to search for perfect φ). With this, we have reached the end of this post. Hopefully, the details provided in this article provided you a good insight into what makes SVM a powerful linear classifier. In case you have any questions or suggestions, please let me know in the comments. Cheers! 🥂 If you liked this article and interested in my future efforts, consider following me on Twitter: https://twitter.com/rishabh_misra_
[ { "code": null, "e": 557, "s": 172, "text": "Support Vector Machine (SVM) is one of the most popular classification techniques which aims to minimize the number of misclassification errors directly. There are many accessible resources to understand the basics of how Support Vector Machines (SVMs) work, however, in almost all the real-world applications (where the data is linearly inseparable), SVMs use some advanced concepts." }, { "code": null, "e": 706, "s": 557, "text": "The goal of this post is to explain the concepts of Soft Margin Formulation and Kernel Trick that SVMs employ to classify linearly inseparable data." }, { "code": null, "e": 813, "s": 706, "text": "If you want to get a refresher on the basics of SVM first, I’d recommend going through the following post." }, { "code": null, "e": 836, "s": 813, "text": "towardsdatascience.com" }, { "code": null, "e": 1017, "s": 836, "text": "Before we move on to the concepts of Soft Margin and Kernel trick, let us establish the need of them. Suppose we have some data and it can be depicted as following in the 2D space:" }, { "code": null, "e": 1628, "s": 1017, "text": "From the figure, it is evident that there’s no specific linear decision boundary that can perfectly separate the data, i.e. the data is linearly inseparable. We can have a similar situation in higher-dimensional representations as well. This can be attributed to the fact that usually, the features we derive from the data don’t contain sufficient information so that we can clearly separate the two classes. This is usually the case in many real-world applications. Fortunately, researchers have already come up with techniques that can handle situations like these. Let’s see what they are and how they work." }, { "code": null, "e": 1866, "s": 1628, "text": "This idea is based on a simple premise: allow SVM to make a certain number of mistakes and keep margin as wide as possible so that other points can still be classified correctly. This can be done simply by modifying the objective of SVM." }, { "code": null, "e": 1941, "s": 1866, "text": "Let us briefly go over the motivation for having this kind of formulation." }, { "code": null, "e": 2038, "s": 1941, "text": "As mentioned earlier, almost all real-world applications have data that is linearly inseparable." }, { "code": null, "e": 2239, "s": 2038, "text": "In rare cases where the data is linearly separable, we might not want to choose a decision boundary that perfectly separates the data to avoid overfitting. For example, consider the following diagram:" }, { "code": null, "e": 2696, "s": 2239, "text": "Here the red decision boundary perfectly separates all the training points. However, is it really a good idea of having a decision boundary with such less margin? Do you think such kind of decision boundary will generalize well on unseen data? The answer is: No. The green decision boundary has a wider margin that would allow it to generalize well on unseen data. In that sense, soft margin formulation would also help in avoiding the overfitting problem." }, { "code": null, "e": 2843, "s": 2696, "text": "Let us see how we can modify our objective to achieve the desired behavior. In this new setting, we would aim to minimize the following objective:" }, { "code": null, "e": 3246, "s": 2843, "text": "This differs from the original objective in the second term. Here, C is a hyperparameter that decides the trade-off between maximizing the margin and minimizing the mistakes. When C is small, classification mistakes are given less importance and focus is more on maximizing the margin, whereas when C is large, the focus is more on avoiding misclassification at the expense of keeping the margin small." }, { "code": null, "e": 3540, "s": 3246, "text": "At this point, we should note, however, that not all mistakes are equal. Data points that are far away on the wrong side of the decision boundary should incur more penalty as compared to the ones that are closer. Let’s see how this could be incorporated with the help of the following diagram." }, { "code": null, "e": 3843, "s": 3540, "text": "The idea is: for every data point x_i, we introduce a slack variable ξ_i. The value of ξ_i is the distance of x_i from the corresponding class’s margin if x_i is on the wrong side of the margin, otherwise zero. Thus the points that are far away from the margin on the wrong side would get more penalty." }, { "code": null, "e": 3922, "s": 3843, "text": "With this idea, each data point x_i needs to satisfy the following constraint:" }, { "code": null, "e": 4241, "s": 3922, "text": "Here, the left-hand side of the inequality could be thought of like the confidence of classification. Confidence score ≥ 1 suggests that classifier has classified the point correctly. However, if confidence score < 1, it means that classifier did not classify the point correctly and incurring a linear penalty of ξ_i." }, { "code": null, "e": 4319, "s": 4241, "text": "Given these constraints, our objective is to minimize the following function:" }, { "code": null, "e": 4523, "s": 4319, "text": "where we have used the concepts of Lagrange Multiplier for optimizing loss function under constraints. Let us compare this with SVM’s objective that handles the linearly separable cases (as given below)." }, { "code": null, "e": 4619, "s": 4523, "text": "We see that only ξ_i terms are extra in the modified objective and everything else is the same." }, { "code": null, "e": 4908, "s": 4619, "text": "Point to note: In the final solution, λ_is corresponding to points that are closest to the margin and on the wrong side of the margin (i.e. having non-zero ξ_i) would be non-zero as they play a key role in positioning of the decision boundary, essentially making them the support vectors." }, { "code": null, "e": 5073, "s": 4908, "text": "Now let us explore the second solution of using “Kernel Trick” to tackle the problem of linear inseparability. But first, we should learn what Kernel functions are." }, { "code": null, "e": 5549, "s": 5073, "text": "Kernel functions are generalized functions that take two vectors (of any dimension) as input and output a score that denotes how similar the input vectors are. A simple Kernel function you already know is the dot product function: if the dot product is small, we conclude that vectors are different and if the dot product is large, we conclude that vectors are more similar. If you are interested in knowing about other types of Kernel functions, this would be a good source." }, { "code": null, "e": 5620, "s": 5549, "text": "Let us look at the objective function for the linearly separable case:" }, { "code": null, "e": 5856, "s": 5620, "text": "This is a modified form of the objective in equation 4. Here, we have substituted the optimal value of w and b. These optimal values can be calculated by differentiating equation 4 with respect to these parameters and equating it to 0." }, { "code": null, "e": 6387, "s": 5856, "text": "We can observe from equation 5 that objective depends on the dot product of input vector pairs (x_i . x_j), which is nothing but a Kernel function. Now here’s a good thing: we don’t have to be restricted to a simple Kernel function like dot product. We can use any fancy Kernel function in place of dot product that has the capability of measuring similarity in higher dimensions (where it could be more accurate; more on this later), without increasing the computational costs much. This is essentially known as the Kernel Trick." }, { "code": null, "e": 6447, "s": 6387, "text": "A Kernel function can be written mathematically as follows:" }, { "code": null, "e": 6628, "s": 6447, "text": "Here x and y are input vectors, φ is a transformation function and < , > denotes dot product operation. In the case of dot product function, φ just maps the input vector to itself." }, { "code": null, "e": 6708, "s": 6628, "text": "Kernel functions essentially take the dot product of transformed input vectors." }, { "code": null, "e": 7033, "s": 6708, "text": "Now let us consider the case depicted in figure 4 below. We see that there is no linear decision boundary in 2d space that could perfectly separate the data points. A circular (or quadratic) decision boundary might do the job, however, linear classifiers are not capable of coming up with these types of decision boundaries." }, { "code": null, "e": 7427, "s": 7033, "text": "In figure 4, each point P is represented by the features of form (x,y) in 2D space. Looking at the desirable decision boundary, we can define a transformation function φ for a point P as φ(P) = (x^2, y^2, √2xy) (why we came up with such a transformation would be clear in just a moment). Let’s see what the Kernel function looks like for this type of transformation for two points P_1 and P_2." }, { "code": null, "e": 7973, "s": 7427, "text": "If we observe the final form of the Kernel function, it’s nothing but a circle! This means we have changed our notion of similarity: instead of measuring similarity by how close the points are (using the dot product), we are measuring similarity based on whether points are within a circle. In this sense, defining such a transformation allowed us to have a non-linear decision boundary in 2D space (it is still linear in the original 3D space). It could be a lot to keep track of, so following is a brief summary of the decisions we have taken:" }, { "code": null, "e": 8520, "s": 7973, "text": "1 - Each point P is represented by (x,y) coordinates in 2D space.2 - We project the points to 3D space by transforming their coordinates to (x^2, y^2, √2xy)3 - Points which have high value of x.y would move upwards along the z-axis (in this case, mostly the red circles). This video provides a good visualization of the same.4 - We find a hyperplane in 3D space that would perfectly separate the classes.5 - The form of Kernel function indicates that this hyperplane would form a circle in 2D space, thus giving us a non-linear decision boundary." }, { "code": null, "e": 8546, "s": 8520, "text": "And the main takeaway is:" }, { "code": null, "e": 8646, "s": 8546, "text": "By embedding the data in a higher-dimensional feature space, we can keep using a linear classifier!" }, { "code": null, "e": 8907, "s": 8646, "text": "A caveat here is that these transformations could increase the feature space drastically and that increases the computational costs. Is there any way we can reap the aforementioned benefits while not increasing the computational costs much? Turns out there is!" }, { "code": null, "e": 8964, "s": 8907, "text": "Let us try to rewrite the Kernel function in equation 7:" }, { "code": null, "e": 9165, "s": 8964, "text": "Whoa! So the value of Kernel function (thus, the similarity between points in 3D space) is just the square of the dot product between points in 2D space. Pretty great, right?! But how did this happen?" }, { "code": null, "e": 9617, "s": 9165, "text": "The reason for this is that we chose our transformation function φ wisely. And as long as we continue to do that, we can circumvent the transformation step and calculate the value of Kernel function directly from the similarity between points in 2D space. This, in turn, would also curb the computational costs. We have many popular Kernel functions which have this nice property and can be used out of the box (we don’t need to search for perfect φ)." }, { "code": null, "e": 9885, "s": 9617, "text": "With this, we have reached the end of this post. Hopefully, the details provided in this article provided you a good insight into what makes SVM a powerful linear classifier. In case you have any questions or suggestions, please let me know in the comments. Cheers! 🥂" } ]
How to Perform Basic Linear Algebra on Arduino?
The BasicLinearAlgebra library helps represent matrices and perform matrix math on Arduino. To install it, search for 'BasicLinearAlgebra' in the Library Manager. Once installed, go to: File → Examples → BasicLinearAlgebra → HowToUse As the name suggests, this example shows how to use this library. While the comments in this example do much of the explanation, here are a few pointers that help illustrate the use of this library − You need to include the library and define the BLA namespace before getting started, as all the functions are wrapped up inside the BLA namespace. #include <BasicLinearAlgebra.h> using namespace BLA; A matrix is defined using the following syntax − BLA::Matrix<3,3> A; A vector is defined using the following syntax: BLA::Matrix<3> v; To set every element of the matric/vector to a specific value, use the Fill() function. v.Fill(0); The row and column counts can be obtained using the .getRowCount() and .getColCount() respectively. The inverse of a matrix is calculated using .Inverse() function. To get the transpose, use the ~ operator. A_T = ~A. A matrix can be initialized with the following syntax − BLA::Matrix<3,3> B = {6.54, 3.66, 2.95, 3.22, 7.54, 5.12, 8.98, 9.99, 1.56}; Or using the Eigen-style comma notation − A << 3.25, 5.67, 8.67, 4.55, 7.23, 9.00, 2.35, 5.73, 10.56; You can horizontally concatenate two matrices using the || operator, and vertically using the && operator. BLA::Matrix<3,6> AleftOfB = A || B; BLA::Matrix<6,3> AonTopOfB = A && B; There are several other operations (multiplication, addition, subtraction, etc.). You are encouraged to go through the entire example (it is heavily commented) to understand the syntax for these various operations. Also, you are strongly encouraged to go through the other examples that come along with this library. Several complex calculations are now possible onboard the Arduino, thanks to this library. The purpose of this article was to make you aware that this library exists and what all is possible with this library. Also, needless to say, this library also allows printing of matrices on the Serial Monitor. If you run this example, your Serial Monitor output looks like
[ { "code": null, "e": 1225, "s": 1062, "text": "The BasicLinearAlgebra library helps represent matrices and perform matrix math on Arduino. To install it, search for 'BasicLinearAlgebra' in the Library Manager." }, { "code": null, "e": 1296, "s": 1225, "text": "Once installed, go to: File → Examples → BasicLinearAlgebra → HowToUse" }, { "code": null, "e": 1496, "s": 1296, "text": "As the name suggests, this example shows how to use this library. While the comments in this example do much of the explanation, here are a few pointers that help illustrate the use of this library −" }, { "code": null, "e": 1643, "s": 1496, "text": "You need to include the library and define the BLA namespace before getting started, as all the functions are wrapped up inside the BLA namespace." }, { "code": null, "e": 1696, "s": 1643, "text": "#include <BasicLinearAlgebra.h>\nusing namespace BLA;" }, { "code": null, "e": 1745, "s": 1696, "text": "A matrix is defined using the following syntax −" }, { "code": null, "e": 1765, "s": 1745, "text": "BLA::Matrix<3,3> A;" }, { "code": null, "e": 1813, "s": 1765, "text": "A vector is defined using the following syntax:" }, { "code": null, "e": 1831, "s": 1813, "text": "BLA::Matrix<3> v;" }, { "code": null, "e": 1919, "s": 1831, "text": "To set every element of the matric/vector to a specific value, use the Fill() function." }, { "code": null, "e": 1930, "s": 1919, "text": "v.Fill(0);" }, { "code": null, "e": 2030, "s": 1930, "text": "The row and column counts can be obtained using the .getRowCount() and .getColCount() respectively." }, { "code": null, "e": 2095, "s": 2030, "text": "The inverse of a matrix is calculated using .Inverse() function." }, { "code": null, "e": 2147, "s": 2095, "text": "To get the transpose, use the ~ operator. A_T = ~A." }, { "code": null, "e": 2203, "s": 2147, "text": "A matrix can be initialized with the following syntax −" }, { "code": null, "e": 2322, "s": 2203, "text": "BLA::Matrix<3,3> B = {6.54, 3.66, 2.95,\n 3.22, 7.54, 5.12,\n 8.98, 9.99, 1.56};" }, { "code": null, "e": 2364, "s": 2322, "text": "Or using the Eigen-style comma notation −" }, { "code": null, "e": 2436, "s": 2364, "text": "A << 3.25, 5.67, 8.67,\n 4.55, 7.23, 9.00,\n 2.35, 5.73, 10.56;" }, { "code": null, "e": 2543, "s": 2436, "text": "You can horizontally concatenate two matrices using the || operator, and vertically using the && operator." }, { "code": null, "e": 2616, "s": 2543, "text": "BLA::Matrix<3,6> AleftOfB = A || B;\nBLA::Matrix<6,3> AonTopOfB = A && B;" }, { "code": null, "e": 3024, "s": 2616, "text": "There are several other operations (multiplication, addition, subtraction, etc.). You are encouraged to go through the entire example (it is heavily commented) to understand the syntax for these various operations. Also, you are strongly encouraged to go through the other examples that come along with this library. Several complex calculations are now possible onboard the Arduino, thanks to this library." }, { "code": null, "e": 3235, "s": 3024, "text": "The purpose of this article was to make you aware that this library exists and what all is possible with this library. Also, needless to say, this library also allows printing of matrices on the Serial Monitor." }, { "code": null, "e": 3298, "s": 3235, "text": "If you run this example, your Serial Monitor output looks like" } ]
SWING - GridBagLayout Class
The class GridBagLayout arranges the components in a horizontal and vertical manner. Following is the declaration for java.awt.GridBagLayout class − public class GridBagLayout extends Object implements LayoutManager2, Serializable Following are the fields for java.awt.GridBagLayout class − static int DEFAULT_SIZE − Indicates the size from the component or the gap should be used for a particular range value. static int DEFAULT_SIZE − Indicates the size from the component or the gap should be used for a particular range value. static int PREFERRED_SIZE − Indicates the preferred size from the component or the gap should be used for a particular range value. static int PREFERRED_SIZE − Indicates the preferred size from the component or the gap should be used for a particular range value. GridBagLayout() Creates a grid bag layout manager. void addLayoutComponent(Component comp, Object constraints) Adds the specified component to the layout, using the specified constraints object. void addLayoutComponent(String name, Component comp) Adds the specified component with the specified name to the layout. protected void adjustForGravity(GridBagConstraints constraints, Rectangle r) Adjusts the x, y width and height fields to the correct values depending on the constraint geometry and pads. protected void AdjustForGravity(GridBagConstraints constraints, Rectangle r) This method is obsolete and supplied for backwards compatability only; new code should call adjustForGravity instead. protected void arrangeGrid(Container parent) Lays out the grid. protected void ArrangeGrid(Container parent) This method is obsolete and supplied for backwards compatability only; new code should call arrangeGrid instead. GridBagConstraints getConstraints(Component comp) Gets the constraints for the specified component. float getLayoutAlignmentX(Container parent) Returns the alignment along the x axis. float getLayoutAlignmentY(Container parent) Returns the alignment along the y axis. int[][] getLayoutDimensions() Determines column widths and row heights for the layout grid. protected java.awt.GridBagLayoutInfo getLayoutInfo(Container parent, int sizeflag) Fills in an instance of GridBagLayoutInfo for the current set of managed children. protected java.awt.GridBagLayoutInfo GetLayoutInfo(Container parent, int sizeflag) This method is obsolete and supplied for backwards compatability only; new code should call getLayoutInfo instead. Point getLayoutOrigin() Determines the origin of the layout area, in the graphics coordinate space of the target container. double[][] getLayoutWeights() Determines the weights of the layout grid's columns and rows. protected Dimension getMinSize(Container parent, java.awt.GridBagLayoutInfo info) Figures out the minimum size of the master based on the information from getLayoutInfo(). protected Dimension GetMinSize(Container parent, java.awt.GridBagLayoutInfo info) This method is obsolete and supplied for backwards compatability only; new code should call getMinSize instead. void invalidateLayout(Container target) Invalidates the layout, indicating that if the layout manager has cached information it should be discarded. void layoutContainer(Container parent) Lays out the specified container using this grid bag layout. Point location(int x, int y) Determines which cell in the layout grid contains the point specified by (x, y). protected GridBagConstraints lookupConstraints(Component comp) Retrieves the constraints for the specified component. Dimension maximumLayoutSize(Container target) Returns the maximum dimensions for this layout given the components in the specified target container. Dimension minimumLayoutSize(Container parent) Determines the minimum size of the parent container using this grid bag layout. Dimension preferredLayoutSize(Container parent) Determines the preferred size of the parent container using this grid bag layout. void removeLayoutComponent(Component comp) Removes the specified component from this layout. void setConstraints(Component comp, GridBagConstraints constraints) Sets the constraints for the specified component in this layout. String toString() Returns a string representation of this grid bag layout's values. This class inherits methods from the following classes − java.lang.Object Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui > SwingLayoutDemo.java package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SwingLayoutDemo { private JFrame mainFrame; private JLabel headerLabel; private JLabel statusLabel; private JPanel controlPanel; private JLabel msglabel; public SwingLayoutDemo(){ prepareGUI(); } public static void main(String[] args){ SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo(); swingLayoutDemo.showGridBagLayoutDemo(); } private void prepareGUI(){ mainFrame = new JFrame("Java SWING Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); headerLabel = new JLabel("",JLabel.CENTER ); statusLabel = new JLabel("",JLabel.CENTER); statusLabel.setSize(350,100); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showGridBagLayoutDemo(){ headerLabel.setText("Layout in action: GridBagLayout"); JPanel panel = new JPanel(); panel.setBackground(Color.darkGray); panel.setSize(300,300); GridBagLayout layout = new GridBagLayout(); panel.setLayout(layout); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridx = 0; gbc.gridy = 0; panel.add(new JButton("Button 1"),gbc); gbc.gridx = 1; gbc.gridy = 0; panel.add(new JButton("Button 2"),gbc); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.ipady = 20; gbc.gridx = 0; gbc.gridy = 1; panel.add(new JButton("Button 3"),gbc); gbc.gridx = 1; gbc.gridy = 1; panel.add(new JButton("Button 4"),gbc); gbc.gridx = 0; gbc.gridy = 2; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridwidth = 2; panel.add(new JButton("Button 5"),gbc); controlPanel.add(panel); mainFrame.setVisible(true); } } Compile the program using the command prompt. Go to D:/ > SWING and type the following command. D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.java If no error occurs, it means the compilation is successful. Run the program using the following command. D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemo Verify the following output. 30 Lectures 3.5 hours Pranjal Srivastava 13 Lectures 1 hours Pranjal Srivastava 25 Lectures 4.5 hours Emenwa Global, Ejike IfeanyiChukwu 14 Lectures 1.5 hours Travis Rose 14 Lectures 1 hours Travis Rose Print Add Notes Bookmark this page
[ { "code": null, "e": 1848, "s": 1763, "text": "The class GridBagLayout arranges the components in a horizontal and vertical manner." }, { "code": null, "e": 1912, "s": 1848, "text": "Following is the declaration for java.awt.GridBagLayout class −" }, { "code": null, "e": 2004, "s": 1912, "text": "public class GridBagLayout\n extends Object\n implements LayoutManager2, Serializable\n" }, { "code": null, "e": 2064, "s": 2004, "text": "Following are the fields for java.awt.GridBagLayout class −" }, { "code": null, "e": 2184, "s": 2064, "text": "static int DEFAULT_SIZE − Indicates the size from the component or the gap should be used for a particular range value." }, { "code": null, "e": 2304, "s": 2184, "text": "static int DEFAULT_SIZE − Indicates the size from the component or the gap should be used for a particular range value." }, { "code": null, "e": 2436, "s": 2304, "text": "static int PREFERRED_SIZE − Indicates the preferred size from the component or the gap should be used for a particular range value." }, { "code": null, "e": 2568, "s": 2436, "text": "static int PREFERRED_SIZE − Indicates the preferred size from the component or the gap should be used for a particular range value." }, { "code": null, "e": 2584, "s": 2568, "text": "GridBagLayout()" }, { "code": null, "e": 2619, "s": 2584, "text": "Creates a grid bag layout manager." }, { "code": null, "e": 2679, "s": 2619, "text": "void addLayoutComponent(Component comp, Object constraints)" }, { "code": null, "e": 2763, "s": 2679, "text": "Adds the specified component to the layout, using the specified constraints object." }, { "code": null, "e": 2816, "s": 2763, "text": "void addLayoutComponent(String name, Component comp)" }, { "code": null, "e": 2884, "s": 2816, "text": "Adds the specified component with the specified name to the layout." }, { "code": null, "e": 2961, "s": 2884, "text": "protected void\tadjustForGravity(GridBagConstraints constraints, Rectangle r)" }, { "code": null, "e": 3071, "s": 2961, "text": "Adjusts the x, y width and height fields to the correct values depending on the constraint geometry and pads." }, { "code": null, "e": 3148, "s": 3071, "text": "protected void\tAdjustForGravity(GridBagConstraints constraints, Rectangle r)" }, { "code": null, "e": 3266, "s": 3148, "text": "This method is obsolete and supplied for backwards compatability only; new code should call adjustForGravity instead." }, { "code": null, "e": 3311, "s": 3266, "text": "protected void\tarrangeGrid(Container parent)" }, { "code": null, "e": 3330, "s": 3311, "text": "Lays out the grid." }, { "code": null, "e": 3375, "s": 3330, "text": "protected void\tArrangeGrid(Container parent)" }, { "code": null, "e": 3488, "s": 3375, "text": "This method is obsolete and supplied for backwards compatability only; new code should call arrangeGrid instead." }, { "code": null, "e": 3538, "s": 3488, "text": "GridBagConstraints getConstraints(Component comp)" }, { "code": null, "e": 3588, "s": 3538, "text": "Gets the constraints for the specified component." }, { "code": null, "e": 3632, "s": 3588, "text": "float getLayoutAlignmentX(Container parent)" }, { "code": null, "e": 3672, "s": 3632, "text": "Returns the alignment along the x axis." }, { "code": null, "e": 3716, "s": 3672, "text": "float getLayoutAlignmentY(Container parent)" }, { "code": null, "e": 3756, "s": 3716, "text": "Returns the alignment along the y axis." }, { "code": null, "e": 3786, "s": 3756, "text": "int[][] getLayoutDimensions()" }, { "code": null, "e": 3848, "s": 3786, "text": "Determines column widths and row heights for the layout grid." }, { "code": null, "e": 3931, "s": 3848, "text": "protected java.awt.GridBagLayoutInfo\tgetLayoutInfo(Container parent, int sizeflag)" }, { "code": null, "e": 4014, "s": 3931, "text": "Fills in an instance of GridBagLayoutInfo for the current set of managed children." }, { "code": null, "e": 4097, "s": 4014, "text": "protected java.awt.GridBagLayoutInfo GetLayoutInfo(Container parent, int sizeflag)" }, { "code": null, "e": 4212, "s": 4097, "text": "This method is obsolete and supplied for backwards compatability only; new code should call getLayoutInfo instead." }, { "code": null, "e": 4236, "s": 4212, "text": "Point getLayoutOrigin()" }, { "code": null, "e": 4336, "s": 4236, "text": "Determines the origin of the layout area, in the graphics coordinate space of the target container." }, { "code": null, "e": 4366, "s": 4336, "text": "double[][] getLayoutWeights()" }, { "code": null, "e": 4428, "s": 4366, "text": "Determines the weights of the layout grid's columns and rows." }, { "code": null, "e": 4510, "s": 4428, "text": "protected Dimension getMinSize(Container parent, java.awt.GridBagLayoutInfo info)" }, { "code": null, "e": 4600, "s": 4510, "text": "Figures out the minimum size of the master based on the information from getLayoutInfo()." }, { "code": null, "e": 4682, "s": 4600, "text": "protected Dimension GetMinSize(Container parent, java.awt.GridBagLayoutInfo info)" }, { "code": null, "e": 4794, "s": 4682, "text": "This method is obsolete and supplied for backwards compatability only; new code should call getMinSize instead." }, { "code": null, "e": 4834, "s": 4794, "text": "void invalidateLayout(Container target)" }, { "code": null, "e": 4943, "s": 4834, "text": "Invalidates the layout, indicating that if the layout manager has cached information it should be discarded." }, { "code": null, "e": 4982, "s": 4943, "text": "void layoutContainer(Container parent)" }, { "code": null, "e": 5043, "s": 4982, "text": "Lays out the specified container using this grid bag layout." }, { "code": null, "e": 5072, "s": 5043, "text": "Point location(int x, int y)" }, { "code": null, "e": 5153, "s": 5072, "text": "Determines which cell in the layout grid contains the point specified by (x, y)." }, { "code": null, "e": 5216, "s": 5153, "text": "protected GridBagConstraints lookupConstraints(Component comp)" }, { "code": null, "e": 5271, "s": 5216, "text": "Retrieves the constraints for the specified component." }, { "code": null, "e": 5317, "s": 5271, "text": "Dimension maximumLayoutSize(Container target)" }, { "code": null, "e": 5420, "s": 5317, "text": "Returns the maximum dimensions for this layout given the components in the specified target container." }, { "code": null, "e": 5466, "s": 5420, "text": "Dimension minimumLayoutSize(Container parent)" }, { "code": null, "e": 5546, "s": 5466, "text": "Determines the minimum size of the parent container using this grid bag layout." }, { "code": null, "e": 5594, "s": 5546, "text": "Dimension preferredLayoutSize(Container parent)" }, { "code": null, "e": 5676, "s": 5594, "text": "Determines the preferred size of the parent container using this grid bag layout." }, { "code": null, "e": 5719, "s": 5676, "text": "void removeLayoutComponent(Component comp)" }, { "code": null, "e": 5769, "s": 5719, "text": "Removes the specified component from this layout." }, { "code": null, "e": 5837, "s": 5769, "text": "void setConstraints(Component comp, GridBagConstraints constraints)" }, { "code": null, "e": 5902, "s": 5837, "text": "Sets the constraints for the specified component in this layout." }, { "code": null, "e": 5920, "s": 5902, "text": "String toString()" }, { "code": null, "e": 5986, "s": 5920, "text": "Returns a string representation of this grid bag layout's values." }, { "code": null, "e": 6043, "s": 5986, "text": "This class inherits methods from the following classes −" }, { "code": null, "e": 6060, "s": 6043, "text": "java.lang.Object" }, { "code": null, "e": 6176, "s": 6060, "text": "Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >" }, { "code": null, "e": 6197, "s": 6176, "text": "SwingLayoutDemo.java" }, { "code": null, "e": 8524, "s": 6197, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\n\npublic class SwingLayoutDemo {\n private JFrame mainFrame;\n private JLabel headerLabel;\n private JLabel statusLabel;\n private JPanel controlPanel;\n private JLabel msglabel;\n\n public SwingLayoutDemo(){\n prepareGUI();\n }\n public static void main(String[] args){\n SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo(); \n swingLayoutDemo.showGridBagLayoutDemo(); \n }\n private void prepareGUI(){\n mainFrame = new JFrame(\"Java SWING Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n\n headerLabel = new JLabel(\"\",JLabel.CENTER );\n statusLabel = new JLabel(\"\",JLabel.CENTER); \n statusLabel.setSize(350,100);\n \n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n controlPanel = new JPanel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n private void showGridBagLayoutDemo(){\n headerLabel.setText(\"Layout in action: GridBagLayout\"); \n\n JPanel panel = new JPanel();\n panel.setBackground(Color.darkGray);\n panel.setSize(300,300);\n GridBagLayout layout = new GridBagLayout();\n\n panel.setLayout(layout); \n GridBagConstraints gbc = new GridBagConstraints();\n\n gbc.fill = GridBagConstraints.HORIZONTAL;\n gbc.gridx = 0;\n gbc.gridy = 0;\n panel.add(new JButton(\"Button 1\"),gbc);\n\n gbc.gridx = 1;\n gbc.gridy = 0;\n panel.add(new JButton(\"Button 2\"),gbc); \n\n gbc.fill = GridBagConstraints.HORIZONTAL;\n gbc.ipady = 20; \n gbc.gridx = 0;\n gbc.gridy = 1;\n panel.add(new JButton(\"Button 3\"),gbc); \n\n gbc.gridx = 1;\n gbc.gridy = 1; \n panel.add(new JButton(\"Button 4\"),gbc); \n\n gbc.gridx = 0;\n gbc.gridy = 2; \n gbc.fill = GridBagConstraints.HORIZONTAL;\n gbc.gridwidth = 2;\n panel.add(new JButton(\"Button 5\"),gbc); \n\n controlPanel.add(panel);\n mainFrame.setVisible(true); \n }\n}" }, { "code": null, "e": 8620, "s": 8524, "text": "Compile the program using the command prompt. Go to D:/ > SWING and type the following command." }, { "code": null, "e": 8680, "s": 8620, "text": "D:\\SWING>javac com\\tutorialspoint\\gui\\SwingLayoutDemo.java\n" }, { "code": null, "e": 8785, "s": 8680, "text": "If no error occurs, it means the compilation is successful. Run the program using the following command." }, { "code": null, "e": 8839, "s": 8785, "text": "D:\\SWING>java com.tutorialspoint.gui.SwingLayoutDemo\n" }, { "code": null, "e": 8868, "s": 8839, "text": "Verify the following output." }, { "code": null, "e": 8903, "s": 8868, "text": "\n 30 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8923, "s": 8903, "text": " Pranjal Srivastava" }, { "code": null, "e": 8956, "s": 8923, "text": "\n 13 Lectures \n 1 hours \n" }, { "code": null, "e": 8976, "s": 8956, "text": " Pranjal Srivastava" }, { "code": null, "e": 9011, "s": 8976, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9047, "s": 9011, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 9082, "s": 9047, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9095, "s": 9082, "text": " Travis Rose" }, { "code": null, "e": 9128, "s": 9095, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 9141, "s": 9128, "text": " Travis Rose" }, { "code": null, "e": 9148, "s": 9141, "text": " Print" }, { "code": null, "e": 9159, "s": 9148, "text": " Add Notes" } ]
Orthogonal Array Testing
Orthogonal array testing is a systematic and statistical way of a black box testing technique used when number of inputs to the application under test is small but too complex for an exhaustive testing. OAT, is a systematic and statistical approach to pairwise interactions. OAT, is a systematic and statistical approach to pairwise interactions. Executing a well-defined and a precise test is likely to uncover most of the defects. Executing a well-defined and a precise test is likely to uncover most of the defects. 100% Orthogonal Array Testing implies 100% pairwise testing. 100% Orthogonal Array Testing implies 100% pairwise testing. If we have 3 parameters, each can have 3 values then the possible Number of tests using conventional method is 3^3 = 27 While the same using OAT, it boils down to 9 test cases. 80 Lectures 7.5 hours Arnab Chakraborty 10 Lectures 1 hours Zach Miller 17 Lectures 1.5 hours Zach Miller 60 Lectures 5 hours John Shea 99 Lectures 10 hours Daniel IT 62 Lectures 5 hours GlobalETraining Print Add Notes Bookmark this page
[ { "code": null, "e": 5948, "s": 5745, "text": "Orthogonal array testing is a systematic and statistical way of a black box testing technique used when number of inputs to the application under test is small but too complex for an exhaustive testing." }, { "code": null, "e": 6020, "s": 5948, "text": "OAT, is a systematic and statistical approach to pairwise interactions." }, { "code": null, "e": 6092, "s": 6020, "text": "OAT, is a systematic and statistical approach to pairwise interactions." }, { "code": null, "e": 6178, "s": 6092, "text": "Executing a well-defined and a precise test is likely to uncover most of the defects." }, { "code": null, "e": 6264, "s": 6178, "text": "Executing a well-defined and a precise test is likely to uncover most of the defects." }, { "code": null, "e": 6325, "s": 6264, "text": "100% Orthogonal Array Testing implies 100% pairwise testing." }, { "code": null, "e": 6386, "s": 6325, "text": "100% Orthogonal Array Testing implies 100% pairwise testing." }, { "code": null, "e": 6563, "s": 6386, "text": "If we have 3 parameters, each can have 3 values then the possible Number of tests using conventional method is 3^3 = 27\nWhile the same using OAT, it boils down to 9 test cases." }, { "code": null, "e": 6598, "s": 6563, "text": "\n 80 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6617, "s": 6598, "text": " Arnab Chakraborty" }, { "code": null, "e": 6650, "s": 6617, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 6663, "s": 6650, "text": " Zach Miller" }, { "code": null, "e": 6698, "s": 6663, "text": "\n 17 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6711, "s": 6698, "text": " Zach Miller" }, { "code": null, "e": 6744, "s": 6711, "text": "\n 60 Lectures \n 5 hours \n" }, { "code": null, "e": 6755, "s": 6744, "text": " John Shea" }, { "code": null, "e": 6789, "s": 6755, "text": "\n 99 Lectures \n 10 hours \n" }, { "code": null, "e": 6800, "s": 6789, "text": " Daniel IT" }, { "code": null, "e": 6833, "s": 6800, "text": "\n 62 Lectures \n 5 hours \n" }, { "code": null, "e": 6850, "s": 6833, "text": " GlobalETraining" }, { "code": null, "e": 6857, "s": 6850, "text": " Print" }, { "code": null, "e": 6868, "s": 6857, "text": " Add Notes" } ]
Program for n’th node from the end of a Linked List in C program
Given with n nodes the task is to print the nth node from the end of a linked list. The program must not change the order of nodes in a list instead it should only print the nth node from the last of a linked list. Input -: 10 20 30 40 50 60 N=3 Output -: 40 In the above example, starting from first node the nodes till count-n nodes are traversed i.e 10,20 30,40, 50,60 and so the third node from the last is 40. Instead of traversing the entire list this efficient approach can be followed − Take a temporary pointer, let’s say, temp of type node Set this temp pointer to first node which is pointed by head pointer Set counter to the number of nodes in a list Move temp to temp → next till count-n Display temp → data If we use this approach, than count will be 5 and program will iterate the loop till 5-3 i.e. 2, so starting from 10 on 0th location than to 20 on 1st location and 30 on 2nd location which is the result. So by this approach there is no need to traverse the entire list till end which will save space and memory. Start Step 1 -> create structure of a node and temp, next and head as pointer to a structure node struct node int data struct node *next, *head, *temp End Step 2 -> declare function to insert a node in a list void insert(int val) struct node* newnode = (struct node*)malloc(sizeof(struct node)) newnode->data = val IF head= NULL set head = newnode set head->next = NULL End Else Set temp=head Loop While temp->next!=NULL Set temp=temp->next End Set newnode->next=NULL Set temp->next=newnode End Step 3 -> Declare a function to display list void display() IF head=NULL Print no node End Else Set temp=head Loop While temp!=NULL Print temp->data Set temp=temp->next End End Step 4 -> declare a function to find nth node from last of a linked list void last(int n) declare int product=1, i Set temp=head Loop For i=0 and i<count-n and i++ Set temp=temp->next End Print temp->data Step 5 -> in main() Create nodes using struct node* head = NULL Declare variable n as nth to 3 Call function insert(10) to insert a node Call display() to display the list Call last(n) to find nth node from last of a list Stop Live Demo #include<stdio.h> #include<stdlib.h> //structure of a node struct node{ int data; struct node *next; }*head,*temp; int count=0; //function for inserting nodes into a list void insert(int val){ struct node* newnode = (struct node*)malloc(sizeof(struct node)); newnode->data = val; newnode->next = NULL; if(head == NULL){ head = newnode; temp = head; count++; } else { temp->next=newnode; temp=temp->next; count++; } } //function for displaying a list void display(){ if(head==NULL) printf("no node "); else { temp=head; while(temp!=NULL) { printf("%d ",temp->data); temp=temp->next; } } } //function for finding 3rd node from the last of a linked list void last(int n){ int i; temp=head; for(i=0;i<count-n;i++){ temp=temp->next; } printf("\n%drd node from the end of linked list is : %d" ,n,temp->data); } int main(){ //creating list struct node* head = NULL; int n=3; //inserting elements into a list insert(1); insert(2); insert(3); insert(4); insert(5); insert(6); //displaying the list printf("\nlinked list is : "); display(); //calling function for finding nth element in a list from last last(n); return 0; } linked list is : 1 2 3 4 5 6 3rd node from the end of linked list is : 4
[ { "code": null, "e": 1277, "s": 1062, "text": "Given with n nodes the task is to print the nth node from the end of a linked list. The program must not change the order of nodes in a list instead it should only print the nth node from the last of a linked list." }, { "code": null, "e": 1324, "s": 1277, "text": "Input -: 10 20 30 40 50 60\n N=3\nOutput -: 40" }, { "code": null, "e": 1480, "s": 1324, "text": "In the above example, starting from first node the nodes till count-n nodes are traversed i.e 10,20 30,40, 50,60 and so the third node from the last is 40." }, { "code": null, "e": 1560, "s": 1480, "text": "Instead of traversing the entire list this efficient approach can be followed −" }, { "code": null, "e": 1615, "s": 1560, "text": "Take a temporary pointer, let’s say, temp of type node" }, { "code": null, "e": 1684, "s": 1615, "text": "Set this temp pointer to first node which is pointed by head pointer" }, { "code": null, "e": 1729, "s": 1684, "text": "Set counter to the number of nodes in a list" }, { "code": null, "e": 1767, "s": 1729, "text": "Move temp to temp → next till count-n" }, { "code": null, "e": 1787, "s": 1767, "text": "Display temp → data" }, { "code": null, "e": 2099, "s": 1787, "text": "If we use this approach, than count will be 5 and program will iterate the loop till 5-3 i.e. 2, so starting from 10 on 0th location than to 20 on 1st location and 30 on 2nd location which is the result. So by this approach there is no need to traverse the entire list till end which will save space and memory." }, { "code": null, "e": 3479, "s": 2099, "text": "Start\nStep 1 -> create structure of a node and temp, next and head as pointer to a structure node\n struct node\n int data\n struct node *next, *head, *temp\n End\nStep 2 -> declare function to insert a node in a list\n void insert(int val)\n struct node* newnode = (struct node*)malloc(sizeof(struct node))\n newnode->data = val\n IF head= NULL\n set head = newnode\n set head->next = NULL\n End\n Else\n Set temp=head\n Loop While temp->next!=NULL\n Set temp=temp->next\n End\n Set newnode->next=NULL\n Set temp->next=newnode\n End\nStep 3 -> Declare a function to display list\n void display()\n IF head=NULL\n Print no node\n End\n Else\n Set temp=head\n Loop While temp!=NULL\n Print temp->data\n Set temp=temp->next\n End\n End\nStep 4 -> declare a function to find nth node from last of a linked list\n void last(int n)\n declare int product=1, i\n Set temp=head\n Loop For i=0 and i<count-n and i++\n Set temp=temp->next\n End\n Print temp->data\nStep 5 -> in main()\n Create nodes using struct node* head = NULL\n Declare variable n as nth to 3\n Call function insert(10) to insert a node\n Call display() to display the list\n Call last(n) to find nth node from last of a list\nStop" }, { "code": null, "e": 3490, "s": 3479, "text": " Live Demo" }, { "code": null, "e": 4785, "s": 3490, "text": "#include<stdio.h>\n#include<stdlib.h>\n//structure of a node\nstruct node{\n int data;\n struct node *next;\n}*head,*temp;\nint count=0;\n//function for inserting nodes into a list\nvoid insert(int val){\n struct node* newnode = (struct node*)malloc(sizeof(struct node));\n newnode->data = val;\n newnode->next = NULL;\n if(head == NULL){\n head = newnode;\n temp = head;\n count++;\n } else {\n temp->next=newnode;\n temp=temp->next;\n count++;\n }\n}\n//function for displaying a list\nvoid display(){\n if(head==NULL)\n printf(\"no node \");\n else {\n temp=head;\n while(temp!=NULL) {\n printf(\"%d \",temp->data);\n temp=temp->next;\n }\n }\n}\n//function for finding 3rd node from the last of a linked list\nvoid last(int n){\n int i;\n temp=head;\n for(i=0;i<count-n;i++){\n temp=temp->next;\n }\n printf(\"\\n%drd node from the end of linked list is : %d\" ,n,temp->data);\n}\nint main(){\n //creating list\n struct node* head = NULL;\n int n=3;\n //inserting elements into a list\n insert(1);\n insert(2);\n insert(3);\n insert(4);\n insert(5);\n insert(6);\n //displaying the list\n printf(\"\\nlinked list is : \");\n display();\n //calling function for finding nth element in a list from last\n last(n);\n return 0;\n}" }, { "code": null, "e": 4858, "s": 4785, "text": "linked list is : 1 2 3 4 5 6\n3rd node from the end of linked list is : 4" } ]
How to display MySQL Table Name with columns?
You can use INFORMATION_SCHEMA.COLUMNS table to display MySQL table name with columns. The syntax is as follows − SELECT DISTINCT TABLE_NAME,Column_Name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'yourDatabaseName'; Here, we have a database with the name ‘sample’ with tables. The query is as follows to display table name along with column name − mysql> SELECT DISTINCT TABLE_NAME,Column_Name -> FROM INFORMATION_SCHEMA.COLUMNS -> WHERE TABLE_SCHEMA = 'sample'; +--------------------------------+-------------------------------+ | TABLE_NAME | COLUMN_NAME | +--------------------------------+-------------------------------+ | aggregatefunctiondemo | UserId | | aggregatefunctiondemo | UserName | | allownulldefaulnotnulldemo | Id | | allownulldefaulnotnulldemo | UserAddress | | allownulldefaulnotnulldemo | UserName | | allrecordsexceptlastone | Id | | allrecordsexceptlastone | UserAge | | allrecordsexceptlastone | UserName | | averagestring | Id | | averagestring | Value | | avoidinserterrordemo | Id | | avoidinserterrordemo | Sentence | | backtick_symboldemo | FileName | | backtick_symboldemo | Id | | backtick_symboldemo | Name | | bar | Id | | bar | Words | | binarykeyworddemo | Id | | binarykeyworddemo | Name | | blobsizedemo | Image | | caseinsensitivedemo | Id | | caseinsensitivedemo | Name | | casttypetobigintdemo | Id | | casttypetobigintdemo | Value | | child_table | ChildId | | childtable | EmployeeAddress | | childtable | UniqueId | | commadelimitedlist | CompanyName | | commadelimitedlist | GroupId | | commadelimitedlist | Id | | commadelimitedlist | Name | | commadelimitedlist | RefId | | countallrowsdemo | Age | | countallrowsdemo | Id | | countallrowsdemo | Name | | coursedemo | CourseId | | coursedemo | CourseName | | coursedemo | StudentName | | crc32demo | Id | | crc32demo | UserId | | datedemo | DateBefore1970 | | datedemo | Id | | dateformatdemo | Id | | dateformatdemo | UserLoginDate | | dateformatdemo | UserName | | decimal_demo | Id | | decimal_demo | PRICE | | decimaldemo | UserId | | defaulmyisam | UserId | | defaulmyisam | UserName | | demo | Id | | demo | UserName | | department | departmentID | | department | Name | | department_table | Department_Id | | department_table | Department_Name | | detectbitdemo | Id | | detectbitdemo | Value | | employee | departmentID | | employee | employeeID | | employee | Job | | employee | Name | | employee_table | Department_Id | | employee_table | EmployeeID | | employee_table | EmployeeName | | employee_table | Job | | employeeinformation | EmployeeDateOfBirth | | employeeinformation | EmployeeId | | employeeinformation | EmployeeName | | employeeinformation | EmployeeSalary | | enumdemo | Color | | enumdemo | Id | | equivalentdemo1 | Id | | equivalentdemo1 | Name | | equivalentdemo2 | Id | | equivalentdemo2 | Name | | eventdemo | EventDateTime | | eventdemo | Id | | extractfilenamedemo | AllProgrammingFilePath | | extractfilenamedemo | Id | | extracttuples | Comments | | extracttuples | Id | | extracttuples | Name | | findbestmatch | UserId | | findbestmatch | UserQuery | | findinvalidemailaddressdemo | EmailAddress | | findinvalidemailaddressdemo | Id | | findinvalidemailaddressdemo | Name | | first_table | Id | | firstweekofmonth | Id | | firstweekofmonth | yourdate | | followers | FollowerId | | followers | FollowerName | | getlatesthour | UserId | | getlatesthour | UserLoginDateTime | | getlatesthour | UserName | | getyearout | Id | | getyearout | Name | | getyearout | yourTimestamp | | groupandcountbydate | Id | | groupandcountbydate | ShopId | | groupandcountbydate | TripDate | | groupbymaxdemo | CategoryId | | groupbymaxdemo | Id | | groupbymaxdemo | Value1 | | groupbymaxdemo | Value2 | | groupbywithwhereclause | Id | | groupbywithwhereclause | IsDeleted | | groupbywithwhereclause | MoneyStatus | | groupbywithwhereclause | UserId | | ifnulldemo | Id | | ifnulldemo | ProductName | | ifnulldemo | ProductRetailPrice | | ifnulldemo | ProductWholePrice | | inclausedemo | Id | | indemo | CodeId | | indemo | Name | | insert_prevent | Id | | insertmultipledemo | Id | | insertmultipledemo | UserName | | insertmultipledemo | UserRole | | insertrecord_selecttable | Id | | insertrecord_selecttable | Name | | insertrecordprevent | Id | | insertrecordprevent | Name | | insertvalueinautoincrement | UserId | | insertvalueinautoincrement | UserName | | instructor | Instructor_CourseName | | instructor | Instructor_Id | | instructor | Instructor_Name | | javadatedemo | Id | | javadatedemo | ShippingDate | | javapreparedstatement | Age | | javapreparedstatement | Id | | javapreparedstatement | Name | | lagdemo | UserId | | lagdemo | UserValue | | largeautoincrement | Id | | limit0demo | Id | | limit0demo | Name | | locktabledemo2 | Id | | loggingdetails | Id | | loggingdetails | LastLoginDetails | | maxdemo | UserId | | maxdemo | UserName | | maxdemo | UserRank | | mergingselectdemo | RoomId | | mergingselectdemo | RoomServicesId | | mergingselectdemo | ServiceId | | multiplecolumnsortingorderdemo | Id | | multiplecolumnsortingorderdemo | LoginDate | | multiplecolumnsortingorderdemo | Name | | mytable | id | | mytable | Name | | newlinedemo | CountryName | | notequaloperator | StudentId | | notequaloperator | StudentName | | notequaloperator | StudentSection | | null_demo | UserAddress | | null_demo | UserId | | null_demo | UserName | | nulldemo | Id | | nulldemo | Name | | orderbycasedemo | ArrivalDate | | orderbycasedemo | GroupId | | orderbycasedemo | Id | | orderbyfield | UserId | | orderdemo | OrderDatetime | | orderdemo | OrderId | | orderdemo | OrderPrice | | pairdemo | UserId | | pairdemo | UserName | | pairdemo | UserRelationshipName | | parent_table | ParentId | | parenttable | EmployeeName | | parenttable | UniqueId | | post | Id | | post | UserName | | post | UserPostMessage | | post_demo | PostDate | | post_demo | PostId | | post_demo | PostName | | primarykeydemo | Id | | productinformations | ProductId | | productinformations | ProductQuantity | | productstock | ProductId | | productstock | ProductName | | productstock | ProductPrice | | productstock | ProductQuantity | | quotesdemo | Id | | quotesdemo | UserAge | | quotesdemo | UserName | | regularexpressiondemo | Id | | removedemo | Id | | removedemo | Name | | removespacedemo | Id | | removespacedemo | UserId | | removespacedemo | UserName | | returndemo | Id | | returndemo | Name | | rownumberdemo | UserId | | rownumberdemo | UserName | | rowsusinglimit | Id | | rowsusinglimit | Name | | searchdateasvarchar | Id | | searchdateasvarchar | ShippingDate | | searchingdemo | UserId | | searchingdemo2 | UserId | | second_table | Id | | select1andlimit1demo | Id | | select1andlimit1demo | Name | | selectifdemo | Id | | selectifdemo | Name | | selectpartoftimestampdemo | Id | | selectpartoftimestampdemo | ShippingTime | | selectpermonthdemo | Id | | selectpermonthdemo | Price | | selectpermonthdemo | PurchaseDate | | selfjoindemo | CountryName | | selfjoindemo | CountryRank | | selfjoindemo | Id | | selfjoindemo | Year | | sortcertainvalues | CountryName | | sortcertainvalues | Id | | sortcertainvalues | Name | | storedproceduredemo | Id | | storedproceduredemo | Name | | storevalue0and1ornulldemo | isDigit | | stringendswithnumber | Id | | stringendswithnumber | UserId | | stringendswithnumber | UserName | | student_table_sample | StudentAge | | student_table_sample | StudentId | | student_table_sample | StudentName | | subtotaldemo | Amount | | subtotaldemo | CustomerName | | subtotaldemo | InvoiceId | | sumdemo | Amount | | sumdemo | Id | | sumofeverydistinct | Amount | | sumofeverydistinct | Id | | tblupdate | Id | | tblupdate | Name | | tematics_field | Id | | tematics_field | yourdate | | ternaryoperationdemo | X | | ternaryoperationdemo | Y | | timedemo | Id | | timedemo | LastLoginTime | | timestamp_tabledemo | Id | | timestamp_tabledemo | yourTimestamp | | uniquecountbyipadress | Id | | uniquecountbyipadress | UserHits | | uniquecountbyipadress | UserIPAdress | | unsigneddemo | Id | | usercommentsview | UserComments | | userdemo | RegisteredCourse | | userdemo | UserId | | userdemo | UserName | | userinformation | UserId | | userinformation | UserName | | userinformation | UserPost | | userinformationexpire | Id | | userinformationexpire | UserInformationExpireDateTime | | userinformationexpire | UserName | | userlogindetails | UserId
[ { "code": null, "e": 1176, "s": 1062, "text": "You can use INFORMATION_SCHEMA.COLUMNS table to display MySQL table name with columns. The syntax is as follows −" }, { "code": null, "e": 1288, "s": 1176, "text": "SELECT DISTINCT TABLE_NAME,Column_Name\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE TABLE_SCHEMA = 'yourDatabaseName';" }, { "code": null, "e": 1420, "s": 1288, "text": "Here, we have a database with the name ‘sample’ with tables. The query is as follows to display table name along with column name −" }, { "code": null, "e": 1535, "s": 1420, "text": "mysql> SELECT DISTINCT TABLE_NAME,Column_Name\n-> FROM INFORMATION_SCHEMA.COLUMNS\n-> WHERE TABLE_SCHEMA = 'sample';" }, { "code": null, "e": 19547, "s": 1535, "text": "+--------------------------------+-------------------------------+\n| TABLE_NAME | COLUMN_NAME |\n+--------------------------------+-------------------------------+\n| aggregatefunctiondemo | UserId |\n| aggregatefunctiondemo | UserName |\n| allownulldefaulnotnulldemo | Id |\n| allownulldefaulnotnulldemo | UserAddress |\n| allownulldefaulnotnulldemo | UserName |\n| allrecordsexceptlastone | Id |\n| allrecordsexceptlastone | UserAge |\n| allrecordsexceptlastone | UserName |\n| averagestring | Id |\n| averagestring | Value |\n| avoidinserterrordemo | Id |\n| avoidinserterrordemo | Sentence |\n| backtick_symboldemo | FileName |\n| backtick_symboldemo | Id |\n| backtick_symboldemo | Name |\n| bar | Id |\n| bar | Words |\n| binarykeyworddemo | Id |\n| binarykeyworddemo | Name |\n| blobsizedemo | Image |\n| caseinsensitivedemo | Id |\n| caseinsensitivedemo | Name |\n| casttypetobigintdemo | Id |\n| casttypetobigintdemo | Value |\n| child_table | ChildId |\n| childtable | EmployeeAddress |\n| childtable | UniqueId |\n| commadelimitedlist | CompanyName |\n| commadelimitedlist | GroupId |\n| commadelimitedlist | Id |\n| commadelimitedlist | Name |\n| commadelimitedlist | RefId |\n| countallrowsdemo | Age |\n| countallrowsdemo | Id |\n| countallrowsdemo | Name |\n| coursedemo | CourseId |\n| coursedemo | CourseName |\n| coursedemo | StudentName |\n| crc32demo | Id |\n| crc32demo | UserId |\n| datedemo | DateBefore1970 |\n| datedemo | Id |\n| dateformatdemo | Id |\n| dateformatdemo | UserLoginDate |\n| dateformatdemo | UserName |\n| decimal_demo | Id |\n| decimal_demo | PRICE |\n| decimaldemo | UserId |\n| defaulmyisam | UserId |\n| defaulmyisam | UserName |\n| demo | Id |\n| demo | UserName |\n| department | departmentID |\n| department | Name |\n| department_table | Department_Id |\n| department_table | Department_Name |\n| detectbitdemo | Id |\n| detectbitdemo | Value |\n| employee | departmentID |\n| employee | employeeID |\n| employee | Job |\n| employee | Name |\n| employee_table | Department_Id |\n| employee_table | EmployeeID |\n| employee_table | EmployeeName |\n| employee_table | Job |\n| employeeinformation | EmployeeDateOfBirth |\n| employeeinformation | EmployeeId |\n| employeeinformation | EmployeeName |\n| employeeinformation | EmployeeSalary |\n| enumdemo | Color |\n| enumdemo | Id |\n| equivalentdemo1 | Id |\n| equivalentdemo1 | Name |\n| equivalentdemo2 | Id |\n| equivalentdemo2 | Name |\n| eventdemo | EventDateTime |\n| eventdemo | Id |\n| extractfilenamedemo | AllProgrammingFilePath |\n| extractfilenamedemo | Id |\n| extracttuples | Comments |\n| extracttuples | Id |\n| extracttuples | Name |\n| findbestmatch | UserId |\n| findbestmatch | UserQuery |\n| findinvalidemailaddressdemo | EmailAddress |\n| findinvalidemailaddressdemo | Id |\n| findinvalidemailaddressdemo | Name |\n| first_table | Id |\n| firstweekofmonth | Id |\n| firstweekofmonth | yourdate |\n| followers | FollowerId |\n| followers | FollowerName |\n| getlatesthour | UserId |\n| getlatesthour | UserLoginDateTime |\n| getlatesthour | UserName |\n| getyearout | Id |\n| getyearout | Name |\n| getyearout | yourTimestamp |\n| groupandcountbydate | Id |\n| groupandcountbydate | ShopId |\n| groupandcountbydate | TripDate |\n| groupbymaxdemo | CategoryId |\n| groupbymaxdemo | Id |\n| groupbymaxdemo | Value1 |\n| groupbymaxdemo | Value2 |\n| groupbywithwhereclause | Id |\n| groupbywithwhereclause | IsDeleted |\n| groupbywithwhereclause | MoneyStatus |\n| groupbywithwhereclause | UserId |\n| ifnulldemo | Id |\n| ifnulldemo | ProductName |\n| ifnulldemo | ProductRetailPrice |\n| ifnulldemo | ProductWholePrice |\n| inclausedemo | Id |\n| indemo | CodeId |\n| indemo | Name |\n| insert_prevent | Id |\n| insertmultipledemo | Id |\n| insertmultipledemo | UserName |\n| insertmultipledemo | UserRole |\n| insertrecord_selecttable | Id |\n| insertrecord_selecttable | Name |\n| insertrecordprevent | Id |\n| insertrecordprevent | Name |\n| insertvalueinautoincrement | UserId |\n| insertvalueinautoincrement | UserName |\n| instructor | Instructor_CourseName |\n| instructor | Instructor_Id |\n| instructor | Instructor_Name |\n| javadatedemo | Id |\n| javadatedemo | ShippingDate |\n| javapreparedstatement | Age |\n| javapreparedstatement | Id |\n| javapreparedstatement | Name |\n| lagdemo | UserId |\n| lagdemo | UserValue |\n| largeautoincrement | Id |\n| limit0demo | Id |\n| limit0demo | Name |\n| locktabledemo2 | Id |\n| loggingdetails | Id |\n| loggingdetails | LastLoginDetails |\n| maxdemo | UserId |\n| maxdemo | UserName |\n| maxdemo | UserRank |\n| mergingselectdemo | RoomId |\n| mergingselectdemo | RoomServicesId |\n| mergingselectdemo | ServiceId |\n| multiplecolumnsortingorderdemo | Id |\n| multiplecolumnsortingorderdemo | LoginDate |\n| multiplecolumnsortingorderdemo | Name |\n| mytable | id |\n| mytable | Name |\n| newlinedemo | CountryName |\n| notequaloperator | StudentId |\n| notequaloperator | StudentName |\n| notequaloperator | StudentSection |\n| null_demo | UserAddress |\n| null_demo | UserId |\n| null_demo | UserName |\n| nulldemo | Id |\n| nulldemo | Name |\n| orderbycasedemo | ArrivalDate |\n| orderbycasedemo | GroupId |\n| orderbycasedemo | Id |\n| orderbyfield | UserId |\n| orderdemo | OrderDatetime |\n| orderdemo | OrderId |\n| orderdemo | OrderPrice |\n| pairdemo | UserId |\n| pairdemo | UserName |\n| pairdemo | UserRelationshipName |\n| parent_table | ParentId |\n| parenttable | EmployeeName |\n| parenttable | UniqueId |\n| post | Id |\n| post | UserName |\n| post | UserPostMessage |\n| post_demo | PostDate |\n| post_demo | PostId |\n| post_demo | PostName |\n| primarykeydemo | Id |\n| productinformations | ProductId |\n| productinformations | ProductQuantity |\n| productstock | ProductId |\n| productstock | ProductName |\n| productstock | ProductPrice |\n| productstock | ProductQuantity |\n| quotesdemo | Id |\n| quotesdemo | UserAge |\n| quotesdemo | UserName |\n| regularexpressiondemo | Id |\n| removedemo | Id |\n| removedemo | Name |\n| removespacedemo | Id |\n| removespacedemo | UserId |\n| removespacedemo | UserName |\n| returndemo | Id |\n| returndemo | Name |\n| rownumberdemo | UserId |\n| rownumberdemo | UserName |\n| rowsusinglimit | Id |\n| rowsusinglimit | Name |\n| searchdateasvarchar | Id |\n| searchdateasvarchar | ShippingDate |\n| searchingdemo | UserId |\n| searchingdemo2 | UserId |\n| second_table | Id |\n| select1andlimit1demo | Id |\n| select1andlimit1demo | Name |\n| selectifdemo | Id |\n| selectifdemo | Name |\n| selectpartoftimestampdemo | Id | \n| selectpartoftimestampdemo | ShippingTime |\n| selectpermonthdemo | Id |\n| selectpermonthdemo | Price |\n| selectpermonthdemo | PurchaseDate |\n| selfjoindemo | CountryName |\n| selfjoindemo | CountryRank |\n| selfjoindemo | Id |\n| selfjoindemo | Year |\n| sortcertainvalues | CountryName |\n| sortcertainvalues | Id |\n| sortcertainvalues | Name |\n| storedproceduredemo | Id |\n| storedproceduredemo | Name |\n| storevalue0and1ornulldemo | isDigit |\n| stringendswithnumber | Id |\n| stringendswithnumber | UserId |\n| stringendswithnumber | UserName |\n| student_table_sample | StudentAge |\n| student_table_sample | StudentId |\n| student_table_sample | StudentName |\n| subtotaldemo | Amount |\n| subtotaldemo | CustomerName |\n| subtotaldemo | InvoiceId |\n| sumdemo | Amount |\n| sumdemo | Id |\n| sumofeverydistinct | Amount |\n| sumofeverydistinct | Id |\n| tblupdate | Id |\n| tblupdate | Name |\n| tematics_field | Id |\n| tematics_field | yourdate |\n| ternaryoperationdemo | X |\n| ternaryoperationdemo | Y |\n| timedemo | Id |\n| timedemo | LastLoginTime |\n| timestamp_tabledemo | Id |\n| timestamp_tabledemo | yourTimestamp |\n| uniquecountbyipadress | Id |\n| uniquecountbyipadress | UserHits |\n| uniquecountbyipadress | UserIPAdress |\n| unsigneddemo | Id |\n| usercommentsview | UserComments |\n| userdemo | RegisteredCourse |\n| userdemo | UserId |\n| userdemo | UserName |\n| userinformation | UserId |\n| userinformation | UserName |\n| userinformation | UserPost |\n| userinformationexpire | Id |\n| userinformationexpire | UserInformationExpireDateTime |\n| userinformationexpire | UserName |\n| userlogindetails | UserId " } ]
Bitwise operations on Subarrays of size K - GeeksforGeeks
15 Jun, 2021 Given an array arr[] of positive integers and a number K, the task is to find the minimum and maximum values of Bitwise operation on elements of subarray of size K. Examples: Input: arr[]={2, 5, 3, 6, 11, 13}, k = 3 Output: Maximum AND = 2 Minimum AND = 0 Maximum OR = 15 Minimum OR = 7 Explanation: Maximum AND is generated by subarray 3, 6 and 11, 3 & 6 & 11 = 2 Minimum AND is generated by subarray 2, 3 and 5, 2 & 3 & 5 = 0 Maximum OR is generated by subarray 2, 6 and 13, 2 | 6 | 13 = 15 Minimum OR is generated by subarray 2, 3 and 5, 2 | 3 | 5 = 7 Input: arr[]={5, 9, 7, 19}, k = 2 Output: Maximum AND = 3 Minimum AND = 1 Maximum OR = 23 Minimum OR = 13 Naive Approach: The naive approach is to generate all possible subarrays of size K and check which of the above-formed subarray will give the minimum and maximum Bitwise OR and AND.Time Complexity: O(N2) Auxiliary Space: O(K) Efficient Approach: The idea is to use the Sliding Window Technique to solve this problem. Below are the steps: Traverse the prefix array of size K and for each array, element goes through it’s each bit and increases bit array (by maintaining an integer array bit of size 32) by 1 if it is set.Convert this bit array to a decimal number lets say ans, and move the sliding window to the next index.For newly added element for the next subarray of size K, Iterate through each bit of the newly added element and increase bit array by 1 if it is set.For removing the first element from the previous window, decrease bit array by 1 if it is set.Update ans with a minimum or maximum of the new decimal number generated by bit array. Traverse the prefix array of size K and for each array, element goes through it’s each bit and increases bit array (by maintaining an integer array bit of size 32) by 1 if it is set. Convert this bit array to a decimal number lets say ans, and move the sliding window to the next index. For newly added element for the next subarray of size K, Iterate through each bit of the newly added element and increase bit array by 1 if it is set. For removing the first element from the previous window, decrease bit array by 1 if it is set. Update ans with a minimum or maximum of the new decimal number generated by bit array. Below is the program to find the Maximum Bitwise OR subarray: C++ Java Python3 C# Javascript // C++ program for maximum values of// each bitwise OR operation on// element of subarray of size K#include <iostream>using namespace std; // Function to convert bit array to// decimal numberint build_num(int bit[]){ int ans = 0; for (int i = 0; i < 32; i++) if (bit[i]) ans += (1 << i); return ans;} // Function to find maximum values of// each bitwise OR operation on// element of subarray of size Kint maximumOR(int arr[], int n, int k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 int bit[32] = { 0 }; // Create a sliding window of size k for (int i = 0; i < k; i++) { for (int j = 0; j < 32; j++) { if (arr[i] & (1 << j)) bit[j]++; } } // Function call int max_or = build_num(bit); for (int i = k; i < n; i++) { // Perform operation for // removed element for (int j = 0; j < 32; j++) { if (arr[i - k] & (1 << j)) bit[j]--; } // Perform operation for // added_element for (int j = 0; j < 32; j++) { if (arr[i] & (1 << j)) bit[j]++; } // Taking maximum value max_or = max(build_num(bit), max_or); } // Return the result return max_or;} // Driver Codeint main(){ // Given array arr[] int arr[] = { 2, 5, 3, 6, 11, 13 }; // Given subarray size K int k = 3; int n = sizeof arr / sizeof arr[0]; // Function Call cout << maximumOR(arr, n, k); return 0;} // Java program for maximum values of// each bitwise OR operation on// element of subarray of size Kimport java.util.*;class GFG{ // Function to convert bit array to// decimal numberstatic int build_num(int bit[]){ int ans = 0; for (int i = 0; i < 32; i++) if (bit[i] > 0) ans += (1 << i); return ans;} // Function to find maximum values of// each bitwise OR operation on// element of subarray of size Kstatic int maximumOR(int arr[], int n, int k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 int bit[] = new int[32]; // Create a sliding window of size k for (int i = 0; i < k; i++) { for (int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call int max_or = build_num(bit); for (int i = k; i < n; i++) { // Perform operation for // removed element for (int j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation for // added_element for (int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking maximum value max_or = Math.max(build_num(bit), max_or); } // Return the result return max_or;} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = { 2, 5, 3, 6, 11, 13 }; // Given subarray size K int k = 3; int n = arr.length; // Function Call System.out.print(maximumOR(arr, n, k));}} // This code is contributed by Rohit_ranjan # Python3 program for maximum values of# each bitwise OR operation on# element of subarray of size K # Function to convert bit array to# decimal numberdef build_num(bit): ans = 0; for i in range(32): if (bit[i] > 0): ans += (1 << i); return ans; # Function to find maximum values of# each bitwise OR operation on# element of subarray of size Kdef maximumOR(arr, n, k): # Maintain an integer array bit # of size 32 all initialized to 0 bit = [0] * 32; # Create a sliding window of size k for i in range(k): for j in range(32): if ((arr[i] & (1 << j)) > 0): bit[j] += 1; # Function call max_or = build_num(bit); for i in range(k, n): # Perform operation for # removed element for j in range(32): if ((arr[i - k] & (1 << j)) > 0): bit[j] -= 1; # Perform operation for # added_element for j in range(32): if ((arr[i] & (1 << j)) > 0): bit[j] += 1; # Taking maximum value max_or = max(build_num(bit), max_or); # Return the result return max_or; # Driver Codeif __name__ == '__main__': # Given array arr arr = [ 2, 5, 3, 6, 11, 13 ]; # Given subarray size K k = 3; n = len(arr); # Function call print(maximumOR(arr, n, k)); # This code is contributed by Amit Katiyar // C# program for maximum values of// each bitwise OR operation on// element of subarray of size Kusing System;class GFG{ // Function to convert bit // array to decimal number static int build_num(int[] bit) { int ans = 0; for (int i = 0; i < 32; i++) if (bit[i] > 0) ans += (1 << i); return ans; } // Function to find maximum values of // each bitwise OR operation on // element of subarray of size K static int maximumOR(int[] arr, int n, int k) { // Maintain an integer array bit[] // of size 32 all initialized to 0 int[] bit = new int[32]; // Create a sliding window of size k for (int i = 0; i < k; i++) { for (int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call int max_or = build_num(bit); for (int i = k; i < n; i++) { // Perform operation for // removed element for (int j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation for // added_element for (int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking maximum value max_or = Math.Max(build_num(bit), max_or); } // Return the result return max_or; } // Driver Code public static void Main(String[] args) { // Given array []arr int[] arr = {2, 5, 3, 6, 11, 13}; // Given subarray size K int k = 3; int n = arr.Length; // Function Call Console.Write(maximumOR(arr, n, k)); }} // This code is contributed by Rohit_ranjan <script> // Javascript program for maximum values of // each bitwise OR operation on // element of subarray of size K // Function to convert bit array to // decimal number function build_num(bit) { let ans = 0; for (let i = 0; i < 32; i++) if (bit[i] > 0) ans += (1 << i); return ans; } // Function to find maximum values of // each bitwise OR operation on // element of subarray of size K function maximumOR(arr, n, k) { // Maintain an integer array bit[] // of size 32 all initialized to 0 let bit = new Array(32); bit.fill(0); // Create a sliding window of size k for (let i = 0; i < k; i++) { for (let j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call let max_or = build_num(bit); for (let i = k; i < n; i++) { // Perform operation for // removed element for (let j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation for // added_element for (let j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking maximum value max_or = Math.max(build_num(bit), max_or); } // Return the result return max_or; } // Given array []arr let arr = [2, 5, 3, 6, 11, 13]; // Given subarray size K let k = 3; let n = arr.length; // Function Call document.write(maximumOR(arr, n, k)); // This code is contributed by divyesh072019.</script> 15 Time Complexity: O(n * B) where n is the size of the array and B is the integer array bit of size 32. Auxiliary Space: O(n) Below is the program to find the Minimum Bitwise OR subarray: C++ Java Python3 C# Javascript // C++ program for minimum values of// each bitwise OR operation on// element of subarray of size K#include <iostream>using namespace std; // Function to convert bit array// to decimal numberint build_num(int bit[]){ int ans = 0; for (int i = 0; i < 32; i++) if (bit[i]) ans += (1 << i); return ans;} // Function to find minimum values of// each bitwise OR operation on// element of subarray of size Kint minimumOR(int arr[], int n, int k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 int bit[32] = { 0 }; // Create a sliding window of size k for (int i = 0; i < k; i++) { for (int j = 0; j < 32; j++) { if (arr[i] & (1 << j)) bit[j]++; } } // Function call int min_or = build_num(bit); for (int i = k; i < n; i++) { // Perform operation for // removed element for (int j = 0; j < 32; j++) { if (arr[i - k] & (1 << j)) bit[j]--; } // Perform operation for // added_element for (int j = 0; j < 32; j++) { if (arr[i] & (1 << j)) bit[j]++; } // Taking minimum value min_or = min(build_num(bit), min_or); } // Return the result return min_or;} // Driver Codeint main(){ // Given array arr[] int arr[] = { 2, 5, 3, 6, 11, 13 }; // Given subarray size K int k = 3; int n = sizeof arr / sizeof arr[0]; // Function Call cout << minimumOR(arr, n, k); return 0;} // Java program for minimum values of// each bitwise OR operation on// element of subarray of size Kimport java.util.*; class GFG{ // Function to convert bit array// to decimal numberstatic int build_num(int bit[]){ int ans = 0; for(int i = 0; i < 32; i++) if (bit[i] > 0) ans += (1 << i); return ans;} // Function to find minimum values of// each bitwise OR operation on// element of subarray of size Kstatic int minimumOR(int arr[], int n, int k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 int bit[] = new int[32]; // Create a sliding window of size k for(int i = 0; i < k; i++) { for(int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call int min_or = build_num(bit); for(int i = k; i < n; i++) { // Perform operation for // removed element for(int j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation for // added_element for(int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking minimum value min_or = Math.min(build_num(bit), min_or); } // Return the result return min_or;} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = { 2, 5, 3, 6, 11, 13 }; // Given subarray size K int k = 3; int n = arr.length; // Function call System.out.print(minimumOR(arr, n, k));}} // This code is contributed by Amit Katiyar # Python3 program for minimum values# of each bitwise OR operation on# element of subarray of size K # Function to convert bit array# to decimal numberdef build_num(bit): ans = 0; for i in range(32): if (bit[i] > 0): ans += (1 << i); return ans; # Function to find minimum values of# each bitwise OR operation on# element of subarray of size Kdef minimumOR(arr, n, k): # Maintain an integer array bit # of size 32 all initialized to 0 bit = [0] * 32; # Create a sliding window of size k for i in range(k): for j in range(32): if ((arr[i] & (1 << j)) > 0): bit[j] += 1; # Function call min_or = build_num(bit); for i in range(k, n): # Perform operation for # removed element for j in range(32): if ((arr[i - k] & (1 << j)) > 0): bit[j] -= 1; # Perform operation for # added_element for j in range(32): if ((arr[i] & (1 << j)) > 0): bit[j] += 1; # Taking minimum value min_or = min(build_num(bit), min_or); # Return the result return min_or; # Driver Codeif __name__ == '__main__': # Given array arr arr = [ 2, 5, 3, 6, 11, 13 ]; # Given subarray size K k = 3; n = len(arr); # Function call print(minimumOR(arr, n, k)); # This code is contributed by Amit Katiyar // C# program for minimum values of// each bitwise OR operation on// element of subarray of size Kusing System; class GFG{ // Function to convert bit array// to decimal numberstatic int build_num(int []bit){ int ans = 0; for(int i = 0; i < 32; i++) if (bit[i] > 0) ans += (1 << i); return ans;} // Function to find minimum values of// each bitwise OR operation on// element of subarray of size Kstatic int minimumOR(int []arr, int n, int k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 int []bit = new int[32]; // Create a sliding window of size k for(int i = 0; i < k; i++) { for(int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call int min_or = build_num(bit); for(int i = k; i < n; i++) { // Perform operation for // removed element for(int j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation for // added_element for(int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking minimum value min_or = Math.Min(build_num(bit), min_or); } // Return the result return min_or;} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = { 2, 5, 3, 6, 11, 13 }; // Given subarray size K int k = 3; int n = arr.Length; // Function call Console.Write(minimumOR(arr, n, k));}} // This code is contributed by Amit Katiyar <script> // Javascript program for minimum values of// each bitwise OR operation on// element of subarray of size K // Function to convert bit array// to decimal numberfunction build_num(bit){ let ans = 0; for(let i = 0; i < 32; i++) if (bit[i] > 0) ans += (1 << i); return ans;} // Function to find minimum values of// each bitwise OR operation on// element of subarray of size Kfunction minimumOR(arr, n, k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 let bit = new Array(32); bit.fill(0); // Create a sliding window of size k for(let i = 0; i < k; i++) { for(let j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call let min_or = build_num(bit); for(let i = k; i < n; i++) { // Perform operation for // removed element for(let j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation for // added_element for(let j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking minimum value min_or = Math.min(build_num(bit), min_or); } // Return the result return min_or;} // Driver code // Given array arr[]let arr = [ 2, 5, 3, 6, 11, 13 ]; // Given subarray size Klet k = 3;let n = arr.length; // Function Calldocument.write(minimumOR(arr, n, k)); // This code is contributed by rameshtravel07 </script> 7 Time Complexity: O(n * B) where n is the size of the array and B is the integer array bit of size 32. Auxiliary Space: O(n) Below is the program to find the Maximum Bitwise AND subarray: C++ Java Python3 C# Javascript // C++ program for maximum values of// each bitwise AND operation on// element of subarray of size K#include <iostream>using namespace std; // Function to convert bit array// to decimal numberint build_num(int bit[], int k){ int ans = 0; for (int i = 0; i < 32; i++) if (bit[i] == k) ans += (1 << i); return ans;} // Function to find maximum values of// each bitwise AND operation on// element of subarray of size Kint maximumAND(int arr[], int n, int k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 int bit[32] = { 0 }; // Create a sliding window of size k for (int i = 0; i < k; i++) { for (int j = 0; j < 32; j++) { if (arr[i] & (1 << j)) bit[j]++; } } // Function call int max_and = build_num(bit, k); for (int i = k; i < n; i++) { // Perform operation for // removed element for (int j = 0; j < 32; j++) { if (arr[i - k] & (1 << j)) bit[j]--; } // Perform operation for // added element for (int j = 0; j < 32; j++) { if (arr[i] & (1 << j)) bit[j]++; } // Taking maximum value max_and = max(build_num(bit, k), max_and); } // Return the result return max_and;} // Driver Codeint main(){ // Given array arr[] int arr[] = { 2, 5, 3, 6, 11, 13 }; // Given subarray size K int k = 3; int n = sizeof arr / sizeof arr[0]; // Function Call cout << maximumAND(arr, n, k); return 0;} // Java program for maximum values of// each bitwise AND operation on// element of subarray of size Kclass GFG{ // Function to convert bit array// to decimal numberstatic int build_num(int bit[], int k){ int ans = 0; for(int i = 0; i < 32; i++) if (bit[i] == k) ans += (1 << i); return ans;} // Function to find maximum values of// each bitwise AND operation on// element of subarray of size Kstatic int maximumAND(int arr[], int n, int k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 int bit[] = new int[32]; // Create a sliding window of size k for(int i = 0; i < k; i++) { for(int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call int max_and = build_num(bit, k); for(int i = k; i < n; i++) { // Perform operation for // removed element for(int j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation for // added element for(int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking maximum value max_and = Math.max(build_num(bit, k), max_and); } // Return the result return max_and;} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = { 2, 5, 3, 6, 11, 13 }; // Given subarray size K int k = 3; int n = arr.length; // Function call System.out.print(maximumAND(arr, n, k));}} // This code is contributed by 29AjayKumar # Python3 program for maximum values of# each bitwise AND operation on# element of subarray of size K # Function to convert bit array# to decimal numberdef build_num(bit, k): ans = 0; for i in range(32): if (bit[i] == k): ans += (1 << i); return ans; # Function to find maximum values of# each bitwise AND operation on# element of subarray of size Kdef maximumAND(arr, n, k): # Maintain an integer array bit # of size 32 all initialized to 0 bit = [0] * 32; # Create a sliding window of size k for i in range(k): for j in range(32): if ((arr[i] & (1 << j)) > 0): bit[j] += 1; # Function call max_and = build_num(bit, k); for i in range(k, n): # Perform operation for # removed element for j in range(32): if ((arr[i - k] & (1 << j)) > 0): bit[j] -= 1; # Perform operation for # added element for j in range(32): if ((arr[i] & (1 << j)) > 0): bit[j] += 1; # Taking maximum value max_and = max(build_num(bit, k), max_and); # Return the result return max_and; # Driver Codeif __name__ == '__main__': # Given array arr arr = [ 2, 5, 3, 6, 11, 13 ]; # Given subarray size K k = 3; n = len(arr); # Function call print(maximumAND(arr, n, k)); # This code is contributed by Amit Katiyar // C# program for maximum values of// each bitwise AND operation on// element of subarray of size Kusing System;class GFG{ // Function to convert bit // array to decimal number static int build_num(int[] bit, int k) { int ans = 0; for (int i = 0; i < 32; i++) if (bit[i] == k) ans += (1 << i); return ans; } // Function to find maximum values of // each bitwise AND operation on // element of subarray of size K static int maximumAND(int[] arr, int n, int k) { // Maintain an integer array bit[] // of size 32 all initialized to 0 int[] bit = new int[32]; // Create a sliding window of size k for (int i = 0; i < k; i++) { for (int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call int max_and = build_num(bit, k); for (int i = k; i < n; i++) { // Perform operation for // removed element for (int j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation for // added element for (int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking maximum value max_and = Math.Max(build_num(bit, k), max_and); } // Return the result return max_and; } // Driver Code public static void Main(String[] args) { // Given array []arr int[] arr = {2, 5, 3, 6, 11, 13}; // Given subarray size K int k = 3; int n = arr.Length; // Function call Console.Write(maximumAND(arr, n, k)); }} // This code is contributed by shikhasingrajput <script> // Javascript program for maximum values of // each bitwise AND operation on // element of subarray of size K // Function to convert bit // array to decimal number function build_num(bit, k) { let ans = 0; for (let i = 0; i < 32; i++) if (bit[i] == k) ans += (1 << i); return ans; } // Function to find maximum values of // each bitwise AND operation on // element of subarray of size K function maximumAND(arr, n, k) { // Maintain an integer array bit[] // of size 32 all initialized to 0 let bit = new Array(32); bit.fill(0); // Create a sliding window of size k for (let i = 0; i < k; i++) { for (let j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call let max_and = build_num(bit, k); for (let i = k; i < n; i++) { // Perform operation for // removed element for (let j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation for // added element for (let j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking maximum value max_and = Math.max(build_num(bit, k), max_and); } // Return the result return max_and; } // Given array []arr let arr = [2, 5, 3, 6, 11, 13]; // Given subarray size K let k = 3; let n = arr.length; // Function call document.write(maximumAND(arr, n, k)); // This code is contributed by mukesh07.</script> 2 Time Complexity: O(n * B) where n is the size of the array and B is the integer array bit of size 32. Auxiliary Space: O(n) Below is the program to find the Minimum Bitwise AND subarray: C++ Java Python3 C# Javascript // C++ program for minimum values of// each bitwise AND operation on// elements of subarray of size K#include <iostream>using namespace std; // Function to convert bit array// to decimal numberint build_num(int bit[], int k){ int ans = 0; for (int i = 0; i < 32; i++) if (bit[i] == k) ans += (1 << i); return ans;} // Function to find minimum values of// each bitwise AND operation on// element of subarray of size Kint minimumAND(int arr[], int n, int k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 int bit[32] = { 0 }; // Create a sliding window of size k for (int i = 0; i < k; i++) { for (int j = 0; j < 32; j++) { if (arr[i] & (1 << j)) bit[j]++; } } // Function call int min_and = build_num(bit, k); for (int i = k; i < n; i++) { // Perform operation to removed // element for (int j = 0; j < 32; j++) { if (arr[i - k] & (1 << j)) bit[j]--; } // Perform operation to add // element for (int j = 0; j < 32; j++) { if (arr[i] & (1 << j)) bit[j]++; } // Taking minimum value min_and = min(build_num(bit, k), min_and); } // Return the result return min_and;} // Driver Codeint main(){ // Given array arr[] int arr[] = { 2, 5, 3, 6, 11, 13 }; // Given subarray size K int k = 3; int n = sizeof arr / sizeof arr[0]; // Function Call cout << minimumAND(arr, n, k); return 0;} // Java program for minimum values of// each bitwise AND operation on// elements of subarray of size Kclass GFG{ // Function to convert bit array// to decimal numberstatic int build_num(int bit[], int k){ int ans = 0; for(int i = 0; i < 32; i++) if (bit[i] == k) ans += (1 << i); return ans;} // Function to find minimum values of// each bitwise AND operation on// element of subarray of size Kstatic int minimumAND(int arr[], int n, int k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 int bit[] = new int[32]; // Create a sliding window of size k for(int i = 0; i < k; i++) { for(int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call int min_and = build_num(bit, k); for(int i = k; i < n; i++) { // Perform operation to removed // element for(int j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation to add // element for(int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking minimum value min_and = Math.min(build_num(bit, k), min_and); } // Return the result return min_and;} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = { 2, 5, 3, 6, 11, 13 }; // Given subarray size K int k = 3; int n = arr.length; // Function call System.out.print(minimumAND(arr, n, k));}} // This code is contributed by 29AjayKumar # Python program for minimum values of# each bitwise AND operation on# elements of subarray of size K # Function to convert bit array# to decimal numberdef build_num(bit, k): ans = 0; for i in range(32): if (bit[i] == k): ans += (1 << i); return ans; # Function to find minimum values of# each bitwise AND operation on# element of subarray of size Kdef minimumAND(arr, n, k): # Maintain an integer array bit # of size 32 all initialized to 0 bit = [0] * 32; # Create a sliding window of size k for i in range(k): for j in range(32): if ((arr[i] & (1 << j)) > 0): bit[j] += 1; # Function call min_and = build_num(bit, k); for i in range(k, n): # Perform operation to removed # element for j in range(32): if ((arr[i - k] & (1 << j)) > 0): bit[j] -=1; # Perform operation to add # element for j in range(32): if ((arr[i] & (1 << j)) > 0): bit[j] += 1; # Taking minimum value min_and = min(build_num(bit, k), min_and); # Return the result return min_and; # Driver Codeif __name__ == '__main__': # Given array arr arr = [2, 5, 3, 6, 11, 13]; # Given subarray size K k = 3; n = len(arr); # Function call print(minimumAND(arr, n, k)); # This code contributed by Rajput-Ji // C# program for minimum values of// each bitwise AND operation on// elements of subarray of size Kusing System; class GFG{ // Function to convert bit array// to decimal numberstatic int build_num(int []bit, int k){ int ans = 0; for(int i = 0; i < 32; i++) if (bit[i] == k) ans += (1 << i); return ans;} // Function to find minimum values of// each bitwise AND operation on// element of subarray of size Kstatic int minimumAND(int []arr, int n, int k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 int []bit = new int[32]; // Create a sliding window of size k for(int i = 0; i < k; i++) { for(int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call int min_and = build_num(bit, k); for(int i = k; i < n; i++) { // Perform operation to removed // element for(int j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation to add // element for(int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking minimum value min_and = Math.Min(build_num(bit, k), min_and); } // Return the result return min_and;} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = { 2, 5, 3, 6, 11, 13 }; // Given subarray size K int k = 3; int n = arr.Length; // Function call Console.Write(minimumAND(arr, n, k));}} // This code is contributed by 29AjayKumar <script> // Javascript program for minimum values of // each bitwise AND operation on // elements of subarray of size K // Function to convert bit array // to decimal number function build_num(bit, k) { let ans = 0; for(let i = 0; i < 32; i++) if (bit[i] == k) ans += (1 << i); return ans; } // Function to find minimum values of // each bitwise AND operation on // element of subarray of size K function minimumAND(arr, n, k) { // Maintain an integer array bit[] // of size 32 all initialized to 0 let bit = new Array(32); bit.fill(0); // Create a sliding window of size k for(let i = 0; i < k; i++) { for(let j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call let min_and = build_num(bit, k); for(let i = k; i < n; i++) { // Perform operation to removed // element for(let j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation to add // element for(let j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking minimum value min_and = Math.min(build_num(bit, k), min_and); } // Return the result return min_and; } // Given array []arr let arr = [ 2, 5, 3, 6, 11, 13 ]; // Given subarray size K let k = 3; let n = arr.length; // Function call document.write(minimumAND(arr, n, k)); </script> 0 Time Complexity: O(n * B) where n is the size of the array and B is the integer array bit of size 32. Auxiliary Space: O(n) Below is the program to find the Minimum Bitwise XOR subarray: C++ Java Python3 C# Javascript // C++ program to find the subarray/// with minimum XOR#include <bits/stdc++.h>using namespace std; // Function to find the minimum XOR// of the subarray of size Kvoid findMinXORSubarray(int arr[], int n, int k){ // K must be smaller than // or equal to n if (n < k) return; // Initialize the beginning // index of result int res_index = 0; // Compute XOR sum of first // subarray of size K int curr_xor = 0; for (int i = 0; i < k; i++) curr_xor ^= arr[i]; // Initialize minimum XOR // sum as current xor int min_xor = curr_xor; // Traverse from (k+1)'th // element to n'th element for (int i = k; i < n; i++) { // XOR with current item // and first item of // previous subarray curr_xor ^= (arr[i] ^ arr[i - k]); // Update result if needed if (curr_xor < min_xor) { min_xor = curr_xor; res_index = (i - k + 1); } } // Print the minimum XOR cout << min_xor << "\n";} // Driver Codeint main(){ // Given array arr[] int arr[] = { 3, 7, 90, 20, 10, 50, 40 }; // Given subarray size K int k = 3; int n = sizeof(arr) / sizeof(arr[0]); // Function Call findMinXORSubarray(arr, n, k); return 0;} // Java program to find the subarray// with minimum XORclass GFG{ // Function to find the minimum XOR// of the subarray of size Kstatic void findMinXORSubarray(int arr[], int n, int k){ // K must be smaller than // or equal to n if (n < k) return; // Initialize the beginning // index of result int res_index = 0; // Compute XOR sum of first // subarray of size K int curr_xor = 0; for(int i = 0; i < k; i++) curr_xor ^= arr[i]; // Initialize minimum XOR // sum as current xor int min_xor = curr_xor; // Traverse from (k+1)'th // element to n'th element for(int i = k; i < n; i++) { // XOR with current item // and first item of // previous subarray curr_xor ^= (arr[i] ^ arr[i - k]); // Update result if needed if (curr_xor < min_xor) { min_xor = curr_xor; res_index = (i - k + 1); } } // Print the minimum XOR System.out.println(min_xor);} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = { 3, 7, 90, 20, 10, 50, 40 }; // Given subarray size K int k = 3; int n = arr.length; // Function call findMinXORSubarray(arr, n, k);}} // This code is contributed by rock_cool # Python3 program to find the subarray# with minimum XOR # Function to find the minimum XOR# of the subarray of size Kdef findMinXORSubarray(arr, n, k): # K must be smaller than # or equal to n if (n < k): return; # Initialize the beginning # index of result res_index = 0; # Compute XOR sum of first # subarray of size K curr_xor = 0; for i in range(k): curr_xor ^= arr[i]; # Initialize minimum XOR # sum as current xor min_xor = curr_xor; # Traverse from (k+1)'th # element to n'th element for i in range(k, n): # XOR with current item # and first item of # previous subarray curr_xor ^= (arr[i] ^ arr[i - k]); # Update result if needed if (curr_xor < min_xor): min_xor = curr_xor; res_index = (i - k + 1); # Print the minimum XOR print(min_xor); # Driver Codeif __name__ == '__main__': # Given array arr arr = [ 3, 7, 90, 20, 10, 50, 40 ]; # Given subarray size K k = 3; n = len(arr); # Function call findMinXORSubarray(arr, n, k); # This code is contributed by Amit Katiyar // C# program to find the subarray// with minimum XORusing System;class GFG{ // Function to find the minimum XOR// of the subarray of size Kstatic void findMinXORSubarray(int []arr, int n, int k){ // K must be smaller than // or equal to n if (n < k) return; // Initialize the beginning // index of result int res_index = 0; // Compute XOR sum of first // subarray of size K int curr_xor = 0; for(int i = 0; i < k; i++) curr_xor ^= arr[i]; // Initialize minimum XOR // sum as current xor int min_xor = curr_xor; // Traverse from (k+1)'th // element to n'th element for(int i = k; i < n; i++) { // XOR with current item // and first item of // previous subarray curr_xor ^= (arr[i] ^ arr[i - k]); // Update result if needed if (curr_xor < min_xor) { min_xor = curr_xor; res_index = (i - k + 1); } } // Print the minimum XOR Console.WriteLine(min_xor);} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = { 3, 7, 90, 20, 10, 50, 40 }; // Given subarray size K int k = 3; int n = arr.Length; // Function call findMinXORSubarray(arr, n, k);}} // This code is contributed by PrinciRaj1992 <script> // Javascript program to find the subarray// with minimum XOR // Function to find the minimum XOR// of the subarray of size Kfunction findMinXORSubarray(arr, n, k){ // K must be smaller than // or equal to n if (n < k) return; // Initialize the beginning // index of result let res_index = 0; // Compute XOR sum of first // subarray of size K let curr_xor = 0; for(let i = 0; i < k; i++) curr_xor ^= arr[i]; // Initialize minimum XOR // sum as current xor let min_xor = curr_xor; // Traverse from (k+1)'th // element to n'th element for(let i = k; i < n; i++) { // XOR with current item // and first item of // previous subarray curr_xor ^= (arr[i] ^ arr[i - k]); // Update result if needed if (curr_xor < min_xor) { min_xor = curr_xor; res_index = (i - k + 1); } } // Print the minimum XOR document.write(min_xor);} // Driver code // Given array arr[]let arr = [ 3, 7, 90, 20, 10, 50, 40 ]; // Given subarray size Klet k = 3;let n = arr.length; // Function CallfindMinXORSubarray(arr, n, k); // This code is contributed by divyeshrabadiya07 </script> 16 Time Complexity: O(n * B) where n is the size of the array and B is the integer array bit of size 32. Auxiliary Space: O(n) rock_cool princiraj1992 Rohit_ranjan 29AjayKumar shikhasingrajput amit143katiyar Rajput-Ji divyeshrabadiya07 divyesh072019 rameshtravel07 decode2207 mukesh07 Bitwise-AND Bitwise-OR Bitwise-XOR subarray Arrays Bit Magic Competitive Programming Arrays Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer How to swap two numbers without using a temporary variable?
[ { "code": null, "e": 24535, "s": 24507, "text": "\n15 Jun, 2021" }, { "code": null, "e": 24700, "s": 24535, "text": "Given an array arr[] of positive integers and a number K, the task is to find the minimum and maximum values of Bitwise operation on elements of subarray of size K." }, { "code": null, "e": 24710, "s": 24700, "text": "Examples:" }, { "code": null, "e": 25090, "s": 24710, "text": "Input: arr[]={2, 5, 3, 6, 11, 13}, k = 3 Output: Maximum AND = 2 Minimum AND = 0 Maximum OR = 15 Minimum OR = 7 Explanation: Maximum AND is generated by subarray 3, 6 and 11, 3 & 6 & 11 = 2 Minimum AND is generated by subarray 2, 3 and 5, 2 & 3 & 5 = 0 Maximum OR is generated by subarray 2, 6 and 13, 2 | 6 | 13 = 15 Minimum OR is generated by subarray 2, 3 and 5, 2 | 3 | 5 = 7" }, { "code": null, "e": 25196, "s": 25090, "text": "Input: arr[]={5, 9, 7, 19}, k = 2 Output: Maximum AND = 3 Minimum AND = 1 Maximum OR = 23 Minimum OR = 13" }, { "code": null, "e": 25422, "s": 25196, "text": "Naive Approach: The naive approach is to generate all possible subarrays of size K and check which of the above-formed subarray will give the minimum and maximum Bitwise OR and AND.Time Complexity: O(N2) Auxiliary Space: O(K)" }, { "code": null, "e": 25534, "s": 25422, "text": "Efficient Approach: The idea is to use the Sliding Window Technique to solve this problem. Below are the steps:" }, { "code": null, "e": 26150, "s": 25534, "text": "Traverse the prefix array of size K and for each array, element goes through it’s each bit and increases bit array (by maintaining an integer array bit of size 32) by 1 if it is set.Convert this bit array to a decimal number lets say ans, and move the sliding window to the next index.For newly added element for the next subarray of size K, Iterate through each bit of the newly added element and increase bit array by 1 if it is set.For removing the first element from the previous window, decrease bit array by 1 if it is set.Update ans with a minimum or maximum of the new decimal number generated by bit array." }, { "code": null, "e": 26333, "s": 26150, "text": "Traverse the prefix array of size K and for each array, element goes through it’s each bit and increases bit array (by maintaining an integer array bit of size 32) by 1 if it is set." }, { "code": null, "e": 26437, "s": 26333, "text": "Convert this bit array to a decimal number lets say ans, and move the sliding window to the next index." }, { "code": null, "e": 26588, "s": 26437, "text": "For newly added element for the next subarray of size K, Iterate through each bit of the newly added element and increase bit array by 1 if it is set." }, { "code": null, "e": 26683, "s": 26588, "text": "For removing the first element from the previous window, decrease bit array by 1 if it is set." }, { "code": null, "e": 26770, "s": 26683, "text": "Update ans with a minimum or maximum of the new decimal number generated by bit array." }, { "code": null, "e": 26832, "s": 26770, "text": "Below is the program to find the Maximum Bitwise OR subarray:" }, { "code": null, "e": 26836, "s": 26832, "text": "C++" }, { "code": null, "e": 26841, "s": 26836, "text": "Java" }, { "code": null, "e": 26849, "s": 26841, "text": "Python3" }, { "code": null, "e": 26852, "s": 26849, "text": "C#" }, { "code": null, "e": 26863, "s": 26852, "text": "Javascript" }, { "code": "// C++ program for maximum values of// each bitwise OR operation on// element of subarray of size K#include <iostream>using namespace std; // Function to convert bit array to// decimal numberint build_num(int bit[]){ int ans = 0; for (int i = 0; i < 32; i++) if (bit[i]) ans += (1 << i); return ans;} // Function to find maximum values of// each bitwise OR operation on// element of subarray of size Kint maximumOR(int arr[], int n, int k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 int bit[32] = { 0 }; // Create a sliding window of size k for (int i = 0; i < k; i++) { for (int j = 0; j < 32; j++) { if (arr[i] & (1 << j)) bit[j]++; } } // Function call int max_or = build_num(bit); for (int i = k; i < n; i++) { // Perform operation for // removed element for (int j = 0; j < 32; j++) { if (arr[i - k] & (1 << j)) bit[j]--; } // Perform operation for // added_element for (int j = 0; j < 32; j++) { if (arr[i] & (1 << j)) bit[j]++; } // Taking maximum value max_or = max(build_num(bit), max_or); } // Return the result return max_or;} // Driver Codeint main(){ // Given array arr[] int arr[] = { 2, 5, 3, 6, 11, 13 }; // Given subarray size K int k = 3; int n = sizeof arr / sizeof arr[0]; // Function Call cout << maximumOR(arr, n, k); return 0;}", "e": 28404, "s": 26863, "text": null }, { "code": "// Java program for maximum values of// each bitwise OR operation on// element of subarray of size Kimport java.util.*;class GFG{ // Function to convert bit array to// decimal numberstatic int build_num(int bit[]){ int ans = 0; for (int i = 0; i < 32; i++) if (bit[i] > 0) ans += (1 << i); return ans;} // Function to find maximum values of// each bitwise OR operation on// element of subarray of size Kstatic int maximumOR(int arr[], int n, int k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 int bit[] = new int[32]; // Create a sliding window of size k for (int i = 0; i < k; i++) { for (int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call int max_or = build_num(bit); for (int i = k; i < n; i++) { // Perform operation for // removed element for (int j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation for // added_element for (int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking maximum value max_or = Math.max(build_num(bit), max_or); } // Return the result return max_or;} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = { 2, 5, 3, 6, 11, 13 }; // Given subarray size K int k = 3; int n = arr.length; // Function Call System.out.print(maximumOR(arr, n, k));}} // This code is contributed by Rohit_ranjan", "e": 30061, "s": 28404, "text": null }, { "code": "# Python3 program for maximum values of# each bitwise OR operation on# element of subarray of size K # Function to convert bit array to# decimal numberdef build_num(bit): ans = 0; for i in range(32): if (bit[i] > 0): ans += (1 << i); return ans; # Function to find maximum values of# each bitwise OR operation on# element of subarray of size Kdef maximumOR(arr, n, k): # Maintain an integer array bit # of size 32 all initialized to 0 bit = [0] * 32; # Create a sliding window of size k for i in range(k): for j in range(32): if ((arr[i] & (1 << j)) > 0): bit[j] += 1; # Function call max_or = build_num(bit); for i in range(k, n): # Perform operation for # removed element for j in range(32): if ((arr[i - k] & (1 << j)) > 0): bit[j] -= 1; # Perform operation for # added_element for j in range(32): if ((arr[i] & (1 << j)) > 0): bit[j] += 1; # Taking maximum value max_or = max(build_num(bit), max_or); # Return the result return max_or; # Driver Codeif __name__ == '__main__': # Given array arr arr = [ 2, 5, 3, 6, 11, 13 ]; # Given subarray size K k = 3; n = len(arr); # Function call print(maximumOR(arr, n, k)); # This code is contributed by Amit Katiyar", "e": 31471, "s": 30061, "text": null }, { "code": "// C# program for maximum values of// each bitwise OR operation on// element of subarray of size Kusing System;class GFG{ // Function to convert bit // array to decimal number static int build_num(int[] bit) { int ans = 0; for (int i = 0; i < 32; i++) if (bit[i] > 0) ans += (1 << i); return ans; } // Function to find maximum values of // each bitwise OR operation on // element of subarray of size K static int maximumOR(int[] arr, int n, int k) { // Maintain an integer array bit[] // of size 32 all initialized to 0 int[] bit = new int[32]; // Create a sliding window of size k for (int i = 0; i < k; i++) { for (int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call int max_or = build_num(bit); for (int i = k; i < n; i++) { // Perform operation for // removed element for (int j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation for // added_element for (int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking maximum value max_or = Math.Max(build_num(bit), max_or); } // Return the result return max_or; } // Driver Code public static void Main(String[] args) { // Given array []arr int[] arr = {2, 5, 3, 6, 11, 13}; // Given subarray size K int k = 3; int n = arr.Length; // Function Call Console.Write(maximumOR(arr, n, k)); }} // This code is contributed by Rohit_ranjan", "e": 33363, "s": 31471, "text": null }, { "code": "<script> // Javascript program for maximum values of // each bitwise OR operation on // element of subarray of size K // Function to convert bit array to // decimal number function build_num(bit) { let ans = 0; for (let i = 0; i < 32; i++) if (bit[i] > 0) ans += (1 << i); return ans; } // Function to find maximum values of // each bitwise OR operation on // element of subarray of size K function maximumOR(arr, n, k) { // Maintain an integer array bit[] // of size 32 all initialized to 0 let bit = new Array(32); bit.fill(0); // Create a sliding window of size k for (let i = 0; i < k; i++) { for (let j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call let max_or = build_num(bit); for (let i = k; i < n; i++) { // Perform operation for // removed element for (let j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation for // added_element for (let j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking maximum value max_or = Math.max(build_num(bit), max_or); } // Return the result return max_or; } // Given array []arr let arr = [2, 5, 3, 6, 11, 13]; // Given subarray size K let k = 3; let n = arr.length; // Function Call document.write(maximumOR(arr, n, k)); // This code is contributed by divyesh072019.</script>", "e": 35193, "s": 33363, "text": null }, { "code": null, "e": 35196, "s": 35193, "text": "15" }, { "code": null, "e": 35321, "s": 35196, "text": "Time Complexity: O(n * B) where n is the size of the array and B is the integer array bit of size 32. Auxiliary Space: O(n) " }, { "code": null, "e": 35383, "s": 35321, "text": "Below is the program to find the Minimum Bitwise OR subarray:" }, { "code": null, "e": 35387, "s": 35383, "text": "C++" }, { "code": null, "e": 35392, "s": 35387, "text": "Java" }, { "code": null, "e": 35400, "s": 35392, "text": "Python3" }, { "code": null, "e": 35403, "s": 35400, "text": "C#" }, { "code": null, "e": 35414, "s": 35403, "text": "Javascript" }, { "code": "// C++ program for minimum values of// each bitwise OR operation on// element of subarray of size K#include <iostream>using namespace std; // Function to convert bit array// to decimal numberint build_num(int bit[]){ int ans = 0; for (int i = 0; i < 32; i++) if (bit[i]) ans += (1 << i); return ans;} // Function to find minimum values of// each bitwise OR operation on// element of subarray of size Kint minimumOR(int arr[], int n, int k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 int bit[32] = { 0 }; // Create a sliding window of size k for (int i = 0; i < k; i++) { for (int j = 0; j < 32; j++) { if (arr[i] & (1 << j)) bit[j]++; } } // Function call int min_or = build_num(bit); for (int i = k; i < n; i++) { // Perform operation for // removed element for (int j = 0; j < 32; j++) { if (arr[i - k] & (1 << j)) bit[j]--; } // Perform operation for // added_element for (int j = 0; j < 32; j++) { if (arr[i] & (1 << j)) bit[j]++; } // Taking minimum value min_or = min(build_num(bit), min_or); } // Return the result return min_or;} // Driver Codeint main(){ // Given array arr[] int arr[] = { 2, 5, 3, 6, 11, 13 }; // Given subarray size K int k = 3; int n = sizeof arr / sizeof arr[0]; // Function Call cout << minimumOR(arr, n, k); return 0;}", "e": 36976, "s": 35414, "text": null }, { "code": "// Java program for minimum values of// each bitwise OR operation on// element of subarray of size Kimport java.util.*; class GFG{ // Function to convert bit array// to decimal numberstatic int build_num(int bit[]){ int ans = 0; for(int i = 0; i < 32; i++) if (bit[i] > 0) ans += (1 << i); return ans;} // Function to find minimum values of// each bitwise OR operation on// element of subarray of size Kstatic int minimumOR(int arr[], int n, int k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 int bit[] = new int[32]; // Create a sliding window of size k for(int i = 0; i < k; i++) { for(int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call int min_or = build_num(bit); for(int i = k; i < n; i++) { // Perform operation for // removed element for(int j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation for // added_element for(int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking minimum value min_or = Math.min(build_num(bit), min_or); } // Return the result return min_or;} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = { 2, 5, 3, 6, 11, 13 }; // Given subarray size K int k = 3; int n = arr.length; // Function call System.out.print(minimumOR(arr, n, k));}} // This code is contributed by Amit Katiyar", "e": 38666, "s": 36976, "text": null }, { "code": "# Python3 program for minimum values# of each bitwise OR operation on# element of subarray of size K # Function to convert bit array# to decimal numberdef build_num(bit): ans = 0; for i in range(32): if (bit[i] > 0): ans += (1 << i); return ans; # Function to find minimum values of# each bitwise OR operation on# element of subarray of size Kdef minimumOR(arr, n, k): # Maintain an integer array bit # of size 32 all initialized to 0 bit = [0] * 32; # Create a sliding window of size k for i in range(k): for j in range(32): if ((arr[i] & (1 << j)) > 0): bit[j] += 1; # Function call min_or = build_num(bit); for i in range(k, n): # Perform operation for # removed element for j in range(32): if ((arr[i - k] & (1 << j)) > 0): bit[j] -= 1; # Perform operation for # added_element for j in range(32): if ((arr[i] & (1 << j)) > 0): bit[j] += 1; # Taking minimum value min_or = min(build_num(bit), min_or); # Return the result return min_or; # Driver Codeif __name__ == '__main__': # Given array arr arr = [ 2, 5, 3, 6, 11, 13 ]; # Given subarray size K k = 3; n = len(arr); # Function call print(minimumOR(arr, n, k)); # This code is contributed by Amit Katiyar", "e": 40072, "s": 38666, "text": null }, { "code": "// C# program for minimum values of// each bitwise OR operation on// element of subarray of size Kusing System; class GFG{ // Function to convert bit array// to decimal numberstatic int build_num(int []bit){ int ans = 0; for(int i = 0; i < 32; i++) if (bit[i] > 0) ans += (1 << i); return ans;} // Function to find minimum values of// each bitwise OR operation on// element of subarray of size Kstatic int minimumOR(int []arr, int n, int k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 int []bit = new int[32]; // Create a sliding window of size k for(int i = 0; i < k; i++) { for(int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call int min_or = build_num(bit); for(int i = k; i < n; i++) { // Perform operation for // removed element for(int j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation for // added_element for(int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking minimum value min_or = Math.Min(build_num(bit), min_or); } // Return the result return min_or;} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = { 2, 5, 3, 6, 11, 13 }; // Given subarray size K int k = 3; int n = arr.Length; // Function call Console.Write(minimumOR(arr, n, k));}} // This code is contributed by Amit Katiyar", "e": 41751, "s": 40072, "text": null }, { "code": "<script> // Javascript program for minimum values of// each bitwise OR operation on// element of subarray of size K // Function to convert bit array// to decimal numberfunction build_num(bit){ let ans = 0; for(let i = 0; i < 32; i++) if (bit[i] > 0) ans += (1 << i); return ans;} // Function to find minimum values of// each bitwise OR operation on// element of subarray of size Kfunction minimumOR(arr, n, k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 let bit = new Array(32); bit.fill(0); // Create a sliding window of size k for(let i = 0; i < k; i++) { for(let j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call let min_or = build_num(bit); for(let i = k; i < n; i++) { // Perform operation for // removed element for(let j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation for // added_element for(let j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking minimum value min_or = Math.min(build_num(bit), min_or); } // Return the result return min_or;} // Driver code // Given array arr[]let arr = [ 2, 5, 3, 6, 11, 13 ]; // Given subarray size Klet k = 3;let n = arr.length; // Function Calldocument.write(minimumOR(arr, n, k)); // This code is contributed by rameshtravel07 </script>", "e": 43335, "s": 41751, "text": null }, { "code": null, "e": 43337, "s": 43335, "text": "7" }, { "code": null, "e": 43461, "s": 43337, "text": "Time Complexity: O(n * B) where n is the size of the array and B is the integer array bit of size 32. Auxiliary Space: O(n)" }, { "code": null, "e": 43524, "s": 43461, "text": "Below is the program to find the Maximum Bitwise AND subarray:" }, { "code": null, "e": 43528, "s": 43524, "text": "C++" }, { "code": null, "e": 43533, "s": 43528, "text": "Java" }, { "code": null, "e": 43541, "s": 43533, "text": "Python3" }, { "code": null, "e": 43544, "s": 43541, "text": "C#" }, { "code": null, "e": 43555, "s": 43544, "text": "Javascript" }, { "code": "// C++ program for maximum values of// each bitwise AND operation on// element of subarray of size K#include <iostream>using namespace std; // Function to convert bit array// to decimal numberint build_num(int bit[], int k){ int ans = 0; for (int i = 0; i < 32; i++) if (bit[i] == k) ans += (1 << i); return ans;} // Function to find maximum values of// each bitwise AND operation on// element of subarray of size Kint maximumAND(int arr[], int n, int k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 int bit[32] = { 0 }; // Create a sliding window of size k for (int i = 0; i < k; i++) { for (int j = 0; j < 32; j++) { if (arr[i] & (1 << j)) bit[j]++; } } // Function call int max_and = build_num(bit, k); for (int i = k; i < n; i++) { // Perform operation for // removed element for (int j = 0; j < 32; j++) { if (arr[i - k] & (1 << j)) bit[j]--; } // Perform operation for // added element for (int j = 0; j < 32; j++) { if (arr[i] & (1 << j)) bit[j]++; } // Taking maximum value max_and = max(build_num(bit, k), max_and); } // Return the result return max_and;} // Driver Codeint main(){ // Given array arr[] int arr[] = { 2, 5, 3, 6, 11, 13 }; // Given subarray size K int k = 3; int n = sizeof arr / sizeof arr[0]; // Function Call cout << maximumAND(arr, n, k); return 0;}", "e": 45143, "s": 43555, "text": null }, { "code": "// Java program for maximum values of// each bitwise AND operation on// element of subarray of size Kclass GFG{ // Function to convert bit array// to decimal numberstatic int build_num(int bit[], int k){ int ans = 0; for(int i = 0; i < 32; i++) if (bit[i] == k) ans += (1 << i); return ans;} // Function to find maximum values of// each bitwise AND operation on// element of subarray of size Kstatic int maximumAND(int arr[], int n, int k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 int bit[] = new int[32]; // Create a sliding window of size k for(int i = 0; i < k; i++) { for(int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call int max_and = build_num(bit, k); for(int i = k; i < n; i++) { // Perform operation for // removed element for(int j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation for // added element for(int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking maximum value max_and = Math.max(build_num(bit, k), max_and); } // Return the result return max_and;} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = { 2, 5, 3, 6, 11, 13 }; // Given subarray size K int k = 3; int n = arr.length; // Function call System.out.print(maximumAND(arr, n, k));}} // This code is contributed by 29AjayKumar", "e": 46860, "s": 45143, "text": null }, { "code": "# Python3 program for maximum values of# each bitwise AND operation on# element of subarray of size K # Function to convert bit array# to decimal numberdef build_num(bit, k): ans = 0; for i in range(32): if (bit[i] == k): ans += (1 << i); return ans; # Function to find maximum values of# each bitwise AND operation on# element of subarray of size Kdef maximumAND(arr, n, k): # Maintain an integer array bit # of size 32 all initialized to 0 bit = [0] * 32; # Create a sliding window of size k for i in range(k): for j in range(32): if ((arr[i] & (1 << j)) > 0): bit[j] += 1; # Function call max_and = build_num(bit, k); for i in range(k, n): # Perform operation for # removed element for j in range(32): if ((arr[i - k] & (1 << j)) > 0): bit[j] -= 1; # Perform operation for # added element for j in range(32): if ((arr[i] & (1 << j)) > 0): bit[j] += 1; # Taking maximum value max_and = max(build_num(bit, k), max_and); # Return the result return max_and; # Driver Codeif __name__ == '__main__': # Given array arr arr = [ 2, 5, 3, 6, 11, 13 ]; # Given subarray size K k = 3; n = len(arr); # Function call print(maximumAND(arr, n, k)); # This code is contributed by Amit Katiyar", "e": 48305, "s": 46860, "text": null }, { "code": "// C# program for maximum values of// each bitwise AND operation on// element of subarray of size Kusing System;class GFG{ // Function to convert bit // array to decimal number static int build_num(int[] bit, int k) { int ans = 0; for (int i = 0; i < 32; i++) if (bit[i] == k) ans += (1 << i); return ans; } // Function to find maximum values of // each bitwise AND operation on // element of subarray of size K static int maximumAND(int[] arr, int n, int k) { // Maintain an integer array bit[] // of size 32 all initialized to 0 int[] bit = new int[32]; // Create a sliding window of size k for (int i = 0; i < k; i++) { for (int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call int max_and = build_num(bit, k); for (int i = k; i < n; i++) { // Perform operation for // removed element for (int j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation for // added element for (int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking maximum value max_and = Math.Max(build_num(bit, k), max_and); } // Return the result return max_and; } // Driver Code public static void Main(String[] args) { // Given array []arr int[] arr = {2, 5, 3, 6, 11, 13}; // Given subarray size K int k = 3; int n = arr.Length; // Function call Console.Write(maximumAND(arr, n, k)); }} // This code is contributed by shikhasingrajput", "e": 50264, "s": 48305, "text": null }, { "code": "<script> // Javascript program for maximum values of // each bitwise AND operation on // element of subarray of size K // Function to convert bit // array to decimal number function build_num(bit, k) { let ans = 0; for (let i = 0; i < 32; i++) if (bit[i] == k) ans += (1 << i); return ans; } // Function to find maximum values of // each bitwise AND operation on // element of subarray of size K function maximumAND(arr, n, k) { // Maintain an integer array bit[] // of size 32 all initialized to 0 let bit = new Array(32); bit.fill(0); // Create a sliding window of size k for (let i = 0; i < k; i++) { for (let j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call let max_and = build_num(bit, k); for (let i = k; i < n; i++) { // Perform operation for // removed element for (let j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation for // added element for (let j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking maximum value max_and = Math.max(build_num(bit, k), max_and); } // Return the result return max_and; } // Given array []arr let arr = [2, 5, 3, 6, 11, 13]; // Given subarray size K let k = 3; let n = arr.length; // Function call document.write(maximumAND(arr, n, k)); // This code is contributed by mukesh07.</script>", "e": 52130, "s": 50264, "text": null }, { "code": null, "e": 52132, "s": 52130, "text": "2" }, { "code": null, "e": 52257, "s": 52132, "text": "Time Complexity: O(n * B) where n is the size of the array and B is the integer array bit of size 32. Auxiliary Space: O(n) " }, { "code": null, "e": 52320, "s": 52257, "text": "Below is the program to find the Minimum Bitwise AND subarray:" }, { "code": null, "e": 52324, "s": 52320, "text": "C++" }, { "code": null, "e": 52329, "s": 52324, "text": "Java" }, { "code": null, "e": 52337, "s": 52329, "text": "Python3" }, { "code": null, "e": 52340, "s": 52337, "text": "C#" }, { "code": null, "e": 52351, "s": 52340, "text": "Javascript" }, { "code": "// C++ program for minimum values of// each bitwise AND operation on// elements of subarray of size K#include <iostream>using namespace std; // Function to convert bit array// to decimal numberint build_num(int bit[], int k){ int ans = 0; for (int i = 0; i < 32; i++) if (bit[i] == k) ans += (1 << i); return ans;} // Function to find minimum values of// each bitwise AND operation on// element of subarray of size Kint minimumAND(int arr[], int n, int k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 int bit[32] = { 0 }; // Create a sliding window of size k for (int i = 0; i < k; i++) { for (int j = 0; j < 32; j++) { if (arr[i] & (1 << j)) bit[j]++; } } // Function call int min_and = build_num(bit, k); for (int i = k; i < n; i++) { // Perform operation to removed // element for (int j = 0; j < 32; j++) { if (arr[i - k] & (1 << j)) bit[j]--; } // Perform operation to add // element for (int j = 0; j < 32; j++) { if (arr[i] & (1 << j)) bit[j]++; } // Taking minimum value min_and = min(build_num(bit, k), min_and); } // Return the result return min_and;} // Driver Codeint main(){ // Given array arr[] int arr[] = { 2, 5, 3, 6, 11, 13 }; // Given subarray size K int k = 3; int n = sizeof arr / sizeof arr[0]; // Function Call cout << minimumAND(arr, n, k); return 0;}", "e": 53935, "s": 52351, "text": null }, { "code": "// Java program for minimum values of// each bitwise AND operation on// elements of subarray of size Kclass GFG{ // Function to convert bit array// to decimal numberstatic int build_num(int bit[], int k){ int ans = 0; for(int i = 0; i < 32; i++) if (bit[i] == k) ans += (1 << i); return ans;} // Function to find minimum values of// each bitwise AND operation on// element of subarray of size Kstatic int minimumAND(int arr[], int n, int k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 int bit[] = new int[32]; // Create a sliding window of size k for(int i = 0; i < k; i++) { for(int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call int min_and = build_num(bit, k); for(int i = k; i < n; i++) { // Perform operation to removed // element for(int j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation to add // element for(int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking minimum value min_and = Math.min(build_num(bit, k), min_and); } // Return the result return min_and;} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = { 2, 5, 3, 6, 11, 13 }; // Given subarray size K int k = 3; int n = arr.length; // Function call System.out.print(minimumAND(arr, n, k));}} // This code is contributed by 29AjayKumar", "e": 55628, "s": 53935, "text": null }, { "code": "# Python program for minimum values of# each bitwise AND operation on# elements of subarray of size K # Function to convert bit array# to decimal numberdef build_num(bit, k): ans = 0; for i in range(32): if (bit[i] == k): ans += (1 << i); return ans; # Function to find minimum values of# each bitwise AND operation on# element of subarray of size Kdef minimumAND(arr, n, k): # Maintain an integer array bit # of size 32 all initialized to 0 bit = [0] * 32; # Create a sliding window of size k for i in range(k): for j in range(32): if ((arr[i] & (1 << j)) > 0): bit[j] += 1; # Function call min_and = build_num(bit, k); for i in range(k, n): # Perform operation to removed # element for j in range(32): if ((arr[i - k] & (1 << j)) > 0): bit[j] -=1; # Perform operation to add # element for j in range(32): if ((arr[i] & (1 << j)) > 0): bit[j] += 1; # Taking minimum value min_and = min(build_num(bit, k), min_and); # Return the result return min_and; # Driver Codeif __name__ == '__main__': # Given array arr arr = [2, 5, 3, 6, 11, 13]; # Given subarray size K k = 3; n = len(arr); # Function call print(minimumAND(arr, n, k)); # This code contributed by Rajput-Ji", "e": 57031, "s": 55628, "text": null }, { "code": "// C# program for minimum values of// each bitwise AND operation on// elements of subarray of size Kusing System; class GFG{ // Function to convert bit array// to decimal numberstatic int build_num(int []bit, int k){ int ans = 0; for(int i = 0; i < 32; i++) if (bit[i] == k) ans += (1 << i); return ans;} // Function to find minimum values of// each bitwise AND operation on// element of subarray of size Kstatic int minimumAND(int []arr, int n, int k){ // Maintain an integer array bit[] // of size 32 all initialized to 0 int []bit = new int[32]; // Create a sliding window of size k for(int i = 0; i < k; i++) { for(int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call int min_and = build_num(bit, k); for(int i = k; i < n; i++) { // Perform operation to removed // element for(int j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation to add // element for(int j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking minimum value min_and = Math.Min(build_num(bit, k), min_and); } // Return the result return min_and;} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = { 2, 5, 3, 6, 11, 13 }; // Given subarray size K int k = 3; int n = arr.Length; // Function call Console.Write(minimumAND(arr, n, k));}} // This code is contributed by 29AjayKumar", "e": 58737, "s": 57031, "text": null }, { "code": "<script> // Javascript program for minimum values of // each bitwise AND operation on // elements of subarray of size K // Function to convert bit array // to decimal number function build_num(bit, k) { let ans = 0; for(let i = 0; i < 32; i++) if (bit[i] == k) ans += (1 << i); return ans; } // Function to find minimum values of // each bitwise AND operation on // element of subarray of size K function minimumAND(arr, n, k) { // Maintain an integer array bit[] // of size 32 all initialized to 0 let bit = new Array(32); bit.fill(0); // Create a sliding window of size k for(let i = 0; i < k; i++) { for(let j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } } // Function call let min_and = build_num(bit, k); for(let i = k; i < n; i++) { // Perform operation to removed // element for(let j = 0; j < 32; j++) { if ((arr[i - k] & (1 << j)) > 0) bit[j]--; } // Perform operation to add // element for(let j = 0; j < 32; j++) { if ((arr[i] & (1 << j)) > 0) bit[j]++; } // Taking minimum value min_and = Math.min(build_num(bit, k), min_and); } // Return the result return min_and; } // Given array []arr let arr = [ 2, 5, 3, 6, 11, 13 ]; // Given subarray size K let k = 3; let n = arr.length; // Function call document.write(minimumAND(arr, n, k)); </script>", "e": 60525, "s": 58737, "text": null }, { "code": null, "e": 60527, "s": 60525, "text": "0" }, { "code": null, "e": 60652, "s": 60527, "text": "Time Complexity: O(n * B) where n is the size of the array and B is the integer array bit of size 32. Auxiliary Space: O(n) " }, { "code": null, "e": 60715, "s": 60652, "text": "Below is the program to find the Minimum Bitwise XOR subarray:" }, { "code": null, "e": 60719, "s": 60715, "text": "C++" }, { "code": null, "e": 60724, "s": 60719, "text": "Java" }, { "code": null, "e": 60732, "s": 60724, "text": "Python3" }, { "code": null, "e": 60735, "s": 60732, "text": "C#" }, { "code": null, "e": 60746, "s": 60735, "text": "Javascript" }, { "code": "// C++ program to find the subarray/// with minimum XOR#include <bits/stdc++.h>using namespace std; // Function to find the minimum XOR// of the subarray of size Kvoid findMinXORSubarray(int arr[], int n, int k){ // K must be smaller than // or equal to n if (n < k) return; // Initialize the beginning // index of result int res_index = 0; // Compute XOR sum of first // subarray of size K int curr_xor = 0; for (int i = 0; i < k; i++) curr_xor ^= arr[i]; // Initialize minimum XOR // sum as current xor int min_xor = curr_xor; // Traverse from (k+1)'th // element to n'th element for (int i = k; i < n; i++) { // XOR with current item // and first item of // previous subarray curr_xor ^= (arr[i] ^ arr[i - k]); // Update result if needed if (curr_xor < min_xor) { min_xor = curr_xor; res_index = (i - k + 1); } } // Print the minimum XOR cout << min_xor << \"\\n\";} // Driver Codeint main(){ // Given array arr[] int arr[] = { 3, 7, 90, 20, 10, 50, 40 }; // Given subarray size K int k = 3; int n = sizeof(arr) / sizeof(arr[0]); // Function Call findMinXORSubarray(arr, n, k); return 0;}", "e": 62033, "s": 60746, "text": null }, { "code": "// Java program to find the subarray// with minimum XORclass GFG{ // Function to find the minimum XOR// of the subarray of size Kstatic void findMinXORSubarray(int arr[], int n, int k){ // K must be smaller than // or equal to n if (n < k) return; // Initialize the beginning // index of result int res_index = 0; // Compute XOR sum of first // subarray of size K int curr_xor = 0; for(int i = 0; i < k; i++) curr_xor ^= arr[i]; // Initialize minimum XOR // sum as current xor int min_xor = curr_xor; // Traverse from (k+1)'th // element to n'th element for(int i = k; i < n; i++) { // XOR with current item // and first item of // previous subarray curr_xor ^= (arr[i] ^ arr[i - k]); // Update result if needed if (curr_xor < min_xor) { min_xor = curr_xor; res_index = (i - k + 1); } } // Print the minimum XOR System.out.println(min_xor);} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = { 3, 7, 90, 20, 10, 50, 40 }; // Given subarray size K int k = 3; int n = arr.length; // Function call findMinXORSubarray(arr, n, k);}} // This code is contributed by rock_cool", "e": 63361, "s": 62033, "text": null }, { "code": "# Python3 program to find the subarray# with minimum XOR # Function to find the minimum XOR# of the subarray of size Kdef findMinXORSubarray(arr, n, k): # K must be smaller than # or equal to n if (n < k): return; # Initialize the beginning # index of result res_index = 0; # Compute XOR sum of first # subarray of size K curr_xor = 0; for i in range(k): curr_xor ^= arr[i]; # Initialize minimum XOR # sum as current xor min_xor = curr_xor; # Traverse from (k+1)'th # element to n'th element for i in range(k, n): # XOR with current item # and first item of # previous subarray curr_xor ^= (arr[i] ^ arr[i - k]); # Update result if needed if (curr_xor < min_xor): min_xor = curr_xor; res_index = (i - k + 1); # Print the minimum XOR print(min_xor); # Driver Codeif __name__ == '__main__': # Given array arr arr = [ 3, 7, 90, 20, 10, 50, 40 ]; # Given subarray size K k = 3; n = len(arr); # Function call findMinXORSubarray(arr, n, k); # This code is contributed by Amit Katiyar", "e": 64511, "s": 63361, "text": null }, { "code": "// C# program to find the subarray// with minimum XORusing System;class GFG{ // Function to find the minimum XOR// of the subarray of size Kstatic void findMinXORSubarray(int []arr, int n, int k){ // K must be smaller than // or equal to n if (n < k) return; // Initialize the beginning // index of result int res_index = 0; // Compute XOR sum of first // subarray of size K int curr_xor = 0; for(int i = 0; i < k; i++) curr_xor ^= arr[i]; // Initialize minimum XOR // sum as current xor int min_xor = curr_xor; // Traverse from (k+1)'th // element to n'th element for(int i = k; i < n; i++) { // XOR with current item // and first item of // previous subarray curr_xor ^= (arr[i] ^ arr[i - k]); // Update result if needed if (curr_xor < min_xor) { min_xor = curr_xor; res_index = (i - k + 1); } } // Print the minimum XOR Console.WriteLine(min_xor);} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = { 3, 7, 90, 20, 10, 50, 40 }; // Given subarray size K int k = 3; int n = arr.Length; // Function call findMinXORSubarray(arr, n, k);}} // This code is contributed by PrinciRaj1992", "e": 65853, "s": 64511, "text": null }, { "code": "<script> // Javascript program to find the subarray// with minimum XOR // Function to find the minimum XOR// of the subarray of size Kfunction findMinXORSubarray(arr, n, k){ // K must be smaller than // or equal to n if (n < k) return; // Initialize the beginning // index of result let res_index = 0; // Compute XOR sum of first // subarray of size K let curr_xor = 0; for(let i = 0; i < k; i++) curr_xor ^= arr[i]; // Initialize minimum XOR // sum as current xor let min_xor = curr_xor; // Traverse from (k+1)'th // element to n'th element for(let i = k; i < n; i++) { // XOR with current item // and first item of // previous subarray curr_xor ^= (arr[i] ^ arr[i - k]); // Update result if needed if (curr_xor < min_xor) { min_xor = curr_xor; res_index = (i - k + 1); } } // Print the minimum XOR document.write(min_xor);} // Driver code // Given array arr[]let arr = [ 3, 7, 90, 20, 10, 50, 40 ]; // Given subarray size Klet k = 3;let n = arr.length; // Function CallfindMinXORSubarray(arr, n, k); // This code is contributed by divyeshrabadiya07 </script>", "e": 67090, "s": 65853, "text": null }, { "code": null, "e": 67093, "s": 67090, "text": "16" }, { "code": null, "e": 67219, "s": 67093, "text": "Time Complexity: O(n * B) where n is the size of the array and B is the integer array bit of size 32. Auxiliary Space: O(n) " }, { "code": null, "e": 67229, "s": 67219, "text": "rock_cool" }, { "code": null, "e": 67243, "s": 67229, "text": "princiraj1992" }, { "code": null, "e": 67256, "s": 67243, "text": "Rohit_ranjan" }, { "code": null, "e": 67268, "s": 67256, "text": "29AjayKumar" }, { "code": null, "e": 67285, "s": 67268, "text": "shikhasingrajput" }, { "code": null, "e": 67300, "s": 67285, "text": "amit143katiyar" }, { "code": null, "e": 67310, "s": 67300, "text": "Rajput-Ji" }, { "code": null, "e": 67328, "s": 67310, "text": "divyeshrabadiya07" }, { "code": null, "e": 67342, "s": 67328, "text": "divyesh072019" }, { "code": null, "e": 67357, "s": 67342, "text": "rameshtravel07" }, { "code": null, "e": 67368, "s": 67357, "text": "decode2207" }, { "code": null, "e": 67377, "s": 67368, "text": "mukesh07" }, { "code": null, "e": 67389, "s": 67377, "text": "Bitwise-AND" }, { "code": null, "e": 67400, "s": 67389, "text": "Bitwise-OR" }, { "code": null, "e": 67412, "s": 67400, "text": "Bitwise-XOR" }, { "code": null, "e": 67421, "s": 67412, "text": "subarray" }, { "code": null, "e": 67428, "s": 67421, "text": "Arrays" }, { "code": null, "e": 67438, "s": 67428, "text": "Bit Magic" }, { "code": null, "e": 67462, "s": 67438, "text": "Competitive Programming" }, { "code": null, "e": 67469, "s": 67462, "text": "Arrays" }, { "code": null, "e": 67479, "s": 67469, "text": "Bit Magic" }, { "code": null, "e": 67577, "s": 67479, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 67586, "s": 67577, "text": "Comments" }, { "code": null, "e": 67599, "s": 67586, "text": "Old Comments" }, { "code": null, "e": 67643, "s": 67599, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 67666, "s": 67643, "text": "Introduction to Arrays" }, { "code": null, "e": 67698, "s": 67666, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 67712, "s": 67698, "text": "Linear Search" }, { "code": null, "e": 67733, "s": 67712, "text": "Linked List vs Array" }, { "code": null, "e": 67760, "s": 67733, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 67806, "s": 67760, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 67874, "s": 67806, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 67903, "s": 67874, "text": "Count set bits in an integer" } ]
JFreeChart - Bubble Chart
This chapter demonstrates how you can use JFreeChart to create Bubble Chart from a given set of business data. A bubble chart displays information in three-dimensional way. A bubble is plotted at the place where (x, y) coordinate intersect. The size of the bubble is considered as range or quantity of X and Y axis. Let us consider different persons along with their age, weight, and work capacities. The wok capacity can be treated as number of hours that is plotted as bubbles in the chart. Following is the code to create Bubble Chart from the above given information. This code helps you to embed a Bubble chart in any AWT based application. import java.awt.Color; import java.awt.Dimension; import javax.swing.JPanel; import org.jfree.chart.*; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.data.xy.DefaultXYZDataset; import org.jfree.data.xy.XYZDataset; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; public class BubbleChart_AWT extends ApplicationFrame { public BubbleChart_AWT( String s ) { super( s ); JPanel jpanel = createDemoPanel( ); jpanel.setPreferredSize(new Dimension( 560 , 370 ) ); setContentPane( jpanel ); } private static JFreeChart createChart( XYZDataset xyzdataset ) { JFreeChart jfreechart = ChartFactory.createBubbleChart( "AGE vs WEIGHT vs WORK", "Weight", "AGE", xyzdataset, PlotOrientation.HORIZONTAL, true, true, false); XYPlot xyplot = ( XYPlot )jfreechart.getPlot( ); xyplot.setForegroundAlpha( 0.65F ); XYItemRenderer xyitemrenderer = xyplot.getRenderer( ); xyitemrenderer.setSeriesPaint( 0 , Color.blue ); NumberAxis numberaxis = ( NumberAxis )xyplot.getDomainAxis( ); numberaxis.setLowerMargin( 0.2 ); numberaxis.setUpperMargin( 0.5 ); NumberAxis numberaxis1 = ( NumberAxis )xyplot.getRangeAxis( ); numberaxis1.setLowerMargin( 0.8 ); numberaxis1.setUpperMargin( 0.9 ); return jfreechart; } public static XYZDataset createDataset( ) { DefaultXYZDataset defaultxyzdataset = new DefaultXYZDataset(); double ad[ ] = { 30 , 40 , 50 , 60 , 70 , 80 }; double ad1[ ] = { 10 , 20 , 30 , 40 , 50 , 60 }; double ad2[ ] = { 4 , 5 , 10 , 8 , 9 , 6 }; double ad3[][] = { ad , ad1 , ad2 }; defaultxyzdataset.addSeries( "Series 1" , ad3 ); return defaultxyzdataset; } public static JPanel createDemoPanel( ) { JFreeChart jfreechart = createChart( createDataset( ) ); ChartPanel chartpanel = new ChartPanel( jfreechart ); chartpanel.setDomainZoomable( true ); chartpanel.setRangeZoomable( true ); return chartpanel; } public static void main( String args[ ] ) { BubbleChart_AWT bubblechart = new BubbleChart_AWT( "Bubble Chart_frame" ); bubblechart.pack( ); RefineryUtilities.centerFrameOnScreen( bubblechart ); bubblechart.setVisible( true ); } } Let us keep the above Java code in BubbleChart_AWT.java file, and then compile and run it from the command prompted as − $javac BubbleChart_AWT.java $java BubbleChart_AW If everything is fine, it will compile and run to generate the following Bubble Graph − Let us re-write the above example to generate a JPEG image from a command line. import java.io.*; import java.awt.Color; import org.jfree.chart.*; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.data.xy.DefaultXYZDataset; import org.jfree.chart.ChartUtilities; public class BubbleChart_image { public static void main( String args[ ] )throws Exception { DefaultXYZDataset defaultxyzdataset = new DefaultXYZDataset( ); double ad[ ] = { 30 , 40 , 50 , 60 , 70 , 80 }; double ad1[ ] = { 10 , 20 , 30 , 40 , 50 , 60 }; double ad2[ ] = { 4 , 5 , 10 , 8 , 9 , 6 }; double ad3[ ][ ] = { ad , ad1 , ad2 }; defaultxyzdataset.addSeries( "Series 1" , ad3 ); JFreeChart jfreechart = ChartFactory.createBubbleChart( "AGE vs WEIGHT vs WORK", "Weight", "AGE", defaultxyzdataset, PlotOrientation.HORIZONTAL, true, true, false); XYPlot xyplot = ( XYPlot )jfreechart.getPlot( ); xyplot.setForegroundAlpha( 0.65F ); XYItemRenderer xyitemrenderer = xyplot.getRenderer( ); xyitemrenderer.setSeriesPaint( 0 , Color.blue ); NumberAxis numberaxis = ( NumberAxis )xyplot.getDomainAxis( ); numberaxis.setLowerMargin( 0.2 ); numberaxis.setUpperMargin( 0.5 ); NumberAxis numberaxis1 = ( NumberAxis )xyplot.getRangeAxis( ); numberaxis1.setLowerMargin( 0.8 ); numberaxis1.setUpperMargin( 0.9 ); int width = 560; /* Width of the image */ int height = 370; /* Height of the image */ File bubbleChart = new File("BubbleChart.jpeg"); ChartUtilities.saveChartAsJPEG(bubbleChart,jfreechart,width,height); } } Let us keep the above Java code in BubbleChart_image.java file, and then compile and run it from the command prompted as − $javac BubbleChart_image.java $java BubbleChart_image If everything is fine, it will compile and run to create a JPEG image file named BubbleChart.jpeg in your current directory. Print Add Notes Bookmark this page
[ { "code": null, "e": 2257, "s": 1941, "text": "This chapter demonstrates how you can use JFreeChart to create Bubble Chart from a given set of business data. A bubble chart displays information in three-dimensional way. A bubble is plotted at the place where (x, y) coordinate intersect. The size of the bubble is considered as range or quantity of X and Y axis." }, { "code": null, "e": 2434, "s": 2257, "text": "Let us consider different persons along with their age, weight, and work capacities. The wok capacity can be treated as number of hours that is plotted as bubbles in the chart." }, { "code": null, "e": 2587, "s": 2434, "text": "Following is the code to create Bubble Chart from the above given information. This code helps you to embed a Bubble chart in any AWT based application." }, { "code": null, "e": 5602, "s": 2587, "text": "import java.awt.Color; \nimport java.awt.Dimension; \n\nimport javax.swing.JPanel; \n\nimport org.jfree.chart.*; \nimport org.jfree.chart.axis.NumberAxis; \nimport org.jfree.chart.plot.PlotOrientation; \nimport org.jfree.chart.plot.XYPlot; \nimport org.jfree.chart.renderer.xy.XYItemRenderer; \nimport org.jfree.data.xy.DefaultXYZDataset; \nimport org.jfree.data.xy.XYZDataset; \nimport org.jfree.ui.ApplicationFrame; \nimport org.jfree.ui.RefineryUtilities;\n \npublic class BubbleChart_AWT extends ApplicationFrame {\n\n public BubbleChart_AWT( String s ) {\n super( s ); \n JPanel jpanel = createDemoPanel( ); \n jpanel.setPreferredSize(new Dimension( 560 , 370 ) ); \n setContentPane( jpanel ); \n }\n\n private static JFreeChart createChart( XYZDataset xyzdataset ) {\n JFreeChart jfreechart = ChartFactory.createBubbleChart(\n \"AGE vs WEIGHT vs WORK\", \n \"Weight\", \n \"AGE\", \n xyzdataset, \n PlotOrientation.HORIZONTAL, \n true, true, false);\n \n XYPlot xyplot = ( XYPlot )jfreechart.getPlot( ); \n xyplot.setForegroundAlpha( 0.65F ); \n XYItemRenderer xyitemrenderer = xyplot.getRenderer( );\n xyitemrenderer.setSeriesPaint( 0 , Color.blue ); \n NumberAxis numberaxis = ( NumberAxis )xyplot.getDomainAxis( ); \n numberaxis.setLowerMargin( 0.2 ); \n numberaxis.setUpperMargin( 0.5 ); \n NumberAxis numberaxis1 = ( NumberAxis )xyplot.getRangeAxis( ); \n numberaxis1.setLowerMargin( 0.8 ); \n numberaxis1.setUpperMargin( 0.9 );\n \n return jfreechart;\n }\n\n public static XYZDataset createDataset( ) {\n DefaultXYZDataset defaultxyzdataset = new DefaultXYZDataset(); \n double ad[ ] = { 30 , 40 , 50 , 60 , 70 , 80 }; \n double ad1[ ] = { 10 , 20 , 30 , 40 , 50 , 60 }; \n double ad2[ ] = { 4 , 5 , 10 , 8 , 9 , 6 }; \n double ad3[][] = { ad , ad1 , ad2 }; \n defaultxyzdataset.addSeries( \"Series 1\" , ad3 );\n \n return defaultxyzdataset; \n }\n\n public static JPanel createDemoPanel( ) {\n JFreeChart jfreechart = createChart( createDataset( ) ); \n ChartPanel chartpanel = new ChartPanel( jfreechart );\n \n chartpanel.setDomainZoomable( true ); \n chartpanel.setRangeZoomable( true );\n \n return chartpanel;\n }\n\n public static void main( String args[ ] ) {\n BubbleChart_AWT bubblechart = new BubbleChart_AWT( \"Bubble Chart_frame\" ); \n bubblechart.pack( ); \n RefineryUtilities.centerFrameOnScreen( bubblechart ); \n bubblechart.setVisible( true ); \n }\n}" }, { "code": null, "e": 5723, "s": 5602, "text": "Let us keep the above Java code in BubbleChart_AWT.java file, and then compile and run it from the command prompted as −" }, { "code": null, "e": 5776, "s": 5723, "text": "$javac BubbleChart_AWT.java \n$java BubbleChart_AW \n" }, { "code": null, "e": 5864, "s": 5776, "text": "If everything is fine, it will compile and run to generate the following Bubble Graph −" }, { "code": null, "e": 5944, "s": 5864, "text": "Let us re-write the above example to generate a JPEG image from a command line." }, { "code": null, "e": 7686, "s": 5944, "text": "import java.io.*;\n\nimport java.awt.Color; \n\nimport org.jfree.chart.*; \nimport org.jfree.chart.axis.NumberAxis;\nimport org.jfree.chart.plot.PlotOrientation;\nimport org.jfree.chart.plot.XYPlot;\nimport org.jfree.chart.renderer.xy.XYItemRenderer;\nimport org.jfree.data.xy.DefaultXYZDataset;\nimport org.jfree.chart.ChartUtilities;\n\npublic class BubbleChart_image {\n \n public static void main( String args[ ] )throws Exception {\n DefaultXYZDataset defaultxyzdataset = new DefaultXYZDataset( );\n double ad[ ] = { 30 , 40 , 50 , 60 , 70 , 80 };\n double ad1[ ] = { 10 , 20 , 30 , 40 , 50 , 60 };\n double ad2[ ] = { 4 , 5 , 10 , 8 , 9 , 6 };\n double ad3[ ][ ] = { ad , ad1 , ad2 };\n defaultxyzdataset.addSeries( \"Series 1\" , ad3 );\n\n JFreeChart jfreechart = ChartFactory.createBubbleChart(\n \"AGE vs WEIGHT vs WORK\", \n \"Weight\", \n \"AGE\", \n defaultxyzdataset, \n PlotOrientation.HORIZONTAL, \n true, true, false);\n\n XYPlot xyplot = ( XYPlot )jfreechart.getPlot( );\n xyplot.setForegroundAlpha( 0.65F );\n XYItemRenderer xyitemrenderer = xyplot.getRenderer( );\n xyitemrenderer.setSeriesPaint( 0 , Color.blue );\n NumberAxis numberaxis = ( NumberAxis )xyplot.getDomainAxis( );\n numberaxis.setLowerMargin( 0.2 );\n numberaxis.setUpperMargin( 0.5 );\n NumberAxis numberaxis1 = ( NumberAxis )xyplot.getRangeAxis( );\n numberaxis1.setLowerMargin( 0.8 );\n numberaxis1.setUpperMargin( 0.9 );\n\n int width = 560; /* Width of the image */\n int height = 370; /* Height of the image */ \n File bubbleChart = new File(\"BubbleChart.jpeg\"); \n ChartUtilities.saveChartAsJPEG(bubbleChart,jfreechart,width,height);\n }\n}" }, { "code": null, "e": 7809, "s": 7686, "text": "Let us keep the above Java code in BubbleChart_image.java file, and then compile and run it from the command prompted as −" }, { "code": null, "e": 7866, "s": 7809, "text": "$javac BubbleChart_image.java \n$java BubbleChart_image\n" }, { "code": null, "e": 7991, "s": 7866, "text": "If everything is fine, it will compile and run to create a JPEG image file named BubbleChart.jpeg in your current directory." }, { "code": null, "e": 7998, "s": 7991, "text": " Print" }, { "code": null, "e": 8009, "s": 7998, "text": " Add Notes" } ]
Coin Change | Practice | GeeksforGeeks
Given a value N, find the number of ways to make change for N cents, if we have infinite supply of each of S = { S1, S2, .. , SM } valued coins. Example 1: Input: n = 4 , m = 3 S[] = {1,2,3} Output: 4 Explanation: Four Possible ways are: {1,1,1,1},{1,1,2},{2,2},{1,3}. Example 2: Input: n = 10 , m = 4 S[] ={2,5,3,6} Output: 5 Explanation: Five Possible ways are: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. Your Task: You don't need to read input or print anything. Your task is to complete the function count() which accepts an array S[] its size m and n as input parameter and returns the number of ways to make change for N cents. Expected Time Complexity: O(m*n). Expected Auxiliary Space: O(n). Constraints: 1 <= n,m <= 103 0 abhaykumar92893 days ago class Solution { public long count(int S[], int m, int n) { // code here. long dp[]=new long[n+1]; dp[0]=1; for(int i=0;i<S.length;i++){//Iterate to each coin for(int j=S[i];j<dp.length;j++){// fill or dp for each value dp[j]+=dp[j-S[i]]; } } return dp[n]; }} 0 akshatsaxenaanpas3 days ago long long int count(int S[], int m, int n) { long long dp[n+1] = {0}; dp[0] = 1; for(int i=0;i<m;i++){ int count = 1; int coin = S[i]; for(int j=1;j<n+1;j++){ if(coin<=j){ int rem = j-coin; if(dp[rem]){ dp[j] += dp[rem]; } } } } return dp[n]; } +1 milindprajapatmst195 days ago # define ll long long const int N = 1e3; ll dp[N + 1]; class Solution { public: ll count(int S[], int n, int m) { memset(dp, 0, sizeof(dp)); dp[0] = 1; for (int i = 0; i < n; i++) { for (int j = 0; j <= m; j++) { if (j + S[i] <= m) dp[j + S[i]] += dp[j]; } } return dp[m]; } }; 0 shivamshuklashivam291 week ago long long int count(int S[], int m, int n) { // code here. if(m == 0 || n == 0) return 0; long long int dp[m+1][n+1]; for(int i=0;i<m+1;i++){ for(int j = 0;j<n+1;j++){ if(i == 0) dp[i][j] = 0; if(j == 0) dp[i][j] = 1; } } for(int i=1;i<m+1;i++){ for(int j = 1;j<n+1;j++){ if(S[i-1] <= j){ dp[i][j] = dp[i][j-S[i-1]] + dp[i-1][j]; } else dp[i][j] = dp[i-1][j]; } } return dp[m][n]; } 0 shivamshuklashivam29 This comment was deleted. 0 anuragshubham341 week ago class Solution { public long count(int s[], int m, int n) { long dp[]=new long[n+1]; Arrays.fill(dp,0); dp[0]=1; for(int i=0;i<m;i++){ for(int j=s[i];j<=n;j++){ dp[j]+=dp[j-s[i]]; } } return dp[n]; }} 0 devashishbakare2 weeks ago Java Dp solution (Tabulation) class Solution { public long count(int arr[], int m, int target) { //created dp array for target size+1 long dp[] = new long[target+1]; //self position is 1, pow(x, 0) -> 1 dp[0] = 1; //travers form total coins for(int i = 0 ; i < arr.length; i++) { //travels to given sum+1 for(int j = arr[i]; j < dp.length; j++) { dp[j] += dp[j - arr[i]]; } } //return total way to spend coin till give sum return dp[target]; } } 0 yasharthkatiyar2 weeks ago JAVA Soln :-(Unbounded Knapsack) class Solution { public long count(int s[], int m, int n) { long dp[][]=new long [m+1][n+1]; for(int i=0;i<n+1;i++) dp[0][i]=0; for(int i=0;i<m+1;i++) dp[i][0]=1; for(int i=1;i<m+1;i++) { for(int j=1;j<n+1;j++) { if(s[i-1]<=j) dp[i][j]=dp[i-1][j]+dp[i][j-s[i-1]]; else dp[i][j]=dp[i-1][j]; } } return dp[m][n]; }} 0 abhiswc292 weeks ago Python UnBounded Knapsack Variation class Solution: def count(self, S, m, n): # code here dp=[[0 for _ in range(n+1)]for _ in range(m+1)] dp[0][0]=1 for i in range(1,m+1): dp[i][0]=1 for i in range(1,n+1): dp[0][i]=0 for i in range(1,m+1): for j in range(1,n+1): if S[i-1]<=j: dp[i][j]=dp[i-1][j]+dp[i][j-S[i-1]] else: dp[i][j]=dp[i-1][j] return dp[m][n] -1 karanpratapsingh100012 weeks ago long long int count(int S[], int n, int s) { // code here. //😘😉😎💕using dp if(n==0) return 0; vector<long long> dp(s+1,0); dp[0]=1; for(int i=1;i<=n;i++) { for(int sum=1;sum<=s;sum++) { if(S[i-1]<=sum) dp[sum]+=dp[sum-S[i-1]]; } } return dp[s]; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 384, "s": 238, "text": "Given a value N, find the number of ways to make change for N cents, if we have infinite supply of each of S = { S1, S2, .. , SM } valued coins. " }, { "code": null, "e": 396, "s": 384, "text": "\nExample 1:" }, { "code": null, "e": 510, "s": 396, "text": "Input:\nn = 4 , m = 3\nS[] = {1,2,3}\nOutput: 4\nExplanation: Four Possible ways are:\n{1,1,1,1},{1,1,2},{2,2},{1,3}.\n" }, { "code": null, "e": 521, "s": 510, "text": "Example 2:" }, { "code": null, "e": 659, "s": 521, "text": "Input:\nn = 10 , m = 4\nS[] ={2,5,3,6}\nOutput: 5\nExplanation: Five Possible ways are:\n{2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} \nand {5,5}.\n" }, { "code": null, "e": 887, "s": 659, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function count() which accepts an array S[] its size m and n as input parameter and returns the number of ways to make change for N cents." }, { "code": null, "e": 955, "s": 887, "text": "\nExpected Time Complexity: O(m*n).\nExpected Auxiliary Space: O(n). " }, { "code": null, "e": 985, "s": 955, "text": "\nConstraints:\n1 <= n,m <= 103" }, { "code": null, "e": 987, "s": 985, "text": "0" }, { "code": null, "e": 1012, "s": 987, "text": "abhaykumar92893 days ago" }, { "code": null, "e": 1354, "s": 1012, "text": "class Solution { public long count(int S[], int m, int n) { // code here. long dp[]=new long[n+1]; dp[0]=1; for(int i=0;i<S.length;i++){//Iterate to each coin for(int j=S[i];j<dp.length;j++){// fill or dp for each value dp[j]+=dp[j-S[i]]; } } return dp[n]; }}" }, { "code": null, "e": 1356, "s": 1354, "text": "0" }, { "code": null, "e": 1384, "s": 1356, "text": "akshatsaxenaanpas3 days ago" }, { "code": null, "e": 1937, "s": 1384, "text": "long long int count(int S[], int m, int n) {\n\n \n long long dp[n+1] = {0};\n dp[0] = 1;\n \n for(int i=0;i<m;i++){\n int count = 1;\n int coin = S[i];\n for(int j=1;j<n+1;j++){\n if(coin<=j){\n int rem = j-coin;\n if(dp[rem]){\n dp[j] += dp[rem];\n }\n \n }\n }\n \n }\n return dp[n];\n \n \n }" }, { "code": null, "e": 1940, "s": 1937, "text": "+1" }, { "code": null, "e": 1970, "s": 1940, "text": "milindprajapatmst195 days ago" }, { "code": null, "e": 2359, "s": 1970, "text": "# define ll long long\nconst int N = 1e3;\nll dp[N + 1];\n\nclass Solution {\n public:\n ll count(int S[], int n, int m) {\n memset(dp, 0, sizeof(dp));\n dp[0] = 1;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j <= m; j++) {\n if (j + S[i] <= m)\n dp[j + S[i]] += dp[j];\n }\n }\n return dp[m];\n }\n};" }, { "code": null, "e": 2361, "s": 2359, "text": "0" }, { "code": null, "e": 2392, "s": 2361, "text": "shivamshuklashivam291 week ago" }, { "code": null, "e": 3008, "s": 2392, "text": "long long int count(int S[], int m, int n) {\n\n // code here.\n if(m == 0 || n == 0) return 0;\n \n long long int dp[m+1][n+1];\n \n for(int i=0;i<m+1;i++){\n for(int j = 0;j<n+1;j++){\n if(i == 0) dp[i][j] = 0;\n if(j == 0) dp[i][j] = 1;\n }\n }\n for(int i=1;i<m+1;i++){\n for(int j = 1;j<n+1;j++){\n if(S[i-1] <= j){\n dp[i][j] = dp[i][j-S[i-1]] + dp[i-1][j];\n }\n else dp[i][j] = dp[i-1][j];\n }\n }\n return dp[m][n];\n }" }, { "code": null, "e": 3010, "s": 3008, "text": "0" }, { "code": null, "e": 3031, "s": 3010, "text": "shivamshuklashivam29" }, { "code": null, "e": 3057, "s": 3031, "text": "This comment was deleted." }, { "code": null, "e": 3059, "s": 3057, "text": "0" }, { "code": null, "e": 3085, "s": 3059, "text": "anuragshubham341 week ago" }, { "code": null, "e": 3353, "s": 3085, "text": "class Solution { public long count(int s[], int m, int n) { long dp[]=new long[n+1]; Arrays.fill(dp,0); dp[0]=1; for(int i=0;i<m;i++){ for(int j=s[i];j<=n;j++){ dp[j]+=dp[j-s[i]]; } } return dp[n]; }}" }, { "code": null, "e": 3355, "s": 3353, "text": "0" }, { "code": null, "e": 3382, "s": 3355, "text": "devashishbakare2 weeks ago" }, { "code": null, "e": 3412, "s": 3382, "text": "Java Dp solution (Tabulation)" }, { "code": null, "e": 4016, "s": 3412, "text": "class Solution {\n public long count(int arr[], int m, int target) {\n \n //created dp array for target size+1\n long dp[] = new long[target+1];\n \n //self position is 1, pow(x, 0) -> 1\n dp[0] = 1;\n \n //travers form total coins\n for(int i = 0 ; i < arr.length; i++)\n {\n //travels to given sum+1\n for(int j = arr[i]; j < dp.length; j++)\n {\n dp[j] += dp[j - arr[i]];\n }\n }\n \n //return total way to spend coin till give sum\n return dp[target];\n }\n}" }, { "code": null, "e": 4018, "s": 4016, "text": "0" }, { "code": null, "e": 4045, "s": 4018, "text": "yasharthkatiyar2 weeks ago" }, { "code": null, "e": 4078, "s": 4045, "text": "JAVA Soln :-(Unbounded Knapsack)" }, { "code": null, "e": 4492, "s": 4080, "text": "class Solution { public long count(int s[], int m, int n) { long dp[][]=new long [m+1][n+1]; for(int i=0;i<n+1;i++) dp[0][i]=0; for(int i=0;i<m+1;i++) dp[i][0]=1; for(int i=1;i<m+1;i++) { for(int j=1;j<n+1;j++) { if(s[i-1]<=j) dp[i][j]=dp[i-1][j]+dp[i][j-s[i-1]]; else dp[i][j]=dp[i-1][j]; } } return dp[m][n]; }}" }, { "code": null, "e": 4494, "s": 4492, "text": "0" }, { "code": null, "e": 4515, "s": 4494, "text": "abhiswc292 weeks ago" }, { "code": null, "e": 4551, "s": 4515, "text": "Python UnBounded Knapsack Variation" }, { "code": null, "e": 5039, "s": 4551, "text": "class Solution:\n def count(self, S, m, n): \n # code here\n dp=[[0 for _ in range(n+1)]for _ in range(m+1)]\n dp[0][0]=1\n for i in range(1,m+1):\n dp[i][0]=1\n for i in range(1,n+1):\n dp[0][i]=0\n for i in range(1,m+1):\n for j in range(1,n+1):\n if S[i-1]<=j:\n dp[i][j]=dp[i-1][j]+dp[i][j-S[i-1]]\n else:\n dp[i][j]=dp[i-1][j]\n return dp[m][n]" }, { "code": null, "e": 5042, "s": 5039, "text": "-1" }, { "code": null, "e": 5075, "s": 5042, "text": "karanpratapsingh100012 weeks ago" }, { "code": null, "e": 5477, "s": 5075, "text": "long long int count(int S[], int n, int s) {\n\n // code here.\n //😘😉😎💕using dp\n if(n==0) return 0;\n \n vector<long long> dp(s+1,0);\n dp[0]=1;\n \n for(int i=1;i<=n;i++)\n {\n for(int sum=1;sum<=s;sum++)\n {\n if(S[i-1]<=sum) dp[sum]+=dp[sum-S[i-1]];\n }\n }\n \n return dp[s];\n }" }, { "code": null, "e": 5623, "s": 5477, "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": 5659, "s": 5623, "text": " Login to access your submissions. " }, { "code": null, "e": 5669, "s": 5659, "text": "\nProblem\n" }, { "code": null, "e": 5679, "s": 5669, "text": "\nContest\n" }, { "code": null, "e": 5742, "s": 5679, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5890, "s": 5742, "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": 6098, "s": 5890, "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": 6204, "s": 6098, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Last digit of sum of numbers in the given range in the Fibonacci series - GeeksforGeeks
12 Nov, 2021 Given two non-negative integers M, N which signifies the range [M, N] where M ≤ N, the task is to find the last digit of the sum of FM + FM+1... + FN where FK is the Kth Fibonacci number in the Fibonacci series. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... Examples: Input: M = 3, N = 9 Output: 6 Explanation: We need to find F3 + F4 + F5 + F6 + F7 + F8 + F9 => 2 + 3 + 5 + 8 + 13 + 21 + 34 = 86. Clearly, the last digit of the sum is 6.Input: M = 3, N = 7 Output: 1 Explanation: We need to find F3 + F4 + F5 + F6 + F7 => 2 + 3 + 5 + 8 + 13 = 31. Clearly, the last digit of the sum is 1. Naive Approach: The naive approach for this problem is to one by one find the sum of all Kth Fibonacci Numbers where K lies in the range [M, N] and return the last digit of the sum in the end. The time complexity for this approach is O(N) and this method fails for higher-ordered values of N. Efficient Approach: An efficient approach for this problem is to use the concept of Pisano Period. The idea is to calculate the sum of (M – 1) and N Fibonacci numbers respectively, and subtracting the last digit of the computed values. This is because the last digit of the sum of all the Kth Fibonacci numbers such that K lies in the range [M, N] is equal to the difference of the last digits of the sum of all the Kth Fibonacci numbers in the range [0, N] and the sum of all the Kth Fibonacci numbers in the range [0, M – 1]. These values can respectively be calculated by the concept of the Pisano period in a very short time. Let’s understand how the Pisano period works. The following table illustrates the first 10 Fibonacci numbers along with its values obtained when modulo 2 is performed on the numbers. Clearly, the Pisano period for (Fi mod 2) is 3 since 011 repeat itself and length(011) = 3. Now, lets observe the following identity: 7 = 2 * 3 + 1 Dividend = (Quotient × Divisor) + Remainder => F7 mod 2 = F1 mod 2 = 1. Therefore, instead of calculating the last digit of the sum of all numbers in the range [0, N], we simply calculate the sum until the remainder given that the Pisano period for Fi mod 10 is 60. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to calculate// last digit of the sum of the// fibonacci numbers from M to N#include<bits/stdc++.h>using namespace std; // Calculate the sum of the first// N Fibonacci numbers using Pisano// periodlong long fib(long long n){ // The first two Fibonacci numbers long long f0 = 0; long long f1 = 1; // Base case if (n == 0) return 0; if (n == 1) return 1; else { // Pisano period for % 10 is 60 long long rem = n % 60; // Checking the remainder if(rem == 0) return 0; // The loop will range from 2 to // two terms after the remainder for(long long i = 2; i < rem + 3; i++) { long long f = (f0 + f1) % 60; f0 = f1; f1 = f; } long long s = f1 - 1; return s; }} // Driver Codeint main(){ long long m = 10087887; long long n = 2983097899; long long final = abs(fib(n) - fib(m - 1)); cout << final % 10 << endl;} // This code is contributed by Bhupendra_Singh // Java program to calculate// last digit of the sum of the// fibonacci numbers from M to Nimport java.util.*; class GFG{ // Calculate the sum of the first// N Fibonacci numbers using Pisano// periodstatic int fib(long n){ // The first two Fibonacci numbers int f0 = 0; int f1 = 1; // Base case if (n == 0) return 0; if (n == 1) return 1; else { // Pisano period for % 10 is 60 int rem = (int) (n % 60); // Checking the remainder if(rem == 0) return 0; // The loop will range from 2 to // two terms after the remainder for(int i = 2; i < rem + 3; i++) { int f = (f0 + f1) % 60; f0 = f1; f1 = f; } int s = f1 - 1; return s; }} // Driver Codepublic static void main(String args[]){ int m = 10087887; long n = 2983097899L; int Final = (int)Math.abs(fib(n) - fib(m - 1)); System.out.println(Final % 10);}} // This code is contributed by AbhiThakur # Python3 program to calculate# Last Digit of the sum of the# Fibonacci numbers from M to N # Calculate the sum of the first# N Fibonacci numbers using Pisano# perioddef fib(n): # The first two Fibonacci numbers f0 = 0 f1 = 1 # Base case if (n == 0): return 0 if (n == 1): return 1 else: # Pisano Period for % 10 is 60 rem = n % 60 # Checking the remainder if(rem == 0): return 0 # The loop will range from 2 to # two terms after the remainder for i in range(2, rem + 3): f =(f0 + f1)% 60 f0 = f1 f1 = f s = f1-1 return(s) # Driver codeif __name__ == '__main__': m = 10087887 n = 2983097899 final = fib(n)-fib(m-1) print(final % 10) // C# program to calculate// last digit of the sum of the// fibonacci numbers from M to Nusing System; class GFG{ // Calculate the sum of the first// N fibonacci numbers using Pisano// periodstatic int fib(long n){ // The first two fibonacci numbers int f0 = 0; int f1 = 1; // Base case if (n == 0) return 0; if (n == 1) return 1; else { // Pisano period for % 10 is 60 int rem = (int)(n % 60); // Checking the remainder if(rem == 0) return 0; // The loop will range from 2 to // two terms after the remainder for(int i = 2; i < rem + 3; i++) { int f = (f0 + f1) % 60; f0 = f1; f1 = f; } int s = f1 - 1; return s; }} // Driver Codepublic static void Main(){ int m = 10087887; long n = 2983097899L; int Final = (int)Math.Abs(fib(n) - fib(m - 1)); Console.WriteLine(Final % 10);}} // This code is contributed by Code_Mech <script>// javascript program to calculate// last digit of the sum of the// fibonacci numbers from M to N // Calculate the sum of the first // N Fibonacci numbers using Pisano // period function fib(n) { // The first two Fibonacci numbers var f0 = 0; var f1 = 1; // Base case if (n == 0) return 0; if (n == 1) return 1; else { // Pisano period for % 10 is 60 var rem = parseInt( (n % 60)); // Checking the remainder if (rem == 0) return 0; // The loop will range from 2 to // two terms after the remainder for (i = 2; i < rem + 3; i++) { var f = (f0 + f1) % 60; f0 = f1; f1 = f; } var s = f1 - 1; return s; } } // Driver Code var m = 10087887; var n = 2983097899; var Final = parseInt( Math.abs(fib(n) - fib(m - 1))); document.write(Final % 10); // This code is contributed by Rajput-Ji</script> 5 Time Complexity: O(1), because this code runs almost 60 times for any input number. Auxiliary Space: O(1) bgangwar59 abhaysingh290895 Code_Mech shobitham1 Rajput-Ji subham348 Fibonacci series series-sum Mathematical Pattern Searching Write From Home Mathematical series Fibonacci Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Find all factors of a natural number | Set 1 Check if a number is Palindrome Program to print prime numbers from 1 to N. Program to add two binary strings Fizz Buzz Implementation KMP Algorithm for Pattern Searching Rabin-Karp Algorithm for Pattern Searching Check if a string is substring of another Naive algorithm for Pattern Searching Boyer Moore Algorithm for Pattern Searching
[ { "code": null, "e": 24327, "s": 24299, "text": "\n12 Nov, 2021" }, { "code": null, "e": 24541, "s": 24327, "text": "Given two non-negative integers M, N which signifies the range [M, N] where M ≤ N, the task is to find the last digit of the sum of FM + FM+1... + FN where FK is the Kth Fibonacci number in the Fibonacci series. " }, { "code": null, "e": 24593, "s": 24541, "text": "0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... " }, { "code": null, "e": 24605, "s": 24593, "text": "Examples: " }, { "code": null, "e": 24928, "s": 24605, "text": "Input: M = 3, N = 9 Output: 6 Explanation: We need to find F3 + F4 + F5 + F6 + F7 + F8 + F9 => 2 + 3 + 5 + 8 + 13 + 21 + 34 = 86. Clearly, the last digit of the sum is 6.Input: M = 3, N = 7 Output: 1 Explanation: We need to find F3 + F4 + F5 + F6 + F7 => 2 + 3 + 5 + 8 + 13 = 31. Clearly, the last digit of the sum is 1. " }, { "code": null, "e": 25324, "s": 24930, "text": "Naive Approach: The naive approach for this problem is to one by one find the sum of all Kth Fibonacci Numbers where K lies in the range [M, N] and return the last digit of the sum in the end. The time complexity for this approach is O(N) and this method fails for higher-ordered values of N. Efficient Approach: An efficient approach for this problem is to use the concept of Pisano Period. " }, { "code": null, "e": 25461, "s": 25324, "text": "The idea is to calculate the sum of (M – 1) and N Fibonacci numbers respectively, and subtracting the last digit of the computed values." }, { "code": null, "e": 25753, "s": 25461, "text": "This is because the last digit of the sum of all the Kth Fibonacci numbers such that K lies in the range [M, N] is equal to the difference of the last digits of the sum of all the Kth Fibonacci numbers in the range [0, N] and the sum of all the Kth Fibonacci numbers in the range [0, M – 1]." }, { "code": null, "e": 25855, "s": 25753, "text": "These values can respectively be calculated by the concept of the Pisano period in a very short time." }, { "code": null, "e": 26039, "s": 25855, "text": "Let’s understand how the Pisano period works. The following table illustrates the first 10 Fibonacci numbers along with its values obtained when modulo 2 is performed on the numbers. " }, { "code": null, "e": 26133, "s": 26041, "text": "Clearly, the Pisano period for (Fi mod 2) is 3 since 011 repeat itself and length(011) = 3." }, { "code": null, "e": 26177, "s": 26133, "text": "Now, lets observe the following identity: " }, { "code": null, "e": 26265, "s": 26177, "text": "7 = 2 * 3 + 1 Dividend = (Quotient × Divisor) + Remainder => F7 mod 2 = F1 mod 2 = 1. " }, { "code": null, "e": 26459, "s": 26265, "text": "Therefore, instead of calculating the last digit of the sum of all numbers in the range [0, N], we simply calculate the sum until the remainder given that the Pisano period for Fi mod 10 is 60." }, { "code": null, "e": 26511, "s": 26459, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26515, "s": 26511, "text": "C++" }, { "code": null, "e": 26520, "s": 26515, "text": "Java" }, { "code": null, "e": 26528, "s": 26520, "text": "Python3" }, { "code": null, "e": 26531, "s": 26528, "text": "C#" }, { "code": null, "e": 26542, "s": 26531, "text": "Javascript" }, { "code": "// C++ program to calculate// last digit of the sum of the// fibonacci numbers from M to N#include<bits/stdc++.h>using namespace std; // Calculate the sum of the first// N Fibonacci numbers using Pisano// periodlong long fib(long long n){ // The first two Fibonacci numbers long long f0 = 0; long long f1 = 1; // Base case if (n == 0) return 0; if (n == 1) return 1; else { // Pisano period for % 10 is 60 long long rem = n % 60; // Checking the remainder if(rem == 0) return 0; // The loop will range from 2 to // two terms after the remainder for(long long i = 2; i < rem + 3; i++) { long long f = (f0 + f1) % 60; f0 = f1; f1 = f; } long long s = f1 - 1; return s; }} // Driver Codeint main(){ long long m = 10087887; long long n = 2983097899; long long final = abs(fib(n) - fib(m - 1)); cout << final % 10 << endl;} // This code is contributed by Bhupendra_Singh", "e": 27596, "s": 26542, "text": null }, { "code": "// Java program to calculate// last digit of the sum of the// fibonacci numbers from M to Nimport java.util.*; class GFG{ // Calculate the sum of the first// N Fibonacci numbers using Pisano// periodstatic int fib(long n){ // The first two Fibonacci numbers int f0 = 0; int f1 = 1; // Base case if (n == 0) return 0; if (n == 1) return 1; else { // Pisano period for % 10 is 60 int rem = (int) (n % 60); // Checking the remainder if(rem == 0) return 0; // The loop will range from 2 to // two terms after the remainder for(int i = 2; i < rem + 3; i++) { int f = (f0 + f1) % 60; f0 = f1; f1 = f; } int s = f1 - 1; return s; }} // Driver Codepublic static void main(String args[]){ int m = 10087887; long n = 2983097899L; int Final = (int)Math.abs(fib(n) - fib(m - 1)); System.out.println(Final % 10);}} // This code is contributed by AbhiThakur", "e": 28667, "s": 27596, "text": null }, { "code": "# Python3 program to calculate# Last Digit of the sum of the# Fibonacci numbers from M to N # Calculate the sum of the first# N Fibonacci numbers using Pisano# perioddef fib(n): # The first two Fibonacci numbers f0 = 0 f1 = 1 # Base case if (n == 0): return 0 if (n == 1): return 1 else: # Pisano Period for % 10 is 60 rem = n % 60 # Checking the remainder if(rem == 0): return 0 # The loop will range from 2 to # two terms after the remainder for i in range(2, rem + 3): f =(f0 + f1)% 60 f0 = f1 f1 = f s = f1-1 return(s) # Driver codeif __name__ == '__main__': m = 10087887 n = 2983097899 final = fib(n)-fib(m-1) print(final % 10)", "e": 29467, "s": 28667, "text": null }, { "code": "// C# program to calculate// last digit of the sum of the// fibonacci numbers from M to Nusing System; class GFG{ // Calculate the sum of the first// N fibonacci numbers using Pisano// periodstatic int fib(long n){ // The first two fibonacci numbers int f0 = 0; int f1 = 1; // Base case if (n == 0) return 0; if (n == 1) return 1; else { // Pisano period for % 10 is 60 int rem = (int)(n % 60); // Checking the remainder if(rem == 0) return 0; // The loop will range from 2 to // two terms after the remainder for(int i = 2; i < rem + 3; i++) { int f = (f0 + f1) % 60; f0 = f1; f1 = f; } int s = f1 - 1; return s; }} // Driver Codepublic static void Main(){ int m = 10087887; long n = 2983097899L; int Final = (int)Math.Abs(fib(n) - fib(m - 1)); Console.WriteLine(Final % 10);}} // This code is contributed by Code_Mech", "e": 30517, "s": 29467, "text": null }, { "code": "<script>// javascript program to calculate// last digit of the sum of the// fibonacci numbers from M to N // Calculate the sum of the first // N Fibonacci numbers using Pisano // period function fib(n) { // The first two Fibonacci numbers var f0 = 0; var f1 = 1; // Base case if (n == 0) return 0; if (n == 1) return 1; else { // Pisano period for % 10 is 60 var rem = parseInt( (n % 60)); // Checking the remainder if (rem == 0) return 0; // The loop will range from 2 to // two terms after the remainder for (i = 2; i < rem + 3; i++) { var f = (f0 + f1) % 60; f0 = f1; f1 = f; } var s = f1 - 1; return s; } } // Driver Code var m = 10087887; var n = 2983097899; var Final = parseInt( Math.abs(fib(n) - fib(m - 1))); document.write(Final % 10); // This code is contributed by Rajput-Ji</script>", "e": 31600, "s": 30517, "text": null }, { "code": null, "e": 31602, "s": 31600, "text": "5" }, { "code": null, "e": 31689, "s": 31604, "text": "Time Complexity: O(1), because this code runs almost 60 times for any input number. " }, { "code": null, "e": 31712, "s": 31689, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 31723, "s": 31712, "text": "bgangwar59" }, { "code": null, "e": 31740, "s": 31723, "text": "abhaysingh290895" }, { "code": null, "e": 31750, "s": 31740, "text": "Code_Mech" }, { "code": null, "e": 31761, "s": 31750, "text": "shobitham1" }, { "code": null, "e": 31771, "s": 31761, "text": "Rajput-Ji" }, { "code": null, "e": 31781, "s": 31771, "text": "subham348" }, { "code": null, "e": 31791, "s": 31781, "text": "Fibonacci" }, { "code": null, "e": 31798, "s": 31791, "text": "series" }, { "code": null, "e": 31809, "s": 31798, "text": "series-sum" }, { "code": null, "e": 31822, "s": 31809, "text": "Mathematical" }, { "code": null, "e": 31840, "s": 31822, "text": "Pattern Searching" }, { "code": null, "e": 31856, "s": 31840, "text": "Write From Home" }, { "code": null, "e": 31869, "s": 31856, "text": "Mathematical" }, { "code": null, "e": 31876, "s": 31869, "text": "series" }, { "code": null, "e": 31886, "s": 31876, "text": "Fibonacci" }, { "code": null, "e": 31904, "s": 31886, "text": "Pattern Searching" }, { "code": null, "e": 32002, "s": 31904, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32011, "s": 32002, "text": "Comments" }, { "code": null, "e": 32024, "s": 32011, "text": "Old Comments" }, { "code": null, "e": 32069, "s": 32024, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 32101, "s": 32069, "text": "Check if a number is Palindrome" }, { "code": null, "e": 32145, "s": 32101, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 32179, "s": 32145, "text": "Program to add two binary strings" }, { "code": null, "e": 32204, "s": 32179, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 32240, "s": 32204, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 32283, "s": 32240, "text": "Rabin-Karp Algorithm for Pattern Searching" }, { "code": null, "e": 32325, "s": 32283, "text": "Check if a string is substring of another" }, { "code": null, "e": 32363, "s": 32325, "text": "Naive algorithm for Pattern Searching" } ]
VueJS - Rendering
In this chapter, we will learn about conditional rendering and list rendering. In conditional rendering, we will discuss about using if, if-else, if-else-if, show, etc. In list rendering, we will discuss how to use for loop. Let’s get started and work on a example first to explain the details for conditional rendering. With conditional rendering, we want to output only when the condition is met and the conditional check is done with the help of if, if-else, if-else-if, show, etc. Example <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "databinding"> <button v-on:click = "showdata" v-bind:style = "styleobj">Click Me</button> <span style = "font-size:25px;"><b>{{show}}</b></span> <h1 v-if = "show">This is h1 tag</h1> <h2>This is h2 tag</h2> </div> <script type = "text/javascript"> var vm = new Vue({ el: '#databinding', data: { show: true, styleobj: { backgroundColor: '#2196F3!important', cursor: 'pointer', padding: '8px 16px', verticalAlign: 'middle', } }, methods : { showdata : function() { this.show = !this.show; } }, }); </script> </body> </html> Output In the above example, we have created a button and two h1 tags with the message. A variable called show is declared and initialized to a value true. It is displayed close to the button. On the click of the button, we are calling a method showdata, which toggles the value of the variable show. This means on the click of the button, the value of the variable show will change from true to false and false to true. We have assigned if to the h1 tag as shown in the following code snippet. <button v-on:click = "showdata" v-bind:style = "styleobj">Click Me</button> <h1 v-if = "show">This is h1 tag</h1> Now what it will do is, it will check the value of the variable show and if its true the h1 tag will be displayed. Click the button and view in the browser, as the value of the show variable changes to false, the h1 tag is not displayed in the browser. It is displayed only when the show variable is true. Following is the display in the browser. If we check in the browser, this is what we get when show is false. The h1 tag is removed from the DOM when the variable show is set to false. This is what we see when the variable is true. The h1 tag is added back to the DOM when the variable show is set to true. In the following example, we have added v-else to the second h1 tag. Example <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "databinding"> <button v-on:click = "showdata" v-bind:style = "styleobj">Click Me</button> <span style = "font-size:25px;"><b>{{show}}</b></span> <h1 v-if = "show">This is h1 tag</h1> <h2 v-else>This is h2 tag</h2> </div> <script type = "text/javascript"> var vm = new Vue({ el: '#databinding', data: { show: true, styleobj: { backgroundColor: '#2196F3!important', cursor: 'pointer', padding: '8px 16px', verticalAlign: 'middle', } }, methods : { showdata : function() { this.show = !this.show; } }, }); </script> </body> </html> v-else is added using the following code snippet. <h1 v-if = "show">This is h1 tag</h1> <h2 v-else>This is h2 tag</h2> Now, if show is true “This is h1 tag” will be displayed, and if false “This is h2 tag” will be displayed. This is what we will get in the browser. The above display is when the show variable is true. Since, we have added v-else, the second statement is not present. Now, when we click the button the show variable will become false and the second statement will be displayed as shown in the following screenshot. v-show behaves same as v-if. It also shows and hides the elements based on the condition assigned to it. The difference between v-if and v-show is that v-if removes the HTML element from the DOM if the condition is false, and adds it back if the condition is true. Whereas v-show hides the element, if the condition is false with display:none. It shows the element back, if the condition is true. Thus, the element is present in the dom always. Example <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "databinding"> <button v-on:click = "showdata" v-bind:style = "styleobj">Click Me</button> <span style = "font-size:25px;"><b>{{show}}</b></span> <h1 v-if = "show">This is h1 tag</h1> <h2 v-else>This is h2 tag</h2> <div v-show = "show"> <b>V-Show:</b> <img src = "images/img.jpg" width = "100" height = "100" /> </div> </div> <script type = "text/javascript"> var vm = new Vue({ el: '#databinding', data: { show: true, styleobj: { backgroundColor: '#2196F3!important', cursor: 'pointer', padding: '8px 16px', verticalAlign: 'middle', } }, methods : { showdata : function() { this.show = !this.show; } }, }); </script> </body> </html> v-show is assigned to the HTML element using the following code snippet. <div v-show = "show"><b>V-Show:</b><img src = "images/img.jpg" width = "100" height = "100" /></div> We have used the same variable show and based on it being true/false, the image is displayed in the browser. Now, since the variable show is true, the image is as displayed in the above screenshot. Let us click the button and see the display. The variable show is false, hence the image is hidden. If we inspect and see the element, the div along with the image is still a part of the DOM with the style property display: none as seen in the above screenshot. Let us now discuss list rendering with v-for directive. Example <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "databinding"> <input type = "text" v-on:keyup.enter = "showinputvalue" v-bind:style = "styleobj" placeholder = "Enter Fruits Names"/> <h1 v-if = "items.length>0">Display Fruits Name</h1> <ul> <li v-for = "a in items">{{a}}</li> </ul> </div> <script type = "text/javascript"> var vm = new Vue({ el: '#databinding', data: { items:[], styleobj: { width: "30%", padding: "12px 20px", margin: "8px 0", boxSizing: "border-box" } }, methods : { showinputvalue : function(event) { this.items.push(event.target.value); } }, }); </script> </body> </html> A variable called items is declared as an array. In methods, there is a method called showinputvalue, which is assigned to the input box that takes the names of the fruits. In the method, the fruits entered inside the textbox are added to the array using the following piece of code. showinputvalue : function(event) { this.items.push(event.target.value); } We have used v-for to display the fruits entered as in the following piece of code. V-for helps to iterate over the values present in the array. <ul> <li v-for = "a in items">{{a}}</li> </ul> To iterate over the array with for loop, we have to use v-for = ”a in items” where a holds the values in the array and will display till all the items are done. Output Following is the output in the browser. On inspecting the items, this is what it shows in the browser. In the DOM, we don’t see any v-for directive to the li element. It displays the DOM without any VueJS directives. If we wish to display the index of the array, it is done using the following code. <html> <head> <title>VueJs Instance</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "databinding"> <input type = "text" v-on:keyup.enter = "showinputvalue" v-bind:style = "styleobj" placeholder = "Enter Fruits Names"/> <h1 v-if = "items.length>0">Display Fruits Name</h1> <ul> <li v-for = "(a, index) in items">{{index}}--{{a}}</li> </ul> </div> <script type = "text/javascript"> var vm = new Vue({ el: '#databinding', data: { items:[], styleobj: { width: "30%", padding: "12px 20px", margin: "8px 0", boxSizing: "border-box" } }, methods : { showinputvalue : function(event) { this.items.push(event.target.value); } }, }); </script> </body> </html> To get the index, we have added one more variable in the bracket as shown in the following piece of code. <li v-for = "(a, index) in items">{{index}}--{{a}}</li> In (a, index), a is the value and index is the key. The browser display will now be as shown in the following screenshot. Thus, with the help of index any specific values can be displayed. Print Add Notes Bookmark this page
[ { "code": null, "e": 2161, "s": 1936, "text": "In this chapter, we will learn about conditional rendering and list rendering. In conditional rendering, we will discuss about using if, if-else, if-else-if, show, etc. In list rendering, we will discuss how to use for loop." }, { "code": null, "e": 2421, "s": 2161, "text": "Let’s get started and work on a example first to explain the details for conditional rendering. With conditional rendering, we want to output only when the condition is met and the conditional check is done with the help of if, if-else, if-else-if, show, etc." }, { "code": null, "e": 2429, "s": 2421, "text": "Example" }, { "code": null, "e": 3409, "s": 2429, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <button v-on:click = \"showdata\" v-bind:style = \"styleobj\">Click Me</button>\n <span style = \"font-size:25px;\"><b>{{show}}</b></span>\n <h1 v-if = \"show\">This is h1 tag</h1>\n <h2>This is h2 tag</h2>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n show: true,\n styleobj: {\n backgroundColor: '#2196F3!important',\n cursor: 'pointer',\n padding: '8px 16px',\n verticalAlign: 'middle',\n }\n },\n methods : {\n showdata : function() {\n this.show = !this.show;\n }\n },\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 3416, "s": 3409, "text": "Output" }, { "code": null, "e": 3497, "s": 3416, "text": "In the above example, we have created a button and two h1 tags with the message." }, { "code": null, "e": 3830, "s": 3497, "text": "A variable called show is declared and initialized to a value true. It is displayed close to the button. On the click of the button, we are calling a method showdata, which toggles the value of the variable show. This means on the click of the button, the value of the variable show will change from true to false and false to true." }, { "code": null, "e": 3904, "s": 3830, "text": "We have assigned if to the h1 tag as shown in the following code snippet." }, { "code": null, "e": 4018, "s": 3904, "text": "<button v-on:click = \"showdata\" v-bind:style = \"styleobj\">Click Me</button>\n<h1 v-if = \"show\">This is h1 tag</h1>" }, { "code": null, "e": 4324, "s": 4018, "text": "Now what it will do is, it will check the value of the variable show and if its true the h1 tag will be displayed. Click the button and view in the browser, as the value of the show variable changes to false, the h1 tag is not displayed in the browser. It is displayed only when the show variable is true." }, { "code": null, "e": 4365, "s": 4324, "text": "Following is the display in the browser." }, { "code": null, "e": 4433, "s": 4365, "text": "If we check in the browser, this is what we get when show is false." }, { "code": null, "e": 4508, "s": 4433, "text": "The h1 tag is removed from the DOM when the variable show is set to false." }, { "code": null, "e": 4630, "s": 4508, "text": "This is what we see when the variable is true.\nThe h1 tag is added back to the DOM when the variable show is set to true." }, { "code": null, "e": 4699, "s": 4630, "text": "In the following example, we have added v-else to the second h1 tag." }, { "code": null, "e": 4707, "s": 4699, "text": "Example" }, { "code": null, "e": 5694, "s": 4707, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <button v-on:click = \"showdata\" v-bind:style = \"styleobj\">Click Me</button>\n <span style = \"font-size:25px;\"><b>{{show}}</b></span>\n <h1 v-if = \"show\">This is h1 tag</h1>\n <h2 v-else>This is h2 tag</h2>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n show: true,\n styleobj: {\n backgroundColor: '#2196F3!important',\n cursor: 'pointer',\n padding: '8px 16px',\n verticalAlign: 'middle',\n }\n },\n methods : {\n showdata : function() {\n this.show = !this.show;\n }\n },\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 5744, "s": 5694, "text": "v-else is added using the following code snippet." }, { "code": null, "e": 5813, "s": 5744, "text": "<h1 v-if = \"show\">This is h1 tag</h1>\n<h2 v-else>This is h2 tag</h2>" }, { "code": null, "e": 5960, "s": 5813, "text": "Now, if show is true “This is h1 tag” will be displayed, and if false “This is h2 tag” will be displayed. This is what we will get in the browser." }, { "code": null, "e": 6226, "s": 5960, "text": "The above display is when the show variable is true. Since, we have added v-else, the second statement is not present. Now, when we click the button the show variable will become false and the second statement will be displayed as shown in the following screenshot." }, { "code": null, "e": 6671, "s": 6226, "text": "v-show behaves same as v-if. It also shows and hides the elements based on the condition assigned to it. The difference between v-if and v-show is that v-if removes the HTML element from the DOM if the condition is false, and adds it back if the condition is true. Whereas v-show hides the element, if the condition is false with display:none. It shows the element back, if the condition is true. Thus, the element is present in the dom always." }, { "code": null, "e": 6679, "s": 6671, "text": "Example" }, { "code": null, "e": 7812, "s": 6679, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <button v-on:click = \"showdata\" v-bind:style = \"styleobj\">Click Me</button>\n <span style = \"font-size:25px;\"><b>{{show}}</b></span>\n <h1 v-if = \"show\">This is h1 tag</h1>\n <h2 v-else>This is h2 tag</h2>\n <div v-show = \"show\">\n <b>V-Show:</b>\n <img src = \"images/img.jpg\" width = \"100\" height = \"100\" />\n </div>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n show: true,\n styleobj: {\n backgroundColor: '#2196F3!important',\n cursor: 'pointer',\n padding: '8px 16px',\n verticalAlign: 'middle',\n }\n },\n methods : {\n showdata : function() {\n this.show = !this.show;\n }\n },\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 7885, "s": 7812, "text": "v-show is assigned to the HTML element using the following code snippet." }, { "code": null, "e": 7986, "s": 7885, "text": "<div v-show = \"show\"><b>V-Show:</b><img src = \"images/img.jpg\" width = \"100\" height = \"100\" /></div>" }, { "code": null, "e": 8095, "s": 7986, "text": "We have used the same variable show and based on it being true/false, the image is displayed in the browser." }, { "code": null, "e": 8229, "s": 8095, "text": "Now, since the variable show is true, the image is as displayed in the above screenshot. Let us click the button and see the display." }, { "code": null, "e": 8446, "s": 8229, "text": "The variable show is false, hence the image is hidden. If we inspect and see the element, the div along with the image is still a part of the DOM with the style property display: none as seen in the above screenshot." }, { "code": null, "e": 8502, "s": 8446, "text": "Let us now discuss list rendering with v-for directive." }, { "code": null, "e": 8510, "s": 8502, "text": "Example" }, { "code": null, "e": 9537, "s": 8510, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <input type = \"text\" v-on:keyup.enter = \"showinputvalue\"\n v-bind:style = \"styleobj\" placeholder = \"Enter Fruits Names\"/>\n <h1 v-if = \"items.length>0\">Display Fruits Name</h1>\n <ul>\n <li v-for = \"a in items\">{{a}}</li>\n </ul>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n items:[],\n styleobj: {\n width: \"30%\",\n padding: \"12px 20px\",\n margin: \"8px 0\",\n boxSizing: \"border-box\"\n }\n },\n methods : {\n showinputvalue : function(event) {\n this.items.push(event.target.value);\n }\n },\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 9821, "s": 9537, "text": "A variable called items is declared as an array. In methods, there is a method called showinputvalue, which is assigned to the input box that takes the names of the fruits. In the method, the fruits entered inside the textbox are added to the array using the following piece of code." }, { "code": null, "e": 9898, "s": 9821, "text": "showinputvalue : function(event) {\n this.items.push(event.target.value);\n}" }, { "code": null, "e": 10043, "s": 9898, "text": "We have used v-for to display the fruits entered as in the following piece of code. V-for helps to iterate over the values present in the array." }, { "code": null, "e": 10093, "s": 10043, "text": "<ul>\n <li v-for = \"a in items\">{{a}}</li>\n</ul>" }, { "code": null, "e": 10254, "s": 10093, "text": "To iterate over the array with for loop, we have to use v-for = ”a in items” where a holds the values in the array and will display till all the items are done." }, { "code": null, "e": 10261, "s": 10254, "text": "Output" }, { "code": null, "e": 10301, "s": 10261, "text": "Following is the output in the browser." }, { "code": null, "e": 10478, "s": 10301, "text": "On inspecting the items, this is what it shows in the browser. In the DOM, we don’t see any v-for directive to the li element. It displays the DOM without any VueJS directives." }, { "code": null, "e": 10561, "s": 10478, "text": "If we wish to display the index of the array, it is done using the following code." }, { "code": null, "e": 11608, "s": 10561, "text": "<html>\n <head>\n <title>VueJs Instance</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"databinding\">\n <input type = \"text\" v-on:keyup.enter = \"showinputvalue\"\n v-bind:style = \"styleobj\" placeholder = \"Enter Fruits Names\"/>\n <h1 v-if = \"items.length>0\">Display Fruits Name</h1>\n <ul>\n <li v-for = \"(a, index) in items\">{{index}}--{{a}}</li>\n </ul>\n </div>\n <script type = \"text/javascript\">\n var vm = new Vue({\n el: '#databinding',\n data: {\n items:[],\n styleobj: {\n width: \"30%\",\n padding: \"12px 20px\",\n margin: \"8px 0\",\n boxSizing: \"border-box\"\n }\n },\n methods : {\n showinputvalue : function(event) {\n this.items.push(event.target.value);\n }\n },\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 11714, "s": 11608, "text": "To get the index, we have added one more variable in the bracket as shown in the following piece of code." }, { "code": null, "e": 11770, "s": 11714, "text": "<li v-for = \"(a, index) in items\">{{index}}--{{a}}</li>" }, { "code": null, "e": 11959, "s": 11770, "text": "In (a, index), a is the value and index is the key. The browser display will now be as shown in the following screenshot. Thus, with the help of index any specific values can be displayed." }, { "code": null, "e": 11966, "s": 11959, "text": " Print" }, { "code": null, "e": 11977, "s": 11966, "text": " Add Notes" } ]
How to concatenate two strings in C#?
To concatenate two strings, use the String.Concat method. Let’s say you want to concatenate two strings in C#, str1 and str2, then add it as arguments in the Concat method − string str3 = string.Concat(str1, str2); The following is the example − Live Demo using System; class Program { static void Main() { string str1 = "Brad"; string str2 = "Pitt"; // Concat strings string str3 = string.Concat(str1, str2); Console.WriteLine(str3); } } BradPitt
[ { "code": null, "e": 1120, "s": 1062, "text": "To concatenate two strings, use the String.Concat method." }, { "code": null, "e": 1236, "s": 1120, "text": "Let’s say you want to concatenate two strings in C#, str1 and str2, then add it as arguments in the Concat method −" }, { "code": null, "e": 1277, "s": 1236, "text": "string str3 = string.Concat(str1, str2);" }, { "code": null, "e": 1308, "s": 1277, "text": "The following is the example −" }, { "code": null, "e": 1319, "s": 1308, "text": " Live Demo" }, { "code": null, "e": 1541, "s": 1319, "text": "using System;\n\nclass Program {\n static void Main() {\n\n string str1 = \"Brad\";\n string str2 = \"Pitt\";\n\n // Concat strings\n string str3 = string.Concat(str1, str2);\n Console.WriteLine(str3);\n }\n}" }, { "code": null, "e": 1550, "s": 1541, "text": "BradPitt" } ]
Can interfaces have constructors in Java?
No, interfaces can’t have constructors for the following reasons − All the members of an interface are abstract, and since a constructor cannot be abstract. Still, if you try to write a constructor within an interface it will generate a compile time error. public interface InterfaceTest { InterfaceTest(){ } public abstract void display(); public abstract void show(); } C:\Sample>javac InterfaceTest.java InterfaceTest.java:2: error: <dentifier> expected public InterfaceTest(){ ^ 1 error
[ { "code": null, "e": 1129, "s": 1062, "text": "No, interfaces can’t have constructors for the following reasons −" }, { "code": null, "e": 1219, "s": 1129, "text": "All the members of an interface are abstract, and since a constructor cannot be abstract." }, { "code": null, "e": 1319, "s": 1219, "text": "Still, if you try to write a constructor within an interface it will generate a compile time error." }, { "code": null, "e": 1446, "s": 1319, "text": "public interface InterfaceTest {\n InterfaceTest(){\n }\n public abstract void display();\n public abstract void show();\n}" }, { "code": null, "e": 1587, "s": 1446, "text": "C:\\Sample>javac InterfaceTest.java\nInterfaceTest.java:2: error: <dentifier> expected\npublic InterfaceTest(){\n ^\n1 error\n" } ]
Change grid interval and specify tick labels in Matplotlib
Using plt.figure() method, we can create a figure and thereafter, we can create an axis. Using set_xticks and set_yticks, we can change the ticks format and ax.grid could help to specify the grid interval. Create a new figure, or activate an existing figure, using fig = plt.figure() method. Create a new figure, or activate an existing figure, using fig = plt.figure() method. Add an `~.axes.Axes` to the figure as part of a subplot arrangement, where nrow = 1, ncols = 1 and index = 1. Add an `~.axes.Axes` to the figure as part of a subplot arrangement, where nrow = 1, ncols = 1 and index = 1. Get or set the current tick locations and labels of the X-axis. Get or set the current tick locations and labels of the X-axis. Get or set the current tick locations and labels of the X-axis. With minor = True, Grid. Get or set the current tick locations and labels of the X-axis. With minor = True, Grid. Get or set the current tick locations and labels of the Y-axis. Get or set the current tick locations and labels of the Y-axis. Get or set the current tick locations and labels of the Y-axis. With minor = True, Grid. Get or set the current tick locations and labels of the Y-axis. With minor = True, Grid. Lay out a grid in current line style, using grid() method. Lay out a grid in current line style, using grid() method. To show the figure we can use the plt.show() method. To show the figure we can use the plt.show() method. import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(1, 1, 1) major_tick = [10, 20, 30, 40, 50] minor_tick = [5, 15, 25, 35, 45] ax.set_xticks(major_tick) # Grid ax.set_xticks(minor_tick, minor=True) ax.set_yticks(major_tick) # Grid ax.set_yticks(minor_tick, minor=True) ax.grid(which='both') ax.grid(which='minor', alpha=1) ax.grid(which='major', alpha=2) plt.show()
[ { "code": null, "e": 1268, "s": 1062, "text": "Using plt.figure() method, we can create a figure and thereafter, we can create an axis. Using set_xticks and set_yticks, we can change the ticks format and ax.grid could help to specify the grid interval." }, { "code": null, "e": 1354, "s": 1268, "text": "Create a new figure, or activate an existing figure, using fig = plt.figure() method." }, { "code": null, "e": 1440, "s": 1354, "text": "Create a new figure, or activate an existing figure, using fig = plt.figure() method." }, { "code": null, "e": 1550, "s": 1440, "text": "Add an `~.axes.Axes` to the figure as part of a subplot arrangement, where nrow = 1, ncols = 1 and index = 1." }, { "code": null, "e": 1660, "s": 1550, "text": "Add an `~.axes.Axes` to the figure as part of a subplot arrangement, where nrow = 1, ncols = 1 and index = 1." }, { "code": null, "e": 1724, "s": 1660, "text": "Get or set the current tick locations and labels of the X-axis." }, { "code": null, "e": 1788, "s": 1724, "text": "Get or set the current tick locations and labels of the X-axis." }, { "code": null, "e": 1877, "s": 1788, "text": "Get or set the current tick locations and labels of the X-axis. With minor = True, Grid." }, { "code": null, "e": 1966, "s": 1877, "text": "Get or set the current tick locations and labels of the X-axis. With minor = True, Grid." }, { "code": null, "e": 2030, "s": 1966, "text": "Get or set the current tick locations and labels of the Y-axis." }, { "code": null, "e": 2094, "s": 2030, "text": "Get or set the current tick locations and labels of the Y-axis." }, { "code": null, "e": 2183, "s": 2094, "text": "Get or set the current tick locations and labels of the Y-axis. With minor = True, Grid." }, { "code": null, "e": 2272, "s": 2183, "text": "Get or set the current tick locations and labels of the Y-axis. With minor = True, Grid." }, { "code": null, "e": 2331, "s": 2272, "text": "Lay out a grid in current line style, using grid() method." }, { "code": null, "e": 2390, "s": 2331, "text": "Lay out a grid in current line style, using grid() method." }, { "code": null, "e": 2443, "s": 2390, "text": "To show the figure we can use the plt.show() method." }, { "code": null, "e": 2496, "s": 2443, "text": "To show the figure we can use the plt.show() method." }, { "code": null, "e": 2887, "s": 2496, "text": "import matplotlib.pyplot as plt\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nmajor_tick = [10, 20, 30, 40, 50]\nminor_tick = [5, 15, 25, 35, 45]\nax.set_xticks(major_tick) # Grid\nax.set_xticks(minor_tick, minor=True)\nax.set_yticks(major_tick) # Grid\nax.set_yticks(minor_tick, minor=True)\n\nax.grid(which='both')\n\nax.grid(which='minor', alpha=1)\nax.grid(which='major', alpha=2)\n\nplt.show()" } ]
How to access nested data in Python | by Jacob Toftgaard Rasmussen | Towards Data Science
In this short guide you will learn how you can access data that is deeply nested in python’s lists and dictionary data structures. You might have met the following errors while working with JSON data: KeyError: 0TypeError: list indices must be integers or slices, not str If that is the case then this guide is for you, as you will learn some tricks for dealing with these situations. This guide includes the following: Introduction Basics of indexing dictionaries and lists An example of how you would extract nested data An example of how you would extract nested data with a loop A tip for avoiding program crash (Use it wisely) Goodbyes A dictionary contains key and value pairs. a_dict = {"key": "value"} To get the value of the corresponding key you put the key in square brackets after the dictionary variable, like this: your_dictionary[key] hero_dict = {'Clark': 'Superman','Bruce': 'Batman','You_reading_this_guide': 'Pythonman'}print(hero_dict['Clark'])-> Superman Similarly, to access the values of a list you also use square brackets, but instead of a providing a key you use the index of the item you want, like this: your_list[index] The index must be an integer. hero_list = ['Superman', 'Batman', 'Pythonman']print(hero_list[0])-> Superman Take a look at the JSON data below. It comes from an apartment building and has some data about its address and the apartments inside it. Apartment number 1 and 2 have two residents. The data is available here:https://github.com/JacobToftgaardRasmussen/medium_nested_data Now imagine that you want to get the name of the first person in the first apartment. You would write the following: import jsonwith open("data.json") as f: data = json.load(f)first_resident = data["ApartmentBuilding"]["Apartments"][0]["Residents"][0]["Name"] First you import the json module, this will allow you to transform the data into a python dictionary via the json.load() function. Next you open the data file and save the data to the variable data. If you look in the picture of the data above, you can see that the first key is “ApartmentBuilding”. By writing the name of the key in square brackets we get the corresponding value which is another dictionary. This dictionary has two key value pairs: “Address” “Apartments” In this example we wanted to access the first resident in the first apartment, so you put “Apartments” in square brackets to get the corresponding value, which is a list. We follow this with a 0 in square brackets to access the first index of the list. Next comes “Residents”, followed by another 0 to access the first person, and finally “Name” to get the name of that person. I encourage you to try it out yourself! Either use the data I have provided or make your own data structure and try to traverse it. Now imagine that you are not only interested in the name of the first resident, but instead you would like the names of all the residents. If you just look at the data you can quickly see that it would be the following list: [Bob, Alice, Jane, William]. This is how you can get that result with code: import jsonwith open("data.json") as f: data = json.load(f)resident_names = []apartments = data['ApartmentBuilding']['Apartments']for apartment in apartments: residents = apartment['Residents'] for resident in residents: name = resident['Name'] resident_names.append(name)print(resident_names)-> ['Bob', 'Alice', 'Jane', 'William'] Alright lets walk through it one line at a time. Just like before we start by importing the json module and the data. This time however, we also initialize the empty list resident_names to store the names in. If you look in the data you will see that the first two levels of the data are dictionaries, therefore we use the the keys “ApartmentBuilding” and “Apartments” in square brackets and save the corresponding value in the variable apartments. This variable is now a list containing all the apartments. Since we want to go through all of the apartments we use a for loop. In each iteration of the loop we save that apartment’s list of residents in the variable residents. Then we can again use a loop to go through all the residents of that current apartment. This is called a double loop, and it can be a bit tricky to wrap your head around the first time you see it, but don’t worry you will learn it with time and practice. Alright, you are now looping through all the apartments one by one, and for each apartment you are looping through it’s residents. Now the final step is to add each resident’s name to the resident_names list. We access the name of the resident with the key “Name” and save the value to the variable name. Then we use the append() method and pass it name. Append() is standard on all python lists, and it simply adds whatever you give to it at the end of the list. If you print the list, you will see the result as we expected it. Great job! You now know how to access nested data! Sometimes when working with dictionaries you cannot be sure that a key is actually present in the dictionary. Imagine that in the above data one of the resident’s age is not recorded in the data. For some unknown reason the “Age” key is not the dictionary with “Bob”. And lets say that now you want to get a list of the ages of all the residents in all the apartments. The code would look exactly like in the example before, except we would be using the key “Age” in the final step instead of “Name”. But this will not work... The script will crash...And you will be met with: File "c:\Users\your_directory\nested_data.py", line 25, in <module> resident_ages.append(resident['Age'])KeyError: 'Age' The dreaded KeyError... But this is actually very valuable information, as the error message tells us that the key ‘Age’ does not exist in the dictionary where we are looking for it. However, we would still like the program to keep running, and to find all the other names. Maybe we would also like the script to add a default value whenever an age is not found. This can be done with the get() function which is standard on python dictionaries. Take a look at the code below I have made the changes bold: import jsonwith open("data_bob_no_age.json") as f: data = json.load(f)resident_ages = []apartments = data['ApartmentBuilding']['Apartments']for apartment in apartments: residents = apartment['Residents'] for resident in residents: age = resident.get('Age', 'N/A') resident_ages.append(age)print(resident_ages)-> ['N/A', 42, 43, 42] The get() functions takes two arguments, the key you are expecting and a default value that will be returned instead if the key is not present. As you can see, the resident_ages list contains the value ‘N/A’ at the first index, and the script did not crash. Using get() can be useful in situations like the one above, but remember to use it cautiously, as you will not receive an error message that could have been important for your understanding of the data structure. Thank you for reading this article, I hope that you learned something useful!If you have any questions or comments feel free to reach out to me.Remember that the code for this article can be found here. Keep learning! — Jacob Toftgaard Rasmussen
[ { "code": null, "e": 302, "s": 171, "text": "In this short guide you will learn how you can access data that is deeply nested in python’s lists and dictionary data structures." }, { "code": null, "e": 372, "s": 302, "text": "You might have met the following errors while working with JSON data:" }, { "code": null, "e": 443, "s": 372, "text": "KeyError: 0TypeError: list indices must be integers or slices, not str" }, { "code": null, "e": 556, "s": 443, "text": "If that is the case then this guide is for you, as you will learn some tricks for dealing with these situations." }, { "code": null, "e": 591, "s": 556, "text": "This guide includes the following:" }, { "code": null, "e": 604, "s": 591, "text": "Introduction" }, { "code": null, "e": 646, "s": 604, "text": "Basics of indexing dictionaries and lists" }, { "code": null, "e": 694, "s": 646, "text": "An example of how you would extract nested data" }, { "code": null, "e": 754, "s": 694, "text": "An example of how you would extract nested data with a loop" }, { "code": null, "e": 803, "s": 754, "text": "A tip for avoiding program crash (Use it wisely)" }, { "code": null, "e": 812, "s": 803, "text": "Goodbyes" }, { "code": null, "e": 855, "s": 812, "text": "A dictionary contains key and value pairs." }, { "code": null, "e": 881, "s": 855, "text": "a_dict = {\"key\": \"value\"}" }, { "code": null, "e": 1000, "s": 881, "text": "To get the value of the corresponding key you put the key in square brackets after the dictionary variable, like this:" }, { "code": null, "e": 1021, "s": 1000, "text": "your_dictionary[key]" }, { "code": null, "e": 1147, "s": 1021, "text": "hero_dict = {'Clark': 'Superman','Bruce': 'Batman','You_reading_this_guide': 'Pythonman'}print(hero_dict['Clark'])-> Superman" }, { "code": null, "e": 1303, "s": 1147, "text": "Similarly, to access the values of a list you also use square brackets, but instead of a providing a key you use the index of the item you want, like this:" }, { "code": null, "e": 1320, "s": 1303, "text": "your_list[index]" }, { "code": null, "e": 1350, "s": 1320, "text": "The index must be an integer." }, { "code": null, "e": 1428, "s": 1350, "text": "hero_list = ['Superman', 'Batman', 'Pythonman']print(hero_list[0])-> Superman" }, { "code": null, "e": 1611, "s": 1428, "text": "Take a look at the JSON data below. It comes from an apartment building and has some data about its address and the apartments inside it. Apartment number 1 and 2 have two residents." }, { "code": null, "e": 1700, "s": 1611, "text": "The data is available here:https://github.com/JacobToftgaardRasmussen/medium_nested_data" }, { "code": null, "e": 1817, "s": 1700, "text": "Now imagine that you want to get the name of the first person in the first apartment. You would write the following:" }, { "code": null, "e": 1963, "s": 1817, "text": "import jsonwith open(\"data.json\") as f: data = json.load(f)first_resident = data[\"ApartmentBuilding\"][\"Apartments\"][0][\"Residents\"][0][\"Name\"]" }, { "code": null, "e": 2414, "s": 1963, "text": "First you import the json module, this will allow you to transform the data into a python dictionary via the json.load() function. Next you open the data file and save the data to the variable data. If you look in the picture of the data above, you can see that the first key is “ApartmentBuilding”. By writing the name of the key in square brackets we get the corresponding value which is another dictionary. This dictionary has two key value pairs:" }, { "code": null, "e": 2424, "s": 2414, "text": "“Address”" }, { "code": null, "e": 2437, "s": 2424, "text": "“Apartments”" }, { "code": null, "e": 2815, "s": 2437, "text": "In this example we wanted to access the first resident in the first apartment, so you put “Apartments” in square brackets to get the corresponding value, which is a list. We follow this with a 0 in square brackets to access the first index of the list. Next comes “Residents”, followed by another 0 to access the first person, and finally “Name” to get the name of that person." }, { "code": null, "e": 2947, "s": 2815, "text": "I encourage you to try it out yourself! Either use the data I have provided or make your own data structure and try to traverse it." }, { "code": null, "e": 3248, "s": 2947, "text": "Now imagine that you are not only interested in the name of the first resident, but instead you would like the names of all the residents. If you just look at the data you can quickly see that it would be the following list: [Bob, Alice, Jane, William]. This is how you can get that result with code:" }, { "code": null, "e": 3610, "s": 3248, "text": "import jsonwith open(\"data.json\") as f: data = json.load(f)resident_names = []apartments = data['ApartmentBuilding']['Apartments']for apartment in apartments: residents = apartment['Residents'] for resident in residents: name = resident['Name'] resident_names.append(name)print(resident_names)-> ['Bob', 'Alice', 'Jane', 'William']" }, { "code": null, "e": 4118, "s": 3610, "text": "Alright lets walk through it one line at a time. Just like before we start by importing the json module and the data. This time however, we also initialize the empty list resident_names to store the names in. If you look in the data you will see that the first two levels of the data are dictionaries, therefore we use the the keys “ApartmentBuilding” and “Apartments” in square brackets and save the corresponding value in the variable apartments. This variable is now a list containing all the apartments." }, { "code": null, "e": 4542, "s": 4118, "text": "Since we want to go through all of the apartments we use a for loop. In each iteration of the loop we save that apartment’s list of residents in the variable residents. Then we can again use a loop to go through all the residents of that current apartment. This is called a double loop, and it can be a bit tricky to wrap your head around the first time you see it, but don’t worry you will learn it with time and practice." }, { "code": null, "e": 5072, "s": 4542, "text": "Alright, you are now looping through all the apartments one by one, and for each apartment you are looping through it’s residents. Now the final step is to add each resident’s name to the resident_names list. We access the name of the resident with the key “Name” and save the value to the variable name. Then we use the append() method and pass it name. Append() is standard on all python lists, and it simply adds whatever you give to it at the end of the list. If you print the list, you will see the result as we expected it." }, { "code": null, "e": 5123, "s": 5072, "text": "Great job! You now know how to access nested data!" }, { "code": null, "e": 5391, "s": 5123, "text": "Sometimes when working with dictionaries you cannot be sure that a key is actually present in the dictionary. Imagine that in the above data one of the resident’s age is not recorded in the data. For some unknown reason the “Age” key is not the dictionary with “Bob”." }, { "code": null, "e": 5624, "s": 5391, "text": "And lets say that now you want to get a list of the ages of all the residents in all the apartments. The code would look exactly like in the example before, except we would be using the key “Age” in the final step instead of “Name”." }, { "code": null, "e": 5700, "s": 5624, "text": "But this will not work... The script will crash...And you will be met with:" }, { "code": null, "e": 5824, "s": 5700, "text": "File \"c:\\Users\\your_directory\\nested_data.py\", line 25, in <module> resident_ages.append(resident['Age'])KeyError: 'Age'" }, { "code": null, "e": 5848, "s": 5824, "text": "The dreaded KeyError..." }, { "code": null, "e": 6330, "s": 5848, "text": "But this is actually very valuable information, as the error message tells us that the key ‘Age’ does not exist in the dictionary where we are looking for it. However, we would still like the program to keep running, and to find all the other names. Maybe we would also like the script to add a default value whenever an age is not found. This can be done with the get() function which is standard on python dictionaries. Take a look at the code below I have made the changes bold:" }, { "code": null, "e": 6685, "s": 6330, "text": "import jsonwith open(\"data_bob_no_age.json\") as f: data = json.load(f)resident_ages = []apartments = data['ApartmentBuilding']['Apartments']for apartment in apartments: residents = apartment['Residents'] for resident in residents: age = resident.get('Age', 'N/A') resident_ages.append(age)print(resident_ages)-> ['N/A', 42, 43, 42]" }, { "code": null, "e": 6943, "s": 6685, "text": "The get() functions takes two arguments, the key you are expecting and a default value that will be returned instead if the key is not present. As you can see, the resident_ages list contains the value ‘N/A’ at the first index, and the script did not crash." }, { "code": null, "e": 7156, "s": 6943, "text": "Using get() can be useful in situations like the one above, but remember to use it cautiously, as you will not receive an error message that could have been important for your understanding of the data structure." }, { "code": null, "e": 7359, "s": 7156, "text": "Thank you for reading this article, I hope that you learned something useful!If you have any questions or comments feel free to reach out to me.Remember that the code for this article can be found here." } ]
PHP: Remove object from array
The unset function can be used to remove array object from a specific index in PHP − Live Demo $index = 2; $objectarray = array( 0 => array('label' => 'abc', 'value' => 'n23'), 1 => array('label' => 'def', 'value' => '2n13'), 2 => array('label' => 'abcdef', 'value' => 'n214'), 3 => array('label' => 'defabc', 'value' => '03n2') ); var_dump($objectarray); foreach ($objectarray as $key => $object) { if ($key == $index) { unset($objectarray[$index]); } } var_dump($objectarray); This will produce the following output − array(4) { [0]=> array(2) { ["label"]=> string(3) "abc" ["value"]=> string(3) "n23" } [1]=> array(2) { ["label"]=> string(3) "def" ["value"]=> string(4) "2n13" } [2]=> array(2) { ["label"]=> string(6) "abcdef" ["value"]=> string(5) "n214" } [3]=> array(2) { ["label"]=> string(6) "defabc" ["value"]=> string(5) "03n2" } } array(3) { [0]=> array(2) { ["label"]=> string(3) "abc" ["value"]=> string(3) "n23" } [1]=> array(2) { ["label"]=> string(3) "def" ["value"]=> string(4) "2n13" } [3]=> array(2) { ["label"]=> string(6) "defabc" ["value"]=> string(5) "03n2" } } An array with 4 objects is declared and assigned to variable ‘objectarray’. Here, we wish to remove the object from index 2, that is also declared with variable named ‘index’. The foreach loop is used to traverse through the array and when the index value in the traversal matches the index from where the value needs to be removed, the ‘unset’ function is called on that element and the remaining elements are returned as output.
[ { "code": null, "e": 1147, "s": 1062, "text": "The unset function can be used to remove array object from a specific index in PHP −" }, { "code": null, "e": 1158, "s": 1147, "text": " Live Demo" }, { "code": null, "e": 1566, "s": 1158, "text": "$index = 2;\n$objectarray = array(\n 0 => array('label' => 'abc', 'value' => 'n23'),\n 1 => array('label' => 'def', 'value' => '2n13'),\n 2 => array('label' => 'abcdef', 'value' => 'n214'),\n 3 => array('label' => 'defabc', 'value' => '03n2')\n);\nvar_dump($objectarray);\nforeach ($objectarray as $key => $object) {\n if ($key == $index) {\n unset($objectarray[$index]);\n }\n}\nvar_dump($objectarray);" }, { "code": null, "e": 1607, "s": 1566, "text": "This will produce the following output −" }, { "code": null, "e": 2177, "s": 1607, "text": "array(4) { [0]=> array(2) { [\"label\"]=> string(3) \"abc\" [\"value\"]=> string(3) \"n23\" } [1]=> array(2) \n{ [\"label\"]=> string(3) \"def\" [\"value\"]=> string(4) \"2n13\" } [2]=> array(2) { [\"label\"]=> string(6) \n\"abcdef\" [\"value\"]=> string(5) \"n214\" } [3]=> array(2) { [\"label\"]=> string(6) \"defabc\" [\"value\"]=> \nstring(5) \"03n2\" } } array(3) { [0]=> array(2) { [\"label\"]=> string(3) \"abc\" [\"value\"]=> string(3) \n\"n23\" } [1]=> array(2) { [\"label\"]=> string(3) \"def\" [\"value\"]=> string(4) \"2n13\" } [3]=> array(2) \n{ [\"label\"]=> string(6) \"defabc\" [\"value\"]=> string(5) \"03n2\" } }" }, { "code": null, "e": 2608, "s": 2177, "text": "An array with 4 objects is declared and assigned to variable ‘objectarray’. Here, we wish to remove the object from index 2, that is also declared with variable named ‘index’. The foreach loop is used to traverse through the array and when the index value in the traversal matches the index from where the value needs to be removed, the ‘unset’ function is called on that element and the remaining elements are returned as output." } ]
Metasploit - Import Data
Metasploit is a powerful security framework which allows you to import scan results from other third-party tools. You can import NMAP scan results in XML format that you might have created earlier. Metasploit also allows you to import scan results from Nessus, which is a vulnerability scanner. Let’s see how it works. At first, perform an NMAP scan and save the result in XML format on your desktop, as shown in the following screenshot. Next, open Metasploit or Armitage to import the scan results. Thereafter, use the following command to import all the host. Msf > db_import "path of xml file" The following screenshot shows what the output will look like. To test whether the import file was correct or not, we can run specific commands on these two hosts and see how they respond. For example, in our case, we have listed all the hosts having the port 445 running on them. Print Add Notes Bookmark this page
[ { "code": null, "e": 2466, "s": 2171, "text": "Metasploit is a powerful security framework which allows you to import scan results from other third-party tools. You can import NMAP scan results in XML format that you might have created earlier. Metasploit also allows you to import scan results from Nessus, which is a vulnerability scanner." }, { "code": null, "e": 2610, "s": 2466, "text": "Let’s see how it works. At first, perform an NMAP scan and save the result in XML format on your desktop, as shown in the following screenshot." }, { "code": null, "e": 2734, "s": 2610, "text": "Next, open Metasploit or Armitage to import the scan results. Thereafter, use the following command to import all the host." }, { "code": null, "e": 2772, "s": 2734, "text": "Msf > db_import \"path of xml file\" \n" }, { "code": null, "e": 2835, "s": 2772, "text": "The following screenshot shows what the output will look like." }, { "code": null, "e": 3053, "s": 2835, "text": "To test whether the import file was correct or not, we can run specific commands on these two hosts and see how they respond. For example, in our case, we have listed all the hosts having the port 445 running on them." }, { "code": null, "e": 3060, "s": 3053, "text": " Print" }, { "code": null, "e": 3071, "s": 3060, "text": " Add Notes" } ]
How To Clone Tables in SQL. Learn how to create a clone of your... | by Oyetoke Tobi Emmanuel | Towards Data Science
In database operations, there may be a time when you need to clone or duplicate an existing table to a new table due to their similarities in columns and attributes either for performing a test without affecting the original table or other personal reasons. I bumped in this situation whereby I need to create a new set of tables for a new feature we are integrating. This table has quite a lot of columns and very similar to an existing table handling another set of similar data of a particular feature. Since this existing table and the new one are quite similar, my quick solution to this is to clone the existing table to create the new table. In SQL it's quite easy to do this as you can easily run a couple of commands to best suit your cloning needs. In this article, I will be showing you how to duplicate and clone existing tables in SQL. The first method is called Simple Cloning and as its name implies it create a table from another table without taking into account any column attributes and indexes. CREATE TABLE new_table SELECT * FROM original_table; So if I have a table called users, I can easily create another table called adminUsers without caring about the users table column attributes and indexes. The below SQL command creates a simple copy of the users table. CREATE TABLE adminUsers SELECT * FROM users; Use this in order to quickly clone any table that only includes the structure and data of the original table. Shallow cloning is mostly used to create a copy of an existing table data structure and column attributes without the data being copied. This will only create an empty table base on the structure of the original table. CREATE TABLE new_table LIKE original_table; The following command would create an empty table base on the original table. CREATE TABLE adminUsers LIKE users; Use this if you only want the data structure and column attributes of the original table Deep cloning is quite different from Simple Cloning and similar to Shallow cloning but with data, and as its name implies it creates a deep copy of the original table. This means the new table gets to have all the attributes of each column and indexes of the existing table. This quite useful if you want to maintain the indexes and attributes of the existing table. To achieve this, we’ll have to create an empty table base on the structure and attributes of the original table, then select data from the original table and insert into the new table. CREATE TABLE new_table LIKE original_table;INSERT INTO new_table SELECT * FROM original_table; To easily clone our original and also have its data copied: CREATE TABLE adminUsers LIKE users;INSERT INTO adminUsers SELECT * FROM adminUsers; Another cool thing now is, let's say you don't want all the data from the existing table and only want some data, based on some conditions then fine-tuning your SELECT queries are your best bet. For instance, we have users with userType="admin" in our users table and we want to only copy those users only to our new table, you can easily do that like below: INSERT INTO adminUsers SELECT * FROM adminUsers where userType="admin"; Cool right? I know. If you are new to SQL below are some useful resources:
[ { "code": null, "e": 430, "s": 172, "text": "In database operations, there may be a time when you need to clone or duplicate an existing table to a new table due to their similarities in columns and attributes either for performing a test without affecting the original table or other personal reasons." }, { "code": null, "e": 678, "s": 430, "text": "I bumped in this situation whereby I need to create a new set of tables for a new feature we are integrating. This table has quite a lot of columns and very similar to an existing table handling another set of similar data of a particular feature." }, { "code": null, "e": 821, "s": 678, "text": "Since this existing table and the new one are quite similar, my quick solution to this is to clone the existing table to create the new table." }, { "code": null, "e": 931, "s": 821, "text": "In SQL it's quite easy to do this as you can easily run a couple of commands to best suit your cloning needs." }, { "code": null, "e": 1021, "s": 931, "text": "In this article, I will be showing you how to duplicate and clone existing tables in SQL." }, { "code": null, "e": 1187, "s": 1021, "text": "The first method is called Simple Cloning and as its name implies it create a table from another table without taking into account any column attributes and indexes." }, { "code": null, "e": 1240, "s": 1187, "text": "CREATE TABLE new_table SELECT * FROM original_table;" }, { "code": null, "e": 1395, "s": 1240, "text": "So if I have a table called users, I can easily create another table called adminUsers without caring about the users table column attributes and indexes." }, { "code": null, "e": 1459, "s": 1395, "text": "The below SQL command creates a simple copy of the users table." }, { "code": null, "e": 1504, "s": 1459, "text": "CREATE TABLE adminUsers SELECT * FROM users;" }, { "code": null, "e": 1614, "s": 1504, "text": "Use this in order to quickly clone any table that only includes the structure and data of the original table." }, { "code": null, "e": 1833, "s": 1614, "text": "Shallow cloning is mostly used to create a copy of an existing table data structure and column attributes without the data being copied. This will only create an empty table base on the structure of the original table." }, { "code": null, "e": 1877, "s": 1833, "text": "CREATE TABLE new_table LIKE original_table;" }, { "code": null, "e": 1955, "s": 1877, "text": "The following command would create an empty table base on the original table." }, { "code": null, "e": 1991, "s": 1955, "text": "CREATE TABLE adminUsers LIKE users;" }, { "code": null, "e": 2080, "s": 1991, "text": "Use this if you only want the data structure and column attributes of the original table" }, { "code": null, "e": 2248, "s": 2080, "text": "Deep cloning is quite different from Simple Cloning and similar to Shallow cloning but with data, and as its name implies it creates a deep copy of the original table." }, { "code": null, "e": 2447, "s": 2248, "text": "This means the new table gets to have all the attributes of each column and indexes of the existing table. This quite useful if you want to maintain the indexes and attributes of the existing table." }, { "code": null, "e": 2632, "s": 2447, "text": "To achieve this, we’ll have to create an empty table base on the structure and attributes of the original table, then select data from the original table and insert into the new table." }, { "code": null, "e": 2727, "s": 2632, "text": "CREATE TABLE new_table LIKE original_table;INSERT INTO new_table SELECT * FROM original_table;" }, { "code": null, "e": 2787, "s": 2727, "text": "To easily clone our original and also have its data copied:" }, { "code": null, "e": 2871, "s": 2787, "text": "CREATE TABLE adminUsers LIKE users;INSERT INTO adminUsers SELECT * FROM adminUsers;" }, { "code": null, "e": 3066, "s": 2871, "text": "Another cool thing now is, let's say you don't want all the data from the existing table and only want some data, based on some conditions then fine-tuning your SELECT queries are your best bet." }, { "code": null, "e": 3230, "s": 3066, "text": "For instance, we have users with userType=\"admin\" in our users table and we want to only copy those users only to our new table, you can easily do that like below:" }, { "code": null, "e": 3302, "s": 3230, "text": "INSERT INTO adminUsers SELECT * FROM adminUsers where userType=\"admin\";" }, { "code": null, "e": 3322, "s": 3302, "text": "Cool right? I know." } ]
Text Justification in C++
Suppose we have an array of words and a width maxWidth, we have to format the text such that each line has exactly maxWidth number of characters and is fully justified. We should pack our words in a greedy approach; so that is, pack as many words as we can in each line. We will pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Here extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, empty slots on the left will be assigned more spaces than the slots on the right. For the final line of text, it should be left justified and no extra space is inserted between words. So if the input is like To solve this, we will follow these steps − create one array called result create one array called result for i in range 0 to size of a, update i by jwidth := 0for j in range i to size of a and width + size of a[j] + j – i <= b,width := width + size of a[j]space := 1, extra := 0if j – 1 != 1 and j != size of a, thenspace := (b - width) / j – i – 1extra := (b - width) mod (j – i – 1)line := a[i]for k in range i + 1 to jconcatenate space number of blank-spaces with lineif extra > 0, then concatenate space with linedecrease extra by 1line := concatenate a[k] with linex := size of lineline := concatenate (b - x) number of spaces with lineinsert line into result for i in range 0 to size of a, update i by j width := 0 width := 0 for j in range i to size of a and width + size of a[j] + j – i <= b,width := width + size of a[j] for j in range i to size of a and width + size of a[j] + j – i <= b, width := width + size of a[j] width := width + size of a[j] space := 1, extra := 0 space := 1, extra := 0 if j – 1 != 1 and j != size of a, thenspace := (b - width) / j – i – 1extra := (b - width) mod (j – i – 1) if j – 1 != 1 and j != size of a, then space := (b - width) / j – i – 1 space := (b - width) / j – i – 1 extra := (b - width) mod (j – i – 1) extra := (b - width) mod (j – i – 1) line := a[i] line := a[i] for k in range i + 1 to jconcatenate space number of blank-spaces with lineif extra > 0, then concatenate space with linedecrease extra by 1line := concatenate a[k] with line for k in range i + 1 to j concatenate space number of blank-spaces with line concatenate space number of blank-spaces with line if extra > 0, then concatenate space with line if extra > 0, then concatenate space with line decrease extra by 1 decrease extra by 1 line := concatenate a[k] with line line := concatenate a[k] with line x := size of line x := size of line line := concatenate (b - x) number of spaces with line line := concatenate (b - x) number of spaces with line insert line into result insert line into result return res return res Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } void print_vector(vector<vector<auto>> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << "["; for(int j = 0; j <v[i].size(); j++){ cout << v[i][j] << ", "; } cout << "],"; } cout << "]"<<endl; } class Solution { public: vector<string> fullJustify(vector<string> &a, int b) { vector <string> result; int i, j; for(i = 0; i < a.size(); i = j){ int width = 0; for(j = i; j < a.size() && width + a[j].size() + j - i <= b; j++){ width += a[j].size(); } int space = 1; int extra = 0; if(j - i != 1 && j != a.size()){ space = (b - width) / (j - i - 1); extra = (b - width) % (j - i - 1); } string line(a[i]); for(int k = i + 1; k < j; k++){ line += string(space, ' '); if(extra-- > 0){ line += " "; } line += a[k]; } int x = line.size(); line += string(b - x, ' '); result.push_back(line); } return result; } }; main(){ vector<string> v = {"I", "love", "coding.", "here", "we", "will", "write", "some", "program"}; Solution ob; print_vector(ob.fullJustify(v, 16)); } ["I", "love", "coding.", "here", "we", "will", "write", "some", "program"] 16 [I love coding., here we will, write some, program , ]
[ { "code": null, "e": 1428, "s": 1062, "text": "Suppose we have an array of words and a width maxWidth, we have to format the text such that each line has exactly maxWidth number of characters and is fully justified. We should pack our words in a greedy approach; so that is, pack as many words as we can in each line. We will pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters." }, { "code": null, "e": 1759, "s": 1428, "text": "Here extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, empty slots on the left will be assigned more spaces than the slots on the right. For the final line of text, it should be left justified and no extra space is inserted between words." }, { "code": null, "e": 1783, "s": 1759, "text": "So if the input is like" }, { "code": null, "e": 1827, "s": 1783, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1858, "s": 1827, "text": "create one array called result" }, { "code": null, "e": 1889, "s": 1858, "text": "create one array called result" }, { "code": null, "e": 2449, "s": 1889, "text": "for i in range 0 to size of a, update i by jwidth := 0for j in range i to size of a and width + size of a[j] + j – i <= b,width := width + size of a[j]space := 1, extra := 0if j – 1 != 1 and j != size of a, thenspace := (b - width) / j – i – 1extra := (b - width) mod (j – i – 1)line := a[i]for k in range i + 1 to jconcatenate space number of blank-spaces with lineif extra > 0, then concatenate space with linedecrease extra by 1line := concatenate a[k] with linex := size of lineline := concatenate (b - x) number of spaces with lineinsert line into result" }, { "code": null, "e": 2494, "s": 2449, "text": "for i in range 0 to size of a, update i by j" }, { "code": null, "e": 2505, "s": 2494, "text": "width := 0" }, { "code": null, "e": 2516, "s": 2505, "text": "width := 0" }, { "code": null, "e": 2614, "s": 2516, "text": "for j in range i to size of a and width + size of a[j] + j – i <= b,width := width + size of a[j]" }, { "code": null, "e": 2683, "s": 2614, "text": "for j in range i to size of a and width + size of a[j] + j – i <= b," }, { "code": null, "e": 2713, "s": 2683, "text": "width := width + size of a[j]" }, { "code": null, "e": 2743, "s": 2713, "text": "width := width + size of a[j]" }, { "code": null, "e": 2766, "s": 2743, "text": "space := 1, extra := 0" }, { "code": null, "e": 2789, "s": 2766, "text": "space := 1, extra := 0" }, { "code": null, "e": 2896, "s": 2789, "text": "if j – 1 != 1 and j != size of a, thenspace := (b - width) / j – i – 1extra := (b - width) mod (j – i – 1)" }, { "code": null, "e": 2935, "s": 2896, "text": "if j – 1 != 1 and j != size of a, then" }, { "code": null, "e": 2968, "s": 2935, "text": "space := (b - width) / j – i – 1" }, { "code": null, "e": 3001, "s": 2968, "text": "space := (b - width) / j – i – 1" }, { "code": null, "e": 3038, "s": 3001, "text": "extra := (b - width) mod (j – i – 1)" }, { "code": null, "e": 3075, "s": 3038, "text": "extra := (b - width) mod (j – i – 1)" }, { "code": null, "e": 3088, "s": 3075, "text": "line := a[i]" }, { "code": null, "e": 3101, "s": 3088, "text": "line := a[i]" }, { "code": null, "e": 3276, "s": 3101, "text": "for k in range i + 1 to jconcatenate space number of blank-spaces with lineif extra > 0, then concatenate space with linedecrease extra by 1line := concatenate a[k] with line" }, { "code": null, "e": 3302, "s": 3276, "text": "for k in range i + 1 to j" }, { "code": null, "e": 3353, "s": 3302, "text": "concatenate space number of blank-spaces with line" }, { "code": null, "e": 3404, "s": 3353, "text": "concatenate space number of blank-spaces with line" }, { "code": null, "e": 3451, "s": 3404, "text": "if extra > 0, then concatenate space with line" }, { "code": null, "e": 3498, "s": 3451, "text": "if extra > 0, then concatenate space with line" }, { "code": null, "e": 3518, "s": 3498, "text": "decrease extra by 1" }, { "code": null, "e": 3538, "s": 3518, "text": "decrease extra by 1" }, { "code": null, "e": 3573, "s": 3538, "text": "line := concatenate a[k] with line" }, { "code": null, "e": 3608, "s": 3573, "text": "line := concatenate a[k] with line" }, { "code": null, "e": 3626, "s": 3608, "text": "x := size of line" }, { "code": null, "e": 3644, "s": 3626, "text": "x := size of line" }, { "code": null, "e": 3699, "s": 3644, "text": "line := concatenate (b - x) number of spaces with line" }, { "code": null, "e": 3754, "s": 3699, "text": "line := concatenate (b - x) number of spaces with line" }, { "code": null, "e": 3778, "s": 3754, "text": "insert line into result" }, { "code": null, "e": 3802, "s": 3778, "text": "insert line into result" }, { "code": null, "e": 3813, "s": 3802, "text": "return res" }, { "code": null, "e": 3824, "s": 3813, "text": "return res" }, { "code": null, "e": 3894, "s": 3824, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3905, "s": 3894, "text": " Live Demo" }, { "code": null, "e": 5372, "s": 3905, "text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print_vector(vector<auto> v){\n cout << \"[\";\n for(int i = 0; i<v.size(); i++){\n cout << v[i] << \", \";\n }\n cout << \"]\"<<endl;\n}\nvoid print_vector(vector<vector<auto>> v){\n cout << \"[\";\n for(int i = 0; i<v.size(); i++){\n cout << \"[\";\n for(int j = 0; j <v[i].size(); j++){\n cout << v[i][j] << \", \";\n }\n cout << \"],\";\n }\n cout << \"]\"<<endl;\n}\nclass Solution {\n public:\n vector<string> fullJustify(vector<string> &a, int b) {\n vector <string> result;\n int i, j;\n for(i = 0; i < a.size(); i = j){\n int width = 0;\n for(j = i; j < a.size() && width + a[j].size() + j - i <= b; j++){\n width += a[j].size();\n }\n int space = 1;\n int extra = 0;\n if(j - i != 1 && j != a.size()){\n space = (b - width) / (j - i - 1);\n extra = (b - width) % (j - i - 1);\n }\n string line(a[i]);\n for(int k = i + 1; k < j; k++){\n line += string(space, ' ');\n if(extra-- > 0){\n line += \" \";\n }\n line += a[k];\n }\n int x = line.size();\n line += string(b - x, ' ');\n result.push_back(line);\n }\n return result;\n }\n};\nmain(){\n vector<string> v = {\"I\", \"love\", \"coding.\", \"here\", \"we\", \"will\", \"write\", \"some\", \"program\"};\n Solution ob;\n print_vector(ob.fullJustify(v, 16));\n}" }, { "code": null, "e": 5450, "s": 5372, "text": "[\"I\", \"love\", \"coding.\", \"here\", \"we\", \"will\", \"write\", \"some\", \"program\"]\n16" }, { "code": null, "e": 5505, "s": 5450, "text": "[I love coding.,\nhere we will,\nwrite some,\nprogram ,\n]" } ]
How to find the critical value of F for regression anova in R?
To find the critical value of F for regression anova in R, we can follow the below steps − First of all, create a data frame. Then, create the regression model. After that, find the critical value of F statistic using qf function. Let's create a data frame as shown below − Live Demo > x<-rpois(20,2) > y<-rpois(20,5) > df<-data.frame(x,y) > df On executing, the above script generates the below output(this output will vary on your system due to randomization) − x y 1 5 5 2 0 9 3 1 3 4 3 5 5 2 5 6 2 4 7 3 6 8 4 6 9 2 5 10 0 6 11 5 8 12 1 7 13 3 2 14 0 4 15 1 4 16 2 4 17 1 7 18 2 8 19 2 6 20 1 4 Using lm function to create the regression model between y and x and anova function to find the ANOVA table − Live Demo > x<-rpois(20,2) > y<-rpois(20,5) > df<-data.frame(x,y) > RegM<-lm(y~x,data=df) > RegM_ANOVA<-anova(RegM) > RegM_ANOVA Analysis of Variance Table Response: y Df Sum Sq Mean Sq F value Pr(>F) x 1 0.024 0.0238 0.0071 0.934 Residuals 18 60.776 3.3765 Using qf function to find the critical value of F for regression anova − Live Demo > x<-rpois(20,2) > y<-rpois(20,5) > df<-data.frame(x,y) > RegM<-lm(y~x,data=df) > RegM_ANOVA<-anova(RegM) > qf(1-0.05,RegM_ANOVA[1,1],RegM_ANOVA[2,1]) [1] 4.413873
[ { "code": null, "e": 1153, "s": 1062, "text": "To find the critical value of F for regression anova in R, we can follow the below steps −" }, { "code": null, "e": 1188, "s": 1153, "text": "First of all, create a data frame." }, { "code": null, "e": 1223, "s": 1188, "text": "Then, create the regression model." }, { "code": null, "e": 1293, "s": 1223, "text": "After that, find the critical value of F statistic using qf function." }, { "code": null, "e": 1336, "s": 1293, "text": "Let's create a data frame as shown below −" }, { "code": null, "e": 1347, "s": 1336, "text": " Live Demo" }, { "code": null, "e": 1408, "s": 1347, "text": "> x<-rpois(20,2)\n> y<-rpois(20,5)\n> df<-data.frame(x,y)\n> df" }, { "code": null, "e": 1527, "s": 1408, "text": "On executing, the above script generates the below output(this output will vary on your system due to randomization) −" }, { "code": null, "e": 1674, "s": 1527, "text": " x y\n1 5 5\n2 0 9\n3 1 3\n4 3 5\n5 2 5\n6 2 4\n7 3 6\n8 4 6\n9 2 5\n10 0 6\n11 5 8\n12 1 7\n13 3 2\n14 0 4\n15 1 4\n16 2 4\n17 1 7\n18 2 8\n19 2 6\n20 1 4" }, { "code": null, "e": 1784, "s": 1674, "text": "Using lm function to create the regression model between y and x and anova function to find the ANOVA table −" }, { "code": null, "e": 1795, "s": 1784, "text": " Live Demo" }, { "code": null, "e": 1914, "s": 1795, "text": "> x<-rpois(20,2)\n> y<-rpois(20,5)\n> df<-data.frame(x,y)\n> RegM<-lm(y~x,data=df)\n> RegM_ANOVA<-anova(RegM)\n> RegM_ANOVA" }, { "code": null, "e": 2049, "s": 1914, "text": "Analysis of Variance Table\nResponse: y\n Df Sum Sq Mean Sq F value Pr(>F)\nx 1 0.024 0.0238 0.0071 0.934\nResiduals 18 60.776 3.3765" }, { "code": null, "e": 2122, "s": 2049, "text": "Using qf function to find the critical value of F for regression anova −" }, { "code": null, "e": 2133, "s": 2122, "text": " Live Demo" }, { "code": null, "e": 2284, "s": 2133, "text": "> x<-rpois(20,2)\n> y<-rpois(20,5)\n> df<-data.frame(x,y)\n> RegM<-lm(y~x,data=df)\n> RegM_ANOVA<-anova(RegM)\n> qf(1-0.05,RegM_ANOVA[1,1],RegM_ANOVA[2,1])" }, { "code": null, "e": 2297, "s": 2284, "text": "[1] 4.413873" } ]
What is a Pytest framework?
Pytest is a test framework in python. To install pytest, we need to use the command pip install pytest. After installation, we can verify if python has been installed by the command pytest –version. The version of pytest shall be known. Pytest can be used for creating and executing test cases. It can be used in a wide range of testing API, UI, database, and so on. The test file of pytest has a naming convention that it starts with test_ or ends with _test keyword and every line of code should be inside a method that should have a name starting with test keyword. Also, each method should have a unique name. Syntax def test_f(): print("Tutorialspoint") To run the above code, we need to move to the terminal and use the command py.test. However, this will not give many details from an execution point of view. To get information on execution we should use the command py.test –v. Here v stands for verbose. In order to print the console logs, we need to use the command py.test –v –s. Again, if we want to run tests from a specific pytest file, the command is py.test <filename> -v. The advantages of pytest framework are listed below − Pytest is capable of executing multiple test cases simultaneously, thereby reducing the execution duration. Pytest is capable of executing multiple test cases simultaneously, thereby reducing the execution duration. Pytest is capable of skipping a test method from a group of test methods during execution. Pytest is capable of skipping a test method from a group of test methods during execution. Pytest is free and does not have to license costs. Pytest is free and does not have to license costs. Pytest is quick and easy to learn. Pytest is quick and easy to learn. Pytest can choose to run a particular test method or all the test methods of a particular test file based on conditions. Pytest can choose to run a particular test method or all the test methods of a particular test file based on conditions. Pytest is capable of skipping a few test methods out of all the test methods during test execution. Pytest is capable of skipping a few test methods out of all the test methods during test execution. Pytest can be used to test a wide range of applications on API, database, and so on. Pytest can be used to test a wide range of applications on API, database, and so on.
[ { "code": null, "e": 1299, "s": 1062, "text": "Pytest is a test framework in python. To install pytest, we need to use the command pip install pytest. After installation, we can verify if python has been installed by the command pytest –version. The version of pytest shall be\nknown." }, { "code": null, "e": 1676, "s": 1299, "text": "Pytest can be used for creating and executing test cases. It can be used in a wide range of testing API, UI, database, and so on. The test file of pytest has a naming convention that it starts with test_ or ends with _test keyword and every line of\ncode should be inside a method that should have a name starting with test keyword. Also, each method should have a unique name." }, { "code": null, "e": 1683, "s": 1676, "text": "Syntax" }, { "code": null, "e": 1724, "s": 1683, "text": "def test_f():\n print(\"Tutorialspoint\")" }, { "code": null, "e": 1979, "s": 1724, "text": "To run the above code, we need to move to the terminal and use the command py.test. However, this will not give many details from an execution point of view. To get information on execution we should use the command py.test –v. Here v\nstands for verbose." }, { "code": null, "e": 2155, "s": 1979, "text": "In order to print the console logs, we need to use the command py.test –v –s. Again, if we want to run tests from a specific pytest file, the command is py.test\n<filename> -v." }, { "code": null, "e": 2209, "s": 2155, "text": "The advantages of pytest framework are listed below −" }, { "code": null, "e": 2317, "s": 2209, "text": "Pytest is capable of executing multiple test cases simultaneously, thereby reducing the execution duration." }, { "code": null, "e": 2425, "s": 2317, "text": "Pytest is capable of executing multiple test cases simultaneously, thereby reducing the execution duration." }, { "code": null, "e": 2516, "s": 2425, "text": "Pytest is capable of skipping a test method from a group of test methods during execution." }, { "code": null, "e": 2607, "s": 2516, "text": "Pytest is capable of skipping a test method from a group of test methods during execution." }, { "code": null, "e": 2658, "s": 2607, "text": "Pytest is free and does not have to license costs." }, { "code": null, "e": 2709, "s": 2658, "text": "Pytest is free and does not have to license costs." }, { "code": null, "e": 2744, "s": 2709, "text": "Pytest is quick and easy to learn." }, { "code": null, "e": 2779, "s": 2744, "text": "Pytest is quick and easy to learn." }, { "code": null, "e": 2900, "s": 2779, "text": "Pytest can choose to run a particular test method or all the test methods of a particular test file based on conditions." }, { "code": null, "e": 3021, "s": 2900, "text": "Pytest can choose to run a particular test method or all the test methods of a particular test file based on conditions." }, { "code": null, "e": 3121, "s": 3021, "text": "Pytest is capable of skipping a few test methods out of all the test methods during test execution." }, { "code": null, "e": 3221, "s": 3121, "text": "Pytest is capable of skipping a few test methods out of all the test methods during test execution." }, { "code": null, "e": 3306, "s": 3221, "text": "Pytest can be used to test a wide range of applications on API, database, and so on." }, { "code": null, "e": 3391, "s": 3306, "text": "Pytest can be used to test a wide range of applications on API, database, and so on." } ]
How to Create GUID / UUID in JavaScript?
We can create GUID or UUID in JavaScript using the following methods − To create or generate UUID or GUID in javascript use the following code with Math.Random() function function createUUID() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } Note − This should not be used in production as GUID or UUID generated by Math.Random() may not be unique. We can use npm's uuid module for generation of RFC4122 UUIDS. First install it using − $ npm install uuid Then create a js file(script.js) with the following contents − const uuid = require('uuid') console.log(uuid()) console.log(uuid()) console.log(uuid()) You can run it using the following command − node script.js Examples of created UUIDs − a85a8e6b-348b-4011-a1ec-1e78e9620782 03ea49f8-1d96-4cd0-b279-0684e3eec3a9 7289708e-b17a-477c-8a77-9ab575c4b4d8
[ { "code": null, "e": 1133, "s": 1062, "text": "We can create GUID or UUID in JavaScript using the following methods −" }, { "code": null, "e": 1233, "s": 1133, "text": "To create or generate UUID or GUID in javascript use the following code with Math.Random() function" }, { "code": null, "e": 1449, "s": 1233, "text": "function createUUID() {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n}" }, { "code": null, "e": 1556, "s": 1449, "text": "Note − This should not be used in production as GUID or UUID generated by Math.Random() may not be unique." }, { "code": null, "e": 1643, "s": 1556, "text": "We can use npm's uuid module for generation of RFC4122 UUIDS. First install it using −" }, { "code": null, "e": 1662, "s": 1643, "text": "$ npm install uuid" }, { "code": null, "e": 1725, "s": 1662, "text": "Then create a js file(script.js) with the following contents −" }, { "code": null, "e": 1814, "s": 1725, "text": "const uuid = require('uuid')\nconsole.log(uuid())\nconsole.log(uuid())\nconsole.log(uuid())" }, { "code": null, "e": 1859, "s": 1814, "text": "You can run it using the following command −" }, { "code": null, "e": 1874, "s": 1859, "text": "node script.js" }, { "code": null, "e": 1902, "s": 1874, "text": "Examples of created UUIDs −" }, { "code": null, "e": 2013, "s": 1902, "text": "a85a8e6b-348b-4011-a1ec-1e78e9620782\n03ea49f8-1d96-4cd0-b279-0684e3eec3a9\n7289708e-b17a-477c-8a77-9ab575c4b4d8" } ]
WebDriver click() vs JavaScript click().
We can click a link with the webdriver click and Javascript click. For the Selenium webdriver click of a link we can use link text and partial link text locator. We can use the methods driver.findElement(By.linkText()) and driver.findElement(By.partialLinkText()) to click. The links in an html code are enclosed in an anchor tag. The link text enclosed within the anchor tag is passed as argument to the driver.findElement(By.linkText(<link text>)) method. The partial matching link text enclosed within the anchor tag is passed as argument to the driver.findElement(By.partialLinkText(<partial link text>)) method. Finally to click on the link the click method is used. Let us see the html code of a link having the anchor tag. Code Implementation. import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.By; public class DriverClick{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.tutorialspoint.com/about/about_careers.htm"); // identify link with link text locator driver.findElement(By.linkText("Write for us")).click(); System.out.println("Page title after click: " + driver.getTitle()); } } We can also perform web operations like clicking on a link with Javascript Executor in Selenium. We shall use the executeScript method and pass argument index.click() and webelement to be clicked as arguments to the method. Code Implementation with Javascript executor. import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.By; public class DriverClickJs{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.tutorialspoint.com/about/about_careers.htm"); // identify link WebElement l = driver.findElement(By.linkText("Write for us")); //click link with Javascript Executor JavascriptExecutor j = (JavascriptExecutor) driver; j.executeScript("arguments[0].click();", l); System.out.println("Page title after click: " + driver.getTitle()); } }
[ { "code": null, "e": 1336, "s": 1062, "text": "We can click a link with the webdriver click and Javascript click. For the Selenium webdriver click of a link we can use link text and partial link text locator. We can use the methods driver.findElement(By.linkText()) and driver.findElement(By.partialLinkText()) to click." }, { "code": null, "e": 1734, "s": 1336, "text": "The links in an html code are enclosed in an anchor tag. The link text enclosed within the anchor tag is passed as argument to the driver.findElement(By.linkText(<link text>)) method. The partial matching link text enclosed within the anchor tag is passed as argument to the driver.findElement(By.partialLinkText(<partial link text>)) method. Finally to click on the link the click method is used." }, { "code": null, "e": 1792, "s": 1734, "text": "Let us see the html code of a link having the anchor tag." }, { "code": null, "e": 1813, "s": 1792, "text": "Code Implementation." }, { "code": null, "e": 2458, "s": 1813, "text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.By;\npublic class DriverClick{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n // identify link with link text locator\n driver.findElement(By.linkText(\"Write for us\")).click();\n System.out.println(\"Page title after click: \" + driver.getTitle());\n }\n}" }, { "code": null, "e": 2682, "s": 2458, "text": "We can also perform web operations like clicking on a link with Javascript Executor in Selenium. We shall use the executeScript method and pass argument index.click() and webelement to be clicked as arguments to the method." }, { "code": null, "e": 2728, "s": 2682, "text": "Code Implementation with Javascript executor." }, { "code": null, "e": 3520, "s": 2728, "text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.JavascriptExecutor;\nimport org.openqa.selenium.By;\npublic class DriverClickJs{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n // identify link\n WebElement l = driver.findElement(By.linkText(\"Write for us\"));\n //click link with Javascript Executor\n JavascriptExecutor j = (JavascriptExecutor) driver;\n j.executeScript(\"arguments[0].click();\", l);\n System.out.println(\"Page title after click: \" + driver.getTitle());\n }\n}" } ]
Bayesian Ranking System. Thumbs up/down, stars, ranking with... | by R Andrew Cocks | Towards Data Science
Note: Assumes familiarity with the beta distribution covered earlier. Beyond calculating lottery probabilities or disease likelihoods there are also other applications for Bayes theorem, for example we could build a ranking system. Let’s take a movie ranking website where users vote up/down on movies. Simple ranking schemes like percentage of positive votes or up minus down votes perform poorly. Percentage: 60 up : 40 down — vs — 6 up : 4 down are both 60% up minus down: 100 up : 95 down vs 5 up : 0 down are both +5 What we would like is for more votes to add more information; 60 votes hold more weight than 6 votes. Let’s use the votes as likelihoods in Bayesian inference. Here’s a set of movies A-E with up/down votes and the calculated beta function starting from an uniform beta(1,1) Prior: However the beta distribution is a PDF so we’ll need some algorithm to convert to a scalar for ranking. One way is to find the minimum value of the beta distribution such that we are 95% confident the true value is greater. This can be done by subtracting a number of standard deviations from the mean. Ranking = Mean + z-score × standard deviation For a normal approximation the cumulative density function CDF is 5% at a z-score of -1.64 which you can use in the formula above. However if you have access to the inverse CDF (aka percent point function) of the beta distribution itself you can use it directly: rank = beta.ppf(0.05,a,b) # pythonrank = BETA.INV(0.05,a,b) # Excel, Sheetsrank = qbeta(0.05,a,a) # R Yielding the following results: B 6:1 rank: 0.53A 60:40 rank: 0.52C 6:4 rank: 0.35E 10:20 rank: 0.21D 1:2 rank: 0.10 This separates the high evidence A (60:40) and low evidence C (6:4) movies but isn’t an ideal ranking overall, particularly for D (red) which has very little evidence yet receives the worst ranking. We know that average movies are more common than extremely good or extremely bad movies. We’d prefer a ranking which started with an assumption of average movies and required evidence to move to the extremes. We can incorporate this preference with a Prior in our ranking system having a bias towards average movies, starting with a Prior of Beta(11,11) rather than Beta(1,1). It will now take a number of votes to move away from the Prior and towards the extremes, yielding a better overall ranking: A 60:40 rank: 0.51B 6:1 rank: 0.43C 6:4 rank: 0.39D 1:2 rank: 0.32E 10:20 rank: 0.30 Giving us a final result showing that the low evidence D curve is roughly in the middle while the E curve with significantly more negative evidence now has the lowest rank. This doesn’t only work with a up/down rating, you can extend it to work with a star based system by assigning values into simultaneous up/down votes. Stars (1,2,3,4,5): up (0,0.25,0.5,0.75,1) down (1,0.75,0.5,0.25,0) so if three people each rated a movie 4 stars that’s a total score of: 3 up votes each of 0.75 value = 3×0.75 = 2.253 down votes each of 0.25 value = 3×0.25 = 0.75Beta(3.25,1.75) # Uniform priorBeta(13.25, 11.75) # Prior biased toward average movie assumption We’ve completed a stable ranking system which rewards increasing amounts of evidence and shown how it can be extended to work with star rating systems all thanks to the Reverend Bayes. If you want to try it for yourself the python code below does the ranking and draws the graphs for the biased case.
[ { "code": null, "e": 241, "s": 171, "text": "Note: Assumes familiarity with the beta distribution covered earlier." }, { "code": null, "e": 570, "s": 241, "text": "Beyond calculating lottery probabilities or disease likelihoods there are also other applications for Bayes theorem, for example we could build a ranking system. Let’s take a movie ranking website where users vote up/down on movies. Simple ranking schemes like percentage of positive votes or up minus down votes perform poorly." }, { "code": null, "e": 632, "s": 570, "text": "Percentage: 60 up : 40 down — vs — 6 up : 4 down are both 60%" }, { "code": null, "e": 693, "s": 632, "text": "up minus down: 100 up : 95 down vs 5 up : 0 down are both +5" }, { "code": null, "e": 974, "s": 693, "text": "What we would like is for more votes to add more information; 60 votes hold more weight than 6 votes. Let’s use the votes as likelihoods in Bayesian inference. Here’s a set of movies A-E with up/down votes and the calculated beta function starting from an uniform beta(1,1) Prior:" }, { "code": null, "e": 1277, "s": 974, "text": "However the beta distribution is a PDF so we’ll need some algorithm to convert to a scalar for ranking. One way is to find the minimum value of the beta distribution such that we are 95% confident the true value is greater. This can be done by subtracting a number of standard deviations from the mean." }, { "code": null, "e": 1323, "s": 1277, "text": "Ranking = Mean + z-score × standard deviation" }, { "code": null, "e": 1586, "s": 1323, "text": "For a normal approximation the cumulative density function CDF is 5% at a z-score of -1.64 which you can use in the formula above. However if you have access to the inverse CDF (aka percent point function) of the beta distribution itself you can use it directly:" }, { "code": null, "e": 1688, "s": 1586, "text": "rank = beta.ppf(0.05,a,b) # pythonrank = BETA.INV(0.05,a,b) # Excel, Sheetsrank = qbeta(0.05,a,a) # R" }, { "code": null, "e": 1720, "s": 1688, "text": "Yielding the following results:" }, { "code": null, "e": 1816, "s": 1720, "text": "B 6:1 rank: 0.53A 60:40 rank: 0.52C 6:4 rank: 0.35E 10:20 rank: 0.21D 1:2 rank: 0.10" }, { "code": null, "e": 2516, "s": 1816, "text": "This separates the high evidence A (60:40) and low evidence C (6:4) movies but isn’t an ideal ranking overall, particularly for D (red) which has very little evidence yet receives the worst ranking. We know that average movies are more common than extremely good or extremely bad movies. We’d prefer a ranking which started with an assumption of average movies and required evidence to move to the extremes. We can incorporate this preference with a Prior in our ranking system having a bias towards average movies, starting with a Prior of Beta(11,11) rather than Beta(1,1). It will now take a number of votes to move away from the Prior and towards the extremes, yielding a better overall ranking:" }, { "code": null, "e": 2612, "s": 2516, "text": "A 60:40 rank: 0.51B 6:1 rank: 0.43C 6:4 rank: 0.39D 1:2 rank: 0.32E 10:20 rank: 0.30" }, { "code": null, "e": 2785, "s": 2612, "text": "Giving us a final result showing that the low evidence D curve is roughly in the middle while the E curve with significantly more negative evidence now has the lowest rank." }, { "code": null, "e": 2935, "s": 2785, "text": "This doesn’t only work with a up/down rating, you can extend it to work with a star based system by assigning values into simultaneous up/down votes." }, { "code": null, "e": 3002, "s": 2935, "text": "Stars (1,2,3,4,5): up (0,0.25,0.5,0.75,1) down (1,0.75,0.5,0.25,0)" }, { "code": null, "e": 3073, "s": 3002, "text": "so if three people each rated a movie 4 stars that’s a total score of:" }, { "code": null, "e": 3264, "s": 3073, "text": "3 up votes each of 0.75 value = 3×0.75 = 2.253 down votes each of 0.25 value = 3×0.25 = 0.75Beta(3.25,1.75) # Uniform priorBeta(13.25, 11.75) # Prior biased toward average movie assumption" }, { "code": null, "e": 3449, "s": 3264, "text": "We’ve completed a stable ranking system which rewards increasing amounts of evidence and shown how it can be extended to work with star rating systems all thanks to the Reverend Bayes." } ]
Jackson Annotations - @JsonFilter
@JsonFilter is used to apply filter during serialization/de-serialization like which properties are to be used or not. import java.io.IOException; import java.text.ParseException; import com.fasterxml.jackson.annotation.JsonFilter; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ser.FilterProvider; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; public class JacksonTester { public static void main(String args[]) throws IOException, ParseException { ObjectMapper mapper = new ObjectMapper(); Student student = new Student(1,13, "Mark"); FilterProvider filters = new SimpleFilterProvider() .addFilter( "nameFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name")); String jsonString = mapper.writer(filters) .withDefaultPrettyPrinter() .writeValueAsString(student); System.out.println(jsonString); } } @JsonFilter("nameFilter") class Student { public int id; public int rollNo; public String name; Student(int id, int rollNo, String name) { this.id = id; this.rollNo = rollNo; this.name = name; } } { "name" : "Mark" } Print Add Notes Bookmark this page
[ { "code": null, "e": 2594, "s": 2475, "text": "@JsonFilter is used to apply filter during serialization/de-serialization like which properties are to be used or not." }, { "code": null, "e": 3751, "s": 2594, "text": "import java.io.IOException;\nimport java.text.ParseException;\n\nimport com.fasterxml.jackson.annotation.JsonFilter;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.ser.FilterProvider;\nimport com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;\nimport com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;\n\npublic class JacksonTester {\n public static void main(String args[]) throws IOException, ParseException {\n ObjectMapper mapper = new ObjectMapper(); \n Student student = new Student(1,13, \"Mark\");\n \n FilterProvider filters = new SimpleFilterProvider() .addFilter(\n \"nameFilter\", SimpleBeanPropertyFilter.filterOutAllExcept(\"name\"));\n \n String jsonString = mapper.writer(filters) \n .withDefaultPrettyPrinter()\n .writeValueAsString(student);\n System.out.println(jsonString);\n }\n}\n@JsonFilter(\"nameFilter\")\nclass Student {\n public int id;\n public int rollNo;\n public String name;\n\n Student(int id, int rollNo, String name) {\n this.id = id;\n this.rollNo = rollNo;\n this.name = name;\n } \n}" }, { "code": null, "e": 3775, "s": 3751, "text": "{\n \"name\" : \"Mark\"\n}\n" }, { "code": null, "e": 3782, "s": 3775, "text": " Print" }, { "code": null, "e": 3793, "s": 3782, "text": " Add Notes" } ]
Scraping and Exploring The SP500 with R Part 1 | by Bryant Crocker | Towards Data Science
Today I wanted to walk through a quick example combining scraping, calls to the Yahoo finance api, data joining and simple asset analysis using functional programming and tidy iteration concepts. I would like to identify which SP500 assets had the highest average return over the last 3 months. The making of this chart, asset analysis and answering my question will be covered in the second part of this series. In todays analysis I will be using the R programming language. If you have read any of my posts on Linkedin or Medium in the past, you may have noticed that I usually program in python. In general, I prefer the python programming language because it has simpler syntax, wider adoption and is easier to put into production. R Tidyverse Ecosystem: In the R programming language, there is a set of packages that make up what is called the tidyverse. These packages are mostly maintained by engineers and data scientists at Rstudio and provide a simple, integrated and uniform way to manipulate data in R. The tidyverse centers around the idea of tidy data a term coined by Hadley Wickham to describe data where: each variable is a column each observation (or case) is a row I will make use of several tidyverse libraries todays. In the following chunk I import the libraries that I will be using. # for scrapinglibrary(rvest)# blanket import for core tidyverse packageslibrary(tidyverse)# tidy financial analysis library(tidyquant)# tidy data cleaning functionslibrary(janitor) The next thing that I will do is define a variable with todays date. I then subtract 3 months from todays date. This returns another date object, indicating what day came 3 months before today. I will need this because I want to get the last 3 months of price data for each ticker. # save current system date to a variabletoday <- Sys.Date()# subtract 3 months from the current datedate = today %m+% months(-3)print(date) I’m going to use the tidyquant package to get the financial data for all SP500 tickers. The tidyqunat package’s core function is tq_get(), which can be used to get various information about stocks. If I pass a string containing a ticker name to tq_get(), it will return Open, High, Low, Close or OHLC data. I pass ^GSPC, the SP500’s ticker to the tq_get() function. # pass SP500 ticker ^GSPC to tq_get functionone_ticker = tq_get("^GSPC", from = date)one_ticker %>% head() Theres a few things to note above: tq_get() returns a tidy dataframe the ticker name is not in the dataframe the %>% operator is called a pipe. It passes the object that precedes it as the first argument to the function that follows it. I want OHLC data for all SP500 tickers. In order to do this, I will need a to do a few things: Create a vector of all SP500 tickers Iterate over this vector and call tq_get() on each element of the vector, returning a dataframe for each element in the vector combine all these dataframes into one dataframe Wow! That sounds a little complicated, right? luckily, with R, going about this will be pretty simple. Wikipedia has a table of all 505 SP500 tickers (some companies, like Google, have multiple asset classes) located at this URL: https://en.wikipedia.org/wiki/List_of_S%26P_500_companies To get all the SP500 tickers, we are going to scrape this table, using the rvest package. The rvest package is a simple scraping package in R that is very similar to python’s beautiful soup. In the context of programming, scraping is defined as programmatically collecting human readable content from the internet and webpages. In the code below I scrape the wikipedia table and create a vector of all SP500 tickers: I first assign the wikipedia URL to a variable Read in the html from the URL Select the correct html nodes and extract the html table Make a small change to ticker names because yahoo finance uses a ‘_’ instead of ‘.’ for certain symbol names The hardest part of scraping is figuring out the xpath or css to indicate which html nodes to select. I really don’t know much about html or css, but using Google Chrome I was able to find the correct xpath (more on this below). # get the URL for the wikipedia page with all SP500 symbolsurl <- "https://en.wikipedia.org/wiki/List_of_S%26P_500_companies"# use that URL to scrape the SP500 table using rvesttickers <- url %>% # read the HTML from the webpage read_html() %>% # one way to get table #html_nodes(xpath='//*[@id="mw-content-text"]/div/table[1]') %>% # easier way to get table html_nodes(xpath = '//*[@id="constituents"]') %>% html_table()#create a vector of tickerssp500tickers <- tickers[[1]]sp500tickers = sp500tickers %>% mutate(Symbol = case_when(Symbol == "BRK.B" ~ "BRK-B", Symbol == "BF.B" ~ "BF-B", TRUE ~ as.character(Symbol))) Go to https://en.wikipedia.org/wiki/List_of_S%26P_500_companies right click on webpage, select inspect option Most webpage content is usually in the body of an html document. We’ll expand that section. That will look like this: Looking at the webpage, I can see the table that I want is right below the first h2 header: After navigating around the page structure I found the first h2 header and the table I wanted below it I can click on the table, right click and copy the xpath that is needed to scrape the table xpath = //*[@id=”constituents”], this is what was passed to html_nodes html_nodes(xpath = '//*[@id="constituents"]' Iterating refers to programmatically repeating a step or sets of steps, a set number of times or until a condition is meant. Typically, when we iterate in any programming language, we use a loop, typically a for loop. I will need to iterate over each element in the vector of SP500 tickers and pass it to the function tq_get(). I could do this with a for loop, but using the purrr package is a better idea. Loops in R are slow and hard to read. The purrr package provides a suite of functions for iteration and functional programming that integrate well with the rest of the tidyverse. The core function in purrr in map(). Most programming languages (including my favorite one python) have a map function that serves to apply a function to all elements of an object. Functional Programming is a programming paradigm in which functions, as opposed to classes, build the structure and logic of programs. For loops are typically avoided in functional programming. Instead, functions are mapped or applied to lists or other objects. As Hadley Wickham stated perfectly in his Advanced R book: “It’s hard to describe exactly what a functional style is, but generally I think it means decomposing a big problem into smaller pieces, then solving each piece with a function or combination of functions. When using a functional style, you strive to decompose components of the problem into isolated functions that operate independently. Each function taken by itself is simple and straightforward to understand; complexity is handled by composing functions in various ways.” Let’s look at the difference between iteration in purrr and a for loop with an example. Both of these operations are roughly equivalent: # get a sequence of the numbers 1 to 5numbers = seq(1:5)print('for loop')# for loop for (i in numbers){ print(i)}print('purrr :)')# purr functional programming approachlist = map(numbers, print) A few things to note: both the for loop and map function do an operation for each element in the vector the map function returns a nested list where each entry is the result of the function called inside of it for one of the entries in the object that being iterated over. I assign this to a variable list to avoid it from printing. Using purrr’s map function is only one line and less code Using purrr’s map function is easier to read First I need to write a function to iterate over or apply to each element of the vector. I cannot simply use tq_get() with map() because it does not return the ticker name as a column of the dataframe. In order to get the ticker with the dataframe, I will use the mutate() function from dplyr to create a new column with the ticker name. get_symbols = function(ticker = "AAPL"){ df = tq_get(ticker, from = date) %>% mutate(symbol = rep(ticker, length(date)))} I then use this function in conjunction with map() to iterate over the list of all symbols. This returns a nested list containing a dataframe for each ticker. I use the dplyr bind_rows() function to bind the dataframes together row-wise, to create one dataframe with all the SP500 tickers. #create the dataframe of SP500 data by interating over our list of symbols and call our get symbols function each time#the map function accomplishes thistickers_df = map(symbols, get_symbols) %>% bind_rows() I also want this dataframe to contain the information from the wikipedia table, most importantly, the name of the company. This can be achieved by joining the two dataframes by the symbol. tickers_df = tickers_df %>% # left join with wikipedia data left_join(sp500tickers, by = c('symbol' = 'Symbol')) %>% # make names R compatible clean_names() %>% # keep only the columns we need select(date:security, gics_sector, gics_sub_industry) After joining the data we should do a quick sanity check to make sure that we have all 505 SP500 tickers tickers_df %>% # select just the symbol columnselect(symbol)%>% # get the distinct valuesdistinct()%>% # count the distinct values count() %>% # we can use select to rename columns select("Total Number of Tickers" = n) Finally, we can inspect the first few rows of the dataframe, to confirm we have gotten the data we want: tickers_df %>% head() Perfect! Exactly what we expected. Wrapping up: In this first blog post we have: Learned about the basics of the tidyverse ecosystem and tidyquant Learned about the basics of tidy iteration and functional programming Learned how to leverage rvest and chrome to scrape data from wikipedia Learned how to move from reading in a single asset to the whole SP500 In the next post: I will answer my original question: Which SP500 assets had the highest average return over the last 3 months? A few things to note: You can obtain a list of all SP500 stocks much more easily with tq_index(“SP500"). This function does require the XLConnect library. I currently am having issues getting that library to import and run on my local machine. tq_get() actually accepts lists of tickers, so using map() isn’t necessary I intentionally wrote the code this way, to demonstrate the described concepts Disclaimer: In college, I did a project with SP500 data and python. It is against class policy to share this project. While what I am doing here is somewhat similar, I am using a completely different programming language and answering a completely different question. Given my previous statement, I assert that this is not a violation of that courses policy. I intentionally used the R programming language as opposed to python to completely avoid any issues and to respect my former professors wishes. The Code can be found here This is another great source on scraping that helped a bit when writing the article. https://medium.com/@kyleake/wikipedia-data-scraping-with-r-rvest-in-action-3c419db9af2dhttps://medium.com/@kyleake/wikipedia-data-scraping-with-r-rvest-in-action-3c419db9af2d Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
[ { "code": null, "e": 367, "s": 171, "text": "Today I wanted to walk through a quick example combining scraping, calls to the Yahoo finance api, data joining and simple asset analysis using functional programming and tidy iteration concepts." }, { "code": null, "e": 466, "s": 367, "text": "I would like to identify which SP500 assets had the highest average return over the last 3 months." }, { "code": null, "e": 584, "s": 466, "text": "The making of this chart, asset analysis and answering my question will be covered in the second part of this series." }, { "code": null, "e": 907, "s": 584, "text": "In todays analysis I will be using the R programming language. If you have read any of my posts on Linkedin or Medium in the past, you may have noticed that I usually program in python. In general, I prefer the python programming language because it has simpler syntax, wider adoption and is easier to put into production." }, { "code": null, "e": 930, "s": 907, "text": "R Tidyverse Ecosystem:" }, { "code": null, "e": 1293, "s": 930, "text": "In the R programming language, there is a set of packages that make up what is called the tidyverse. These packages are mostly maintained by engineers and data scientists at Rstudio and provide a simple, integrated and uniform way to manipulate data in R. The tidyverse centers around the idea of tidy data a term coined by Hadley Wickham to describe data where:" }, { "code": null, "e": 1319, "s": 1293, "text": "each variable is a column" }, { "code": null, "e": 1355, "s": 1319, "text": "each observation (or case) is a row" }, { "code": null, "e": 1478, "s": 1355, "text": "I will make use of several tidyverse libraries todays. In the following chunk I import the libraries that I will be using." }, { "code": null, "e": 1659, "s": 1478, "text": "# for scrapinglibrary(rvest)# blanket import for core tidyverse packageslibrary(tidyverse)# tidy financial analysis library(tidyquant)# tidy data cleaning functionslibrary(janitor)" }, { "code": null, "e": 1941, "s": 1659, "text": "The next thing that I will do is define a variable with todays date. I then subtract 3 months from todays date. This returns another date object, indicating what day came 3 months before today. I will need this because I want to get the last 3 months of price data for each ticker." }, { "code": null, "e": 2081, "s": 1941, "text": "# save current system date to a variabletoday <- Sys.Date()# subtract 3 months from the current datedate = today %m+% months(-3)print(date)" }, { "code": null, "e": 2447, "s": 2081, "text": "I’m going to use the tidyquant package to get the financial data for all SP500 tickers. The tidyqunat package’s core function is tq_get(), which can be used to get various information about stocks. If I pass a string containing a ticker name to tq_get(), it will return Open, High, Low, Close or OHLC data. I pass ^GSPC, the SP500’s ticker to the tq_get() function." }, { "code": null, "e": 2556, "s": 2447, "text": "# pass SP500 ticker ^GSPC to tq_get functionone_ticker = tq_get(\"^GSPC\", from = date)one_ticker %>% head()" }, { "code": null, "e": 2591, "s": 2556, "text": "Theres a few things to note above:" }, { "code": null, "e": 2625, "s": 2591, "text": "tq_get() returns a tidy dataframe" }, { "code": null, "e": 2665, "s": 2625, "text": "the ticker name is not in the dataframe" }, { "code": null, "e": 2793, "s": 2665, "text": "the %>% operator is called a pipe. It passes the object that precedes it as the first argument to the function that follows it." }, { "code": null, "e": 2888, "s": 2793, "text": "I want OHLC data for all SP500 tickers. In order to do this, I will need a to do a few things:" }, { "code": null, "e": 2925, "s": 2888, "text": "Create a vector of all SP500 tickers" }, { "code": null, "e": 3052, "s": 2925, "text": "Iterate over this vector and call tq_get() on each element of the vector, returning a dataframe for each element in the vector" }, { "code": null, "e": 3100, "s": 3052, "text": "combine all these dataframes into one dataframe" }, { "code": null, "e": 3330, "s": 3100, "text": "Wow! That sounds a little complicated, right? luckily, with R, going about this will be pretty simple. Wikipedia has a table of all 505 SP500 tickers (some companies, like Google, have multiple asset classes) located at this URL:" }, { "code": null, "e": 3388, "s": 3330, "text": "https://en.wikipedia.org/wiki/List_of_S%26P_500_companies" }, { "code": null, "e": 3716, "s": 3388, "text": "To get all the SP500 tickers, we are going to scrape this table, using the rvest package. The rvest package is a simple scraping package in R that is very similar to python’s beautiful soup. In the context of programming, scraping is defined as programmatically collecting human readable content from the internet and webpages." }, { "code": null, "e": 3805, "s": 3716, "text": "In the code below I scrape the wikipedia table and create a vector of all SP500 tickers:" }, { "code": null, "e": 3852, "s": 3805, "text": "I first assign the wikipedia URL to a variable" }, { "code": null, "e": 3882, "s": 3852, "text": "Read in the html from the URL" }, { "code": null, "e": 3939, "s": 3882, "text": "Select the correct html nodes and extract the html table" }, { "code": null, "e": 4048, "s": 3939, "text": "Make a small change to ticker names because yahoo finance uses a ‘_’ instead of ‘.’ for certain symbol names" }, { "code": null, "e": 4277, "s": 4048, "text": "The hardest part of scraping is figuring out the xpath or css to indicate which html nodes to select. I really don’t know much about html or css, but using Google Chrome I was able to find the correct xpath (more on this below)." }, { "code": null, "e": 4990, "s": 4277, "text": "# get the URL for the wikipedia page with all SP500 symbolsurl <- \"https://en.wikipedia.org/wiki/List_of_S%26P_500_companies\"# use that URL to scrape the SP500 table using rvesttickers <- url %>% # read the HTML from the webpage read_html() %>% # one way to get table #html_nodes(xpath='//*[@id=\"mw-content-text\"]/div/table[1]') %>% # easier way to get table html_nodes(xpath = '//*[@id=\"constituents\"]') %>% html_table()#create a vector of tickerssp500tickers <- tickers[[1]]sp500tickers = sp500tickers %>% mutate(Symbol = case_when(Symbol == \"BRK.B\" ~ \"BRK-B\", Symbol == \"BF.B\" ~ \"BF-B\", TRUE ~ as.character(Symbol)))" }, { "code": null, "e": 5054, "s": 4990, "text": "Go to https://en.wikipedia.org/wiki/List_of_S%26P_500_companies" }, { "code": null, "e": 5100, "s": 5054, "text": "right click on webpage, select inspect option" }, { "code": null, "e": 5218, "s": 5100, "text": "Most webpage content is usually in the body of an html document. We’ll expand that section. That will look like this:" }, { "code": null, "e": 5310, "s": 5218, "text": "Looking at the webpage, I can see the table that I want is right below the first h2 header:" }, { "code": null, "e": 5413, "s": 5310, "text": "After navigating around the page structure I found the first h2 header and the table I wanted below it" }, { "code": null, "e": 5505, "s": 5413, "text": "I can click on the table, right click and copy the xpath that is needed to scrape the table" }, { "code": null, "e": 5576, "s": 5505, "text": "xpath = //*[@id=”constituents”], this is what was passed to html_nodes" }, { "code": null, "e": 5621, "s": 5576, "text": "html_nodes(xpath = '//*[@id=\"constituents\"]'" }, { "code": null, "e": 5746, "s": 5621, "text": "Iterating refers to programmatically repeating a step or sets of steps, a set number of times or until a condition is meant." }, { "code": null, "e": 6388, "s": 5746, "text": "Typically, when we iterate in any programming language, we use a loop, typically a for loop. I will need to iterate over each element in the vector of SP500 tickers and pass it to the function tq_get(). I could do this with a for loop, but using the purrr package is a better idea. Loops in R are slow and hard to read. The purrr package provides a suite of functions for iteration and functional programming that integrate well with the rest of the tidyverse. The core function in purrr in map(). Most programming languages (including my favorite one python) have a map function that serves to apply a function to all elements of an object." }, { "code": null, "e": 6650, "s": 6388, "text": "Functional Programming is a programming paradigm in which functions, as opposed to classes, build the structure and logic of programs. For loops are typically avoided in functional programming. Instead, functions are mapped or applied to lists or other objects." }, { "code": null, "e": 6709, "s": 6650, "text": "As Hadley Wickham stated perfectly in his Advanced R book:" }, { "code": null, "e": 7186, "s": 6709, "text": "“It’s hard to describe exactly what a functional style is, but generally I think it means decomposing a big problem into smaller pieces, then solving each piece with a function or combination of functions. When using a functional style, you strive to decompose components of the problem into isolated functions that operate independently. Each function taken by itself is simple and straightforward to understand; complexity is handled by composing functions in various ways.”" }, { "code": null, "e": 7323, "s": 7186, "text": "Let’s look at the difference between iteration in purrr and a for loop with an example. Both of these operations are roughly equivalent:" }, { "code": null, "e": 7521, "s": 7323, "text": "# get a sequence of the numbers 1 to 5numbers = seq(1:5)print('for loop')# for loop for (i in numbers){ print(i)}print('purrr :)')# purr functional programming approachlist = map(numbers, print)" }, { "code": null, "e": 7543, "s": 7521, "text": "A few things to note:" }, { "code": null, "e": 7625, "s": 7543, "text": "both the for loop and map function do an operation for each element in the vector" }, { "code": null, "e": 7854, "s": 7625, "text": "the map function returns a nested list where each entry is the result of the function called inside of it for one of the entries in the object that being iterated over. I assign this to a variable list to avoid it from printing." }, { "code": null, "e": 7912, "s": 7854, "text": "Using purrr’s map function is only one line and less code" }, { "code": null, "e": 7957, "s": 7912, "text": "Using purrr’s map function is easier to read" }, { "code": null, "e": 8295, "s": 7957, "text": "First I need to write a function to iterate over or apply to each element of the vector. I cannot simply use tq_get() with map() because it does not return the ticker name as a column of the dataframe. In order to get the ticker with the dataframe, I will use the mutate() function from dplyr to create a new column with the ticker name." }, { "code": null, "e": 8418, "s": 8295, "text": "get_symbols = function(ticker = \"AAPL\"){ df = tq_get(ticker, from = date) %>% mutate(symbol = rep(ticker, length(date)))}" }, { "code": null, "e": 8708, "s": 8418, "text": "I then use this function in conjunction with map() to iterate over the list of all symbols. This returns a nested list containing a dataframe for each ticker. I use the dplyr bind_rows() function to bind the dataframes together row-wise, to create one dataframe with all the SP500 tickers." }, { "code": null, "e": 8916, "s": 8708, "text": "#create the dataframe of SP500 data by interating over our list of symbols and call our get symbols function each time#the map function accomplishes thistickers_df = map(symbols, get_symbols) %>% bind_rows()" }, { "code": null, "e": 9105, "s": 8916, "text": "I also want this dataframe to contain the information from the wikipedia table, most importantly, the name of the company. This can be achieved by joining the two dataframes by the symbol." }, { "code": null, "e": 9361, "s": 9105, "text": "tickers_df = tickers_df %>% # left join with wikipedia data left_join(sp500tickers, by = c('symbol' = 'Symbol')) %>% # make names R compatible clean_names() %>% # keep only the columns we need select(date:security, gics_sector, gics_sub_industry)" }, { "code": null, "e": 9466, "s": 9361, "text": "After joining the data we should do a quick sanity check to make sure that we have all 505 SP500 tickers" }, { "code": null, "e": 9685, "s": 9466, "text": "tickers_df %>% # select just the symbol columnselect(symbol)%>% # get the distinct valuesdistinct()%>% # count the distinct values count() %>% # we can use select to rename columns select(\"Total Number of Tickers\" = n)" }, { "code": null, "e": 9790, "s": 9685, "text": "Finally, we can inspect the first few rows of the dataframe, to confirm we have gotten the data we want:" }, { "code": null, "e": 9814, "s": 9790, "text": "tickers_df %>% head()" }, { "code": null, "e": 9849, "s": 9814, "text": "Perfect! Exactly what we expected." }, { "code": null, "e": 9862, "s": 9849, "text": "Wrapping up:" }, { "code": null, "e": 9895, "s": 9862, "text": "In this first blog post we have:" }, { "code": null, "e": 9961, "s": 9895, "text": "Learned about the basics of the tidyverse ecosystem and tidyquant" }, { "code": null, "e": 10031, "s": 9961, "text": "Learned about the basics of tidy iteration and functional programming" }, { "code": null, "e": 10102, "s": 10031, "text": "Learned how to leverage rvest and chrome to scrape data from wikipedia" }, { "code": null, "e": 10172, "s": 10102, "text": "Learned how to move from reading in a single asset to the whole SP500" }, { "code": null, "e": 10190, "s": 10172, "text": "In the next post:" }, { "code": null, "e": 10226, "s": 10190, "text": "I will answer my original question:" }, { "code": null, "e": 10300, "s": 10226, "text": "Which SP500 assets had the highest average return over the last 3 months?" }, { "code": null, "e": 10322, "s": 10300, "text": "A few things to note:" }, { "code": null, "e": 10544, "s": 10322, "text": "You can obtain a list of all SP500 stocks much more easily with tq_index(“SP500\"). This function does require the XLConnect library. I currently am having issues getting that library to import and run on my local machine." }, { "code": null, "e": 10619, "s": 10544, "text": "tq_get() actually accepts lists of tickers, so using map() isn’t necessary" }, { "code": null, "e": 10698, "s": 10619, "text": "I intentionally wrote the code this way, to demonstrate the described concepts" }, { "code": null, "e": 11201, "s": 10698, "text": "Disclaimer: In college, I did a project with SP500 data and python. It is against class policy to share this project. While what I am doing here is somewhat similar, I am using a completely different programming language and answering a completely different question. Given my previous statement, I assert that this is not a violation of that courses policy. I intentionally used the R programming language as opposed to python to completely avoid any issues and to respect my former professors wishes." }, { "code": null, "e": 11228, "s": 11201, "text": "The Code can be found here" }, { "code": null, "e": 11313, "s": 11228, "text": "This is another great source on scraping that helped a bit when writing the article." }, { "code": null, "e": 11488, "s": 11313, "text": "https://medium.com/@kyleake/wikipedia-data-scraping-with-r-rvest-in-action-3c419db9af2dhttps://medium.com/@kyleake/wikipedia-data-scraping-with-r-rvest-in-action-3c419db9af2d" } ]
Python Program for Program to find area of a circle - GeeksforGeeks
12 Apr, 2022 Area of a circle can simply be evaluated using following formula. Area = pi * r2 where r is radius of circle Python3 # Python program to find Area of a circle def findArea(r): PI = 3.142 return PI * (r*r); # Driver methodprint("Area is %.6f" % findArea(5)); # This code is contributed by Chinmoy Lenka Python3 # Python program to find Area of a circle using inbuild library import mathdef area(r): area = math.pi* pow(r,2) return print('Area of circle is:' ,area)area(4) # This code is contributed by Sejal Pol Please refer complete article on Program to find area of a circle for more details! sejalpol2 Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for factorial of a number Python | Convert string dictionary to dictionary Python program to add two numbers Python Program for Binary Search (Recursive and Iterative) Python Program for Bubble Sort Iterate over characters of a string in Python Python | Check if a variable is string Python | Convert set into a list
[ { "code": null, "e": 25070, "s": 25042, "text": "\n12 Apr, 2022" }, { "code": null, "e": 25136, "s": 25070, "text": "Area of a circle can simply be evaluated using following formula." }, { "code": null, "e": 25180, "s": 25136, "text": "Area = pi * r2\nwhere r is radius of circle " }, { "code": null, "e": 25188, "s": 25180, "text": "Python3" }, { "code": "# Python program to find Area of a circle def findArea(r): PI = 3.142 return PI * (r*r); # Driver methodprint(\"Area is %.6f\" % findArea(5)); # This code is contributed by Chinmoy Lenka", "e": 25386, "s": 25188, "text": null }, { "code": null, "e": 25394, "s": 25386, "text": "Python3" }, { "code": "# Python program to find Area of a circle using inbuild library import mathdef area(r): area = math.pi* pow(r,2) return print('Area of circle is:' ,area)area(4) # This code is contributed by Sejal Pol", "e": 25599, "s": 25394, "text": null }, { "code": null, "e": 25683, "s": 25599, "text": "Please refer complete article on Program to find area of a circle for more details!" }, { "code": null, "e": 25693, "s": 25683, "text": "sejalpol2" }, { "code": null, "e": 25709, "s": 25693, "text": "Python Programs" }, { "code": null, "e": 25807, "s": 25709, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25816, "s": 25807, "text": "Comments" }, { "code": null, "e": 25829, "s": 25816, "text": "Old Comments" }, { "code": null, "e": 25868, "s": 25829, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25906, "s": 25868, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 25947, "s": 25906, "text": "Python Program for factorial of a number" }, { "code": null, "e": 25996, "s": 25947, "text": "Python | Convert string dictionary to dictionary" }, { "code": null, "e": 26030, "s": 25996, "text": "Python program to add two numbers" }, { "code": null, "e": 26089, "s": 26030, "text": "Python Program for Binary Search (Recursive and Iterative)" }, { "code": null, "e": 26120, "s": 26089, "text": "Python Program for Bubble Sort" }, { "code": null, "e": 26166, "s": 26120, "text": "Iterate over characters of a string in Python" }, { "code": null, "e": 26205, "s": 26166, "text": "Python | Check if a variable is string" } ]
How to Select Multiple Images from Gallery in Android? - GeeksforGeeks
07 Mar, 2021 In the previous article, we have seen How to Select an Image from Gallery in Android but most of the time when we are posting a status on whatsapp or posting a post on facebook or instagram we select more than one images. So in this article, it’s been discussed step by step how to select one or more than one image from the gallery and then we will see the total count of selected image. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the AndroidManifest.xml file For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and Inside that file add the below permissions to it. <uses-permission android:name=”android.permission.READ_EXTERNAL_STORAGE”/> <uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”/> <uses-permission android:name=”android.permission.INTERNET”/> Step 3: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/select" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="Select Multiple Images" /> <ImageSwitcher android:id="@+id/image" android:layout_width="200dp" android:layout_height="200dp" android:layout_marginLeft="100dp" /> <!--click here to view previous image--> <Button android:id="@+id/previous" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="Previous" /> <!--click here to view next image--> <Button android:id="@+id/next" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="Next" /> <TextView android:id="@+id/text" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#000" android:textSize="22sp" android:textStyle="bold" /> </LinearLayout> Step 4: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.ClipData;import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageSwitcher;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast;import android.widget.ViewSwitcher; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { Button select, previous, next; ImageSwitcher imageView; int PICK_IMAGE_MULTIPLE = 1; String imageEncoded; TextView total; ArrayList<Uri> mArrayUri; int position = 0; List<String> imagesEncodedList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); select = findViewById(R.id.select); total = findViewById(R.id.text); imageView = findViewById(R.id.image); previous = findViewById(R.id.previous); mArrayUri = new ArrayList<Uri>(); // showing all images in imageswitcher imageView.setFactory(new ViewSwitcher.ViewFactory() { @Override public View makeView() { ImageView imageView1 = new ImageView(getApplicationContext()); return imageView1; } }); next = findViewById(R.id.next); // click here to select next image next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (position < mArrayUri.size() - 1) { // increase the position by 1 position++; imageView.setImageURI(mArrayUri.get(position)); } else { Toast.makeText(MainActivity.this, "Last Image Already Shown", Toast.LENGTH_SHORT).show(); } } }); // click here to view previous image previous.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (position > 0) { // decrease the position by 1 position--; imageView.setImageURI(mArrayUri.get(position)); } } }); imageView = findViewById(R.id.image); // click here to select image select.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // initialising intent Intent intent = new Intent(); // setting type to select to be image intent.setType("image/*"); // allowing multiple image to be selected intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_MULTIPLE); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // When an Image is picked if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK && null != data) { // Get the Image from data if (data.getClipData() != null) { ClipData mClipData = data.getClipData(); int cout = data.getClipData().getItemCount(); for (int i = 0; i < cout; i++) { // adding imageuri in array Uri imageurl = data.getClipData().getItemAt(i).getUri(); mArrayUri.add(imageurl); } // setting 1st selected image into image switcher imageView.setImageURI(mArrayUri.get(0)); position = 0; } else { Uri imageurl = data.getData(); mArrayUri.add(imageurl); imageView.setImageURI(mArrayUri.get(0)); position = 0; } } else { // show this if no image is selected Toast.makeText(this, "You haven't picked Image", Toast.LENGTH_LONG).show(); } }} Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Android RecyclerView in Kotlin CardView in Android With Example Content Providers in Android with Example Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 25133, "s": 25105, "text": "\n07 Mar, 2021" }, { "code": null, "e": 25689, "s": 25133, "text": "In the previous article, we have seen How to Select an Image from Gallery in Android but most of the time when we are posting a status on whatsapp or posting a post on facebook or instagram we select more than one images. So in this article, it’s been discussed step by step how to select one or more than one image from the gallery and then we will see the total count of selected image. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 25718, "s": 25689, "text": "Step 1: Create a New Project" }, { "code": null, "e": 25880, "s": 25718, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 25930, "s": 25880, "text": "Step 2: Working with the AndroidManifest.xml file" }, { "code": null, "e": 26148, "s": 25930, "text": "For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and Inside that file add the below permissions to it. " }, { "code": null, "e": 26223, "s": 26148, "text": "<uses-permission android:name=”android.permission.READ_EXTERNAL_STORAGE”/>" }, { "code": null, "e": 26299, "s": 26223, "text": "<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”/>" }, { "code": null, "e": 26361, "s": 26299, "text": "<uses-permission android:name=”android.permission.INTERNET”/>" }, { "code": null, "e": 26409, "s": 26361, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 26552, "s": 26409, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 26556, "s": 26552, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/select\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"20dp\" android:text=\"Select Multiple Images\" /> <ImageSwitcher android:id=\"@+id/image\" android:layout_width=\"200dp\" android:layout_height=\"200dp\" android:layout_marginLeft=\"100dp\" /> <!--click here to view previous image--> <Button android:id=\"@+id/previous\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"20dp\" android:text=\"Previous\" /> <!--click here to view next image--> <Button android:id=\"@+id/next\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"20dp\" android:text=\"Next\" /> <TextView android:id=\"@+id/text\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:textColor=\"#000\" android:textSize=\"22sp\" android:textStyle=\"bold\" /> </LinearLayout>", "e": 27996, "s": 26556, "text": null }, { "code": null, "e": 28044, "s": 27996, "text": "Step 4: Working with the MainActivity.java file" }, { "code": null, "e": 28234, "s": 28044, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 28239, "s": 28234, "text": "Java" }, { "code": "import android.content.ClipData;import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageSwitcher;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast;import android.widget.ViewSwitcher; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { Button select, previous, next; ImageSwitcher imageView; int PICK_IMAGE_MULTIPLE = 1; String imageEncoded; TextView total; ArrayList<Uri> mArrayUri; int position = 0; List<String> imagesEncodedList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); select = findViewById(R.id.select); total = findViewById(R.id.text); imageView = findViewById(R.id.image); previous = findViewById(R.id.previous); mArrayUri = new ArrayList<Uri>(); // showing all images in imageswitcher imageView.setFactory(new ViewSwitcher.ViewFactory() { @Override public View makeView() { ImageView imageView1 = new ImageView(getApplicationContext()); return imageView1; } }); next = findViewById(R.id.next); // click here to select next image next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (position < mArrayUri.size() - 1) { // increase the position by 1 position++; imageView.setImageURI(mArrayUri.get(position)); } else { Toast.makeText(MainActivity.this, \"Last Image Already Shown\", Toast.LENGTH_SHORT).show(); } } }); // click here to view previous image previous.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (position > 0) { // decrease the position by 1 position--; imageView.setImageURI(mArrayUri.get(position)); } } }); imageView = findViewById(R.id.image); // click here to select image select.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // initialising intent Intent intent = new Intent(); // setting type to select to be image intent.setType(\"image/*\"); // allowing multiple image to be selected intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, \"Select Picture\"), PICK_IMAGE_MULTIPLE); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // When an Image is picked if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK && null != data) { // Get the Image from data if (data.getClipData() != null) { ClipData mClipData = data.getClipData(); int cout = data.getClipData().getItemCount(); for (int i = 0; i < cout; i++) { // adding imageuri in array Uri imageurl = data.getClipData().getItemAt(i).getUri(); mArrayUri.add(imageurl); } // setting 1st selected image into image switcher imageView.setImageURI(mArrayUri.get(0)); position = 0; } else { Uri imageurl = data.getData(); mArrayUri.add(imageurl); imageView.setImageURI(mArrayUri.get(0)); position = 0; } } else { // show this if no image is selected Toast.makeText(this, \"You haven't picked Image\", Toast.LENGTH_LONG).show(); } }}", "e": 32635, "s": 28239, "text": null }, { "code": null, "e": 32643, "s": 32635, "text": "Android" }, { "code": null, "e": 32648, "s": 32643, "text": "Java" }, { "code": null, "e": 32653, "s": 32648, "text": "Java" }, { "code": null, "e": 32661, "s": 32653, "text": "Android" }, { "code": null, "e": 32759, "s": 32661, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32768, "s": 32759, "text": "Comments" }, { "code": null, "e": 32781, "s": 32768, "text": "Old Comments" }, { "code": null, "e": 32839, "s": 32781, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 32882, "s": 32839, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 32913, "s": 32882, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 32946, "s": 32913, "text": "CardView in Android With Example" }, { "code": null, "e": 32988, "s": 32946, "text": "Content Providers in Android with Example" }, { "code": null, "e": 33003, "s": 32988, "text": "Arrays in Java" }, { "code": null, "e": 33047, "s": 33003, "text": "Split() String method in Java with examples" }, { "code": null, "e": 33069, "s": 33047, "text": "For-each loop in Java" }, { "code": null, "e": 33094, "s": 33069, "text": "Reverse a string in Java" } ]
A Novel Solution to Cleaning Extremely Dirty Unstructured text | by Timothy Tan | Towards Data Science
After two whole weeks of trial and error and almost thinking it was impossible... I did it. I’d managed to turn this: “Thsi wass a dificult prbl em to resol ve” Into this: “This was a difficult problem to resolve” I thought I’d seen it all after working with the likes of Singlish or even Tweets. But never would I have thought I’d come across unstructured text data so dirty. I’ve obviously exaggerated the example above but the problem boils down to these two key points: Misspelling detection and resolution Handling random white spaces in-between words As humans, we can easily decipher the statement above as: “This was a difficult problem to resolve” However, coming up with a methodology to resolve such a data issue proved more challenging than anticipated. In this post, I will be going through a novel solution I took to clean up an extremely dirty unstructured text dataset. Here’s a glimpse of how the data looked like: Note: This is just an example of how the dirty data looked like and not the actual data. There won’t be much code snippets today but by the end of the post, you will get an idea of the methodology involved to resolve such a data issue if you ever come across it. In one of my previous posts on handling misspellings, I used word vectors and did a lot of translations to form a generalised translation vector to handle misspellings. towardsdatascience.com In this post, I will be falling back on an algorithmic approach to handling misspellings. There are two parts to this segment: Detect misspelled wordsResolve misspelled words Detect misspelled words Resolve misspelled words I used SAS Viya’s out of the box misspelling action called tpSpell to do this. Note: SAS works with something called Actionsets which are synonymous to Python Packages. Within each Actionset, there are many Actions that can be performed. In this step, the tpSpell action performs what it is known as Candidate Extraction. Candidate Extraction groups words into two categories: Correctly-spelled word candidates Misspelled word candidates A correctly-spelled word candidate is determined by a predetermined parameter (“minimum parents”) before running the procedure. This parameter specifies the minimum number of documents a term must appear in to be considered a correctly-spelled word candidate. All correctly-spelled word candidate takes the form <term>-<role>-<parent> . For example, refer to figure 1 below: Notice how the potential candidate name is a concatenation of the columns “Term”, “Role” and “Parent” to form “algorithms-N-algorithm”. Here’s the breakdown of the logic. If the potential candidate name, “algorithms-N-algorithm”, appears 5 times in 4 documents, then the number of documents it appeared in equals to 4.If the predetermined parameter called “minimum parents” is set to 3, since 4 is more 3, the word “algorithms-N-algorithm” is added into a correctly-spelled candidate list. If the potential candidate name, “algorithms-N-algorithm”, appears 5 times in 4 documents, then the number of documents it appeared in equals to 4. If the predetermined parameter called “minimum parents” is set to 3, since 4 is more 3, the word “algorithms-N-algorithm” is added into a correctly-spelled candidate list. Now, what about the misspelled word candidates list? How then do we create this table? Just like the correctly-spelled word candidate list, there is another predetermined parameter to set. This time, it is called “maximum children”. Take a look a figure 2 below for instance: The logic is simple. If the “maximum children” parameter is set to 3 and the number of documents a potential candidate name like “algoxxxthzs-N-algoxxxthzs” appears in is less than 3, then “algoxxxthzs-N-algoxxxthzs” is added into the misspelled word candidate list. This logic is repeated for the whole table specified in figure 2. Now that we have got a correctly-spelled candidate list and a misspelled word candidate list, what follows is the logic in assigning the correctly spelled word to its respective misspellings. In this step, Candidate Comparisons are performed to resolve misspellings. The algorithm will now check all words in the misspelled list against all words in the correctly-spelled list. It compares a misspelled word candidate to every correctly spelled word candidate, and computes a distance between them. Another predetermined parameter called “maximum spell distance” determines if the misspelled word has a correct spelling or not. For instance, if the word “algoxxxthzs” is the given misspelled word and the word “algorithm” is the correctly spelled candidate, then the distance computed between “algoxxxthzs” and “algorithm” would be 50. If “maximum spell distance” was set to 20. Since 50 is greater than 20, the correctly spelled candidate “algorithm” is now deemed as the correct spelling for the word “algoxxxthzs”. There are also other advance parameters you could set here to account for multi-term words like “fire engine”, “carry on” or “join in” etc. You can read the documentation here. Although I made it sound really complicated above... It is not. Here’s how to run all of the above. proc cas; textParse.tpSpell / table={name="pos", caslib="public"} minParents=3 maxChildren=6 maxSpellDist=15 casOut={name="tpSpell_Out", replace=true}; run;quit; The result will look as such: One thing I love about SAS programming is how easy it is to make use of complicated algorithms with just a few lines of code. Yes, Python packages do the same thing but sometimes, the packages are not as advanced as SAS. A good example would be how SAS does optimization for deep learning hyperparameters and parameters within the layers. As an anecdote, it was really easy to do hyper-parameter tuning in SAS. SAS combines Latin Hypercube with the Genetic Algorithm optimized with the Hyperband method to account for resource utilization. In addition, everything is automatically multi-threaded. Coding what SAS does out of the box in Python would have definitely taken more time, effort and not to mention, the knowledge needed on how to distribute processing with Python, accounting for resource allocation and utilization — which I think the majority of the people aren’t familiar with. This problem really had me testing multiple methodologies. All of which did not perform well except for the methodology I’ll be going through now. To re fresh your m emry, thee probl em loked lik e thsi There are a few data quality issues worth pointing out above: Space in-between the words i.e. “probl em”Missing characters i.e. “loked”Swapped characters i.e. “thsi”Double characters i.e. “thee”Combination of issues i.e. “m emry” — combination of 1 and 2. Space in-between the words i.e. “probl em” Missing characters i.e. “loked” Swapped characters i.e. “thsi” Double characters i.e. “thee” Combination of issues i.e. “m emry” — combination of 1 and 2. I had to find a way to resolve the spaces in-between words while at the same time, account for the misspellings (numbers 2, 3 and 4). Thankfully, handling the misspellings can be taken care of relatively easily as I have shown above with tpSpell. But the complexity comes in with the combinations of issues (number 5). For a combination problem like this, I first needed to resolve the white spaces before applying the misspelling resolution. While thinking about the best solution for the job, I took inspiration from how encoder-decoder networks worked. Could I somehow “encode” the sentences and “decode” them after? Obviously I’m using the terms inappropriately here. By “encode” I actually meant to remove all white spaces between words. Like such: torefreshyourmemrytheeproblemlokedlikethsi By “decode”, I mean to break the words back into their individual words after resolving misspellings: to refresh your memory the problem looked like this One of the biggest problem I had to resolve was when to insert a white space once a string had been “encoded”. Take the words “torefresh” for instance. How would you know to insert a white space between “to” and “refresh”? Why not “to”, “re” and “fresh”? Here’s how I did it and the logic of my SAS script. Decoded words are based off the longest match of the word. For example, if I saw the words “helloworld”, I am first going to perform a look up for the word “hell” in a predefined potential candidate list. i.e. dictionary table Until the next character “o” appears, since “hell+o” = “hello”, “hello” becomes the better potential candidate. I drop the word “hell” as main candidate and keep the word “hello” as the new main candidate. As the next character gets read in, “hello+w” = “hellow”, since “hellow” is not a proper word in the potential candidate list, the best candidate to split off is “hello”. Once these checks are completed, I add a white space after “hello” and continue the logic above for “w”, “o”, “r”, “l” and “d” until I get “hello world” So what is this potential candidate list and how did I get this dictionary? It is a dictionary I created from the correctly-spelled word list generated from the tpSpell action earlier. Meaning to say, all correctly-spelled words are placed into this dictionary table for me to look up as I “decode” each string. There were other issues that needed to be resolved to make the “decoder” work. That is, I had to remove stop words, all forms of punctuation, lower cased all words and only keep parent terms. Why? Because if I didn’t there would have been a lot of issues that surfaced. Take this sentence for instance: “the series of books” After “encoding” it will be: “theseriesofbooks” Recall that the algorithm I created takes the longest match in the dictionary during the “decoding” process. If I kept all stop words, the “decoder” would have parsed the first word as “these” and not “the”. Because of this, the next characters “ries” in the word “series” will no longer be a word in my dictionary, and will be discarded. This would mean the “decoded” string will end up being “these of books”, which is obviously incorrect. Another intricacy that affects the “decoder” looks something like this: “bicycle sports” → “bicyclesports” → “bicycles ports” (wrong) To counter this issue, I only kept parent terms in my dictionary table. Example 1: bicycles → bicycle Example 2: sports → sport By only looking at parent terms, my output looked like this: “bicycle sport” → “bicyclesport” → “bicycle sport” (correct) Because “bicycles” is no longer in my dictionary and “bicycle” is, the decoder parses it correctly and does not output “bicycles port”. So there you have it! My very own “encoder-decoder” methodology to clean extremely dirty unstructured text! 😉 It’s not a perfect solution but it does get the job done enough for me to start my downstream NLP task proper. Just to show you an example of how the would look like after running the code, I ran the code against a books review corpus with mocked up data quality issues. Here’s how the sample and the process looks like: Well, that’s it then! I hope you found this post insightful! 😃 Albeit spending close to 2 weeks trying out many methodologies, I had tons of fun with this! Till next time, farewell! Linkedin Profile: Timothy Tan
[ { "code": null, "e": 254, "s": 172, "text": "After two whole weeks of trial and error and almost thinking it was impossible..." }, { "code": null, "e": 264, "s": 254, "text": "I did it." }, { "code": null, "e": 290, "s": 264, "text": "I’d managed to turn this:" }, { "code": null, "e": 333, "s": 290, "text": "“Thsi wass a dificult prbl em to resol ve”" }, { "code": null, "e": 344, "s": 333, "text": "Into this:" }, { "code": null, "e": 386, "s": 344, "text": "“This was a difficult problem to resolve”" }, { "code": null, "e": 469, "s": 386, "text": "I thought I’d seen it all after working with the likes of Singlish or even Tweets." }, { "code": null, "e": 549, "s": 469, "text": "But never would I have thought I’d come across unstructured text data so dirty." }, { "code": null, "e": 646, "s": 549, "text": "I’ve obviously exaggerated the example above but the problem boils down to these two key points:" }, { "code": null, "e": 683, "s": 646, "text": "Misspelling detection and resolution" }, { "code": null, "e": 729, "s": 683, "text": "Handling random white spaces in-between words" }, { "code": null, "e": 787, "s": 729, "text": "As humans, we can easily decipher the statement above as:" }, { "code": null, "e": 829, "s": 787, "text": "“This was a difficult problem to resolve”" }, { "code": null, "e": 938, "s": 829, "text": "However, coming up with a methodology to resolve such a data issue proved more challenging than anticipated." }, { "code": null, "e": 1058, "s": 938, "text": "In this post, I will be going through a novel solution I took to clean up an extremely dirty unstructured text dataset." }, { "code": null, "e": 1104, "s": 1058, "text": "Here’s a glimpse of how the data looked like:" }, { "code": null, "e": 1193, "s": 1104, "text": "Note: This is just an example of how the dirty data looked like and not the actual data." }, { "code": null, "e": 1367, "s": 1193, "text": "There won’t be much code snippets today but by the end of the post, you will get an idea of the methodology involved to resolve such a data issue if you ever come across it." }, { "code": null, "e": 1536, "s": 1367, "text": "In one of my previous posts on handling misspellings, I used word vectors and did a lot of translations to form a generalised translation vector to handle misspellings." }, { "code": null, "e": 1559, "s": 1536, "text": "towardsdatascience.com" }, { "code": null, "e": 1649, "s": 1559, "text": "In this post, I will be falling back on an algorithmic approach to handling misspellings." }, { "code": null, "e": 1686, "s": 1649, "text": "There are two parts to this segment:" }, { "code": null, "e": 1734, "s": 1686, "text": "Detect misspelled wordsResolve misspelled words" }, { "code": null, "e": 1758, "s": 1734, "text": "Detect misspelled words" }, { "code": null, "e": 1783, "s": 1758, "text": "Resolve misspelled words" }, { "code": null, "e": 1862, "s": 1783, "text": "I used SAS Viya’s out of the box misspelling action called tpSpell to do this." }, { "code": null, "e": 2021, "s": 1862, "text": "Note: SAS works with something called Actionsets which are synonymous to Python Packages. Within each Actionset, there are many Actions that can be performed." }, { "code": null, "e": 2105, "s": 2021, "text": "In this step, the tpSpell action performs what it is known as Candidate Extraction." }, { "code": null, "e": 2160, "s": 2105, "text": "Candidate Extraction groups words into two categories:" }, { "code": null, "e": 2194, "s": 2160, "text": "Correctly-spelled word candidates" }, { "code": null, "e": 2221, "s": 2194, "text": "Misspelled word candidates" }, { "code": null, "e": 2349, "s": 2221, "text": "A correctly-spelled word candidate is determined by a predetermined parameter (“minimum parents”) before running the procedure." }, { "code": null, "e": 2481, "s": 2349, "text": "This parameter specifies the minimum number of documents a term must appear in to be considered a correctly-spelled word candidate." }, { "code": null, "e": 2558, "s": 2481, "text": "All correctly-spelled word candidate takes the form <term>-<role>-<parent> ." }, { "code": null, "e": 2596, "s": 2558, "text": "For example, refer to figure 1 below:" }, { "code": null, "e": 2732, "s": 2596, "text": "Notice how the potential candidate name is a concatenation of the columns “Term”, “Role” and “Parent” to form “algorithms-N-algorithm”." }, { "code": null, "e": 2767, "s": 2732, "text": "Here’s the breakdown of the logic." }, { "code": null, "e": 3086, "s": 2767, "text": "If the potential candidate name, “algorithms-N-algorithm”, appears 5 times in 4 documents, then the number of documents it appeared in equals to 4.If the predetermined parameter called “minimum parents” is set to 3, since 4 is more 3, the word “algorithms-N-algorithm” is added into a correctly-spelled candidate list." }, { "code": null, "e": 3234, "s": 3086, "text": "If the potential candidate name, “algorithms-N-algorithm”, appears 5 times in 4 documents, then the number of documents it appeared in equals to 4." }, { "code": null, "e": 3406, "s": 3234, "text": "If the predetermined parameter called “minimum parents” is set to 3, since 4 is more 3, the word “algorithms-N-algorithm” is added into a correctly-spelled candidate list." }, { "code": null, "e": 3493, "s": 3406, "text": "Now, what about the misspelled word candidates list? How then do we create this table?" }, { "code": null, "e": 3595, "s": 3493, "text": "Just like the correctly-spelled word candidate list, there is another predetermined parameter to set." }, { "code": null, "e": 3639, "s": 3595, "text": "This time, it is called “maximum children”." }, { "code": null, "e": 3682, "s": 3639, "text": "Take a look a figure 2 below for instance:" }, { "code": null, "e": 3703, "s": 3682, "text": "The logic is simple." }, { "code": null, "e": 3949, "s": 3703, "text": "If the “maximum children” parameter is set to 3 and the number of documents a potential candidate name like “algoxxxthzs-N-algoxxxthzs” appears in is less than 3, then “algoxxxthzs-N-algoxxxthzs” is added into the misspelled word candidate list." }, { "code": null, "e": 4015, "s": 3949, "text": "This logic is repeated for the whole table specified in figure 2." }, { "code": null, "e": 4207, "s": 4015, "text": "Now that we have got a correctly-spelled candidate list and a misspelled word candidate list, what follows is the logic in assigning the correctly spelled word to its respective misspellings." }, { "code": null, "e": 4282, "s": 4207, "text": "In this step, Candidate Comparisons are performed to resolve misspellings." }, { "code": null, "e": 4393, "s": 4282, "text": "The algorithm will now check all words in the misspelled list against all words in the correctly-spelled list." }, { "code": null, "e": 4514, "s": 4393, "text": "It compares a misspelled word candidate to every correctly spelled word candidate, and computes a distance between them." }, { "code": null, "e": 4643, "s": 4514, "text": "Another predetermined parameter called “maximum spell distance” determines if the misspelled word has a correct spelling or not." }, { "code": null, "e": 4851, "s": 4643, "text": "For instance, if the word “algoxxxthzs” is the given misspelled word and the word “algorithm” is the correctly spelled candidate, then the distance computed between “algoxxxthzs” and “algorithm” would be 50." }, { "code": null, "e": 5033, "s": 4851, "text": "If “maximum spell distance” was set to 20. Since 50 is greater than 20, the correctly spelled candidate “algorithm” is now deemed as the correct spelling for the word “algoxxxthzs”." }, { "code": null, "e": 5210, "s": 5033, "text": "There are also other advance parameters you could set here to account for multi-term words like “fire engine”, “carry on” or “join in” etc. You can read the documentation here." }, { "code": null, "e": 5263, "s": 5210, "text": "Although I made it sound really complicated above..." }, { "code": null, "e": 5274, "s": 5263, "text": "It is not." }, { "code": null, "e": 5310, "s": 5274, "text": "Here’s how to run all of the above." }, { "code": null, "e": 5479, "s": 5310, "text": "proc cas; textParse.tpSpell / table={name=\"pos\", caslib=\"public\"} minParents=3 maxChildren=6 maxSpellDist=15 casOut={name=\"tpSpell_Out\", replace=true}; run;quit;" }, { "code": null, "e": 5509, "s": 5479, "text": "The result will look as such:" }, { "code": null, "e": 5635, "s": 5509, "text": "One thing I love about SAS programming is how easy it is to make use of complicated algorithms with just a few lines of code." }, { "code": null, "e": 5730, "s": 5635, "text": "Yes, Python packages do the same thing but sometimes, the packages are not as advanced as SAS." }, { "code": null, "e": 5920, "s": 5730, "text": "A good example would be how SAS does optimization for deep learning hyperparameters and parameters within the layers. As an anecdote, it was really easy to do hyper-parameter tuning in SAS." }, { "code": null, "e": 6106, "s": 5920, "text": "SAS combines Latin Hypercube with the Genetic Algorithm optimized with the Hyperband method to account for resource utilization. In addition, everything is automatically multi-threaded." }, { "code": null, "e": 6400, "s": 6106, "text": "Coding what SAS does out of the box in Python would have definitely taken more time, effort and not to mention, the knowledge needed on how to distribute processing with Python, accounting for resource allocation and utilization — which I think the majority of the people aren’t familiar with." }, { "code": null, "e": 6547, "s": 6400, "text": "This problem really had me testing multiple methodologies. All of which did not perform well except for the methodology I’ll be going through now." }, { "code": null, "e": 6603, "s": 6547, "text": "To re fresh your m emry, thee probl em loked lik e thsi" }, { "code": null, "e": 6665, "s": 6603, "text": "There are a few data quality issues worth pointing out above:" }, { "code": null, "e": 6859, "s": 6665, "text": "Space in-between the words i.e. “probl em”Missing characters i.e. “loked”Swapped characters i.e. “thsi”Double characters i.e. “thee”Combination of issues i.e. “m emry” — combination of 1 and 2." }, { "code": null, "e": 6902, "s": 6859, "text": "Space in-between the words i.e. “probl em”" }, { "code": null, "e": 6934, "s": 6902, "text": "Missing characters i.e. “loked”" }, { "code": null, "e": 6965, "s": 6934, "text": "Swapped characters i.e. “thsi”" }, { "code": null, "e": 6995, "s": 6965, "text": "Double characters i.e. “thee”" }, { "code": null, "e": 7057, "s": 6995, "text": "Combination of issues i.e. “m emry” — combination of 1 and 2." }, { "code": null, "e": 7191, "s": 7057, "text": "I had to find a way to resolve the spaces in-between words while at the same time, account for the misspellings (numbers 2, 3 and 4)." }, { "code": null, "e": 7304, "s": 7191, "text": "Thankfully, handling the misspellings can be taken care of relatively easily as I have shown above with tpSpell." }, { "code": null, "e": 7376, "s": 7304, "text": "But the complexity comes in with the combinations of issues (number 5)." }, { "code": null, "e": 7500, "s": 7376, "text": "For a combination problem like this, I first needed to resolve the white spaces before applying the misspelling resolution." }, { "code": null, "e": 7613, "s": 7500, "text": "While thinking about the best solution for the job, I took inspiration from how encoder-decoder networks worked." }, { "code": null, "e": 7677, "s": 7613, "text": "Could I somehow “encode” the sentences and “decode” them after?" }, { "code": null, "e": 7811, "s": 7677, "text": "Obviously I’m using the terms inappropriately here. By “encode” I actually meant to remove all white spaces between words. Like such:" }, { "code": null, "e": 7854, "s": 7811, "text": "torefreshyourmemrytheeproblemlokedlikethsi" }, { "code": null, "e": 7956, "s": 7854, "text": "By “decode”, I mean to break the words back into their individual words after resolving misspellings:" }, { "code": null, "e": 8008, "s": 7956, "text": "to refresh your memory the problem looked like this" }, { "code": null, "e": 8119, "s": 8008, "text": "One of the biggest problem I had to resolve was when to insert a white space once a string had been “encoded”." }, { "code": null, "e": 8160, "s": 8119, "text": "Take the words “torefresh” for instance." }, { "code": null, "e": 8263, "s": 8160, "text": "How would you know to insert a white space between “to” and “refresh”? Why not “to”, “re” and “fresh”?" }, { "code": null, "e": 8315, "s": 8263, "text": "Here’s how I did it and the logic of my SAS script." }, { "code": null, "e": 8374, "s": 8315, "text": "Decoded words are based off the longest match of the word." }, { "code": null, "e": 8542, "s": 8374, "text": "For example, if I saw the words “helloworld”, I am first going to perform a look up for the word “hell” in a predefined potential candidate list. i.e. dictionary table" }, { "code": null, "e": 8654, "s": 8542, "text": "Until the next character “o” appears, since “hell+o” = “hello”, “hello” becomes the better potential candidate." }, { "code": null, "e": 8748, "s": 8654, "text": "I drop the word “hell” as main candidate and keep the word “hello” as the new main candidate." }, { "code": null, "e": 8919, "s": 8748, "text": "As the next character gets read in, “hello+w” = “hellow”, since “hellow” is not a proper word in the potential candidate list, the best candidate to split off is “hello”." }, { "code": null, "e": 9072, "s": 8919, "text": "Once these checks are completed, I add a white space after “hello” and continue the logic above for “w”, “o”, “r”, “l” and “d” until I get “hello world”" }, { "code": null, "e": 9148, "s": 9072, "text": "So what is this potential candidate list and how did I get this dictionary?" }, { "code": null, "e": 9257, "s": 9148, "text": "It is a dictionary I created from the correctly-spelled word list generated from the tpSpell action earlier." }, { "code": null, "e": 9384, "s": 9257, "text": "Meaning to say, all correctly-spelled words are placed into this dictionary table for me to look up as I “decode” each string." }, { "code": null, "e": 9463, "s": 9384, "text": "There were other issues that needed to be resolved to make the “decoder” work." }, { "code": null, "e": 9576, "s": 9463, "text": "That is, I had to remove stop words, all forms of punctuation, lower cased all words and only keep parent terms." }, { "code": null, "e": 9581, "s": 9576, "text": "Why?" }, { "code": null, "e": 9654, "s": 9581, "text": "Because if I didn’t there would have been a lot of issues that surfaced." }, { "code": null, "e": 9687, "s": 9654, "text": "Take this sentence for instance:" }, { "code": null, "e": 9709, "s": 9687, "text": "“the series of books”" }, { "code": null, "e": 9738, "s": 9709, "text": "After “encoding” it will be:" }, { "code": null, "e": 9757, "s": 9738, "text": "“theseriesofbooks”" }, { "code": null, "e": 9866, "s": 9757, "text": "Recall that the algorithm I created takes the longest match in the dictionary during the “decoding” process." }, { "code": null, "e": 9965, "s": 9866, "text": "If I kept all stop words, the “decoder” would have parsed the first word as “these” and not “the”." }, { "code": null, "e": 10096, "s": 9965, "text": "Because of this, the next characters “ries” in the word “series” will no longer be a word in my dictionary, and will be discarded." }, { "code": null, "e": 10199, "s": 10096, "text": "This would mean the “decoded” string will end up being “these of books”, which is obviously incorrect." }, { "code": null, "e": 10271, "s": 10199, "text": "Another intricacy that affects the “decoder” looks something like this:" }, { "code": null, "e": 10333, "s": 10271, "text": "“bicycle sports” → “bicyclesports” → “bicycles ports” (wrong)" }, { "code": null, "e": 10405, "s": 10333, "text": "To counter this issue, I only kept parent terms in my dictionary table." }, { "code": null, "e": 10435, "s": 10405, "text": "Example 1: bicycles → bicycle" }, { "code": null, "e": 10461, "s": 10435, "text": "Example 2: sports → sport" }, { "code": null, "e": 10522, "s": 10461, "text": "By only looking at parent terms, my output looked like this:" }, { "code": null, "e": 10583, "s": 10522, "text": "“bicycle sport” → “bicyclesport” → “bicycle sport” (correct)" }, { "code": null, "e": 10719, "s": 10583, "text": "Because “bicycles” is no longer in my dictionary and “bicycle” is, the decoder parses it correctly and does not output “bicycles port”." }, { "code": null, "e": 10741, "s": 10719, "text": "So there you have it!" }, { "code": null, "e": 10829, "s": 10741, "text": "My very own “encoder-decoder” methodology to clean extremely dirty unstructured text! 😉" }, { "code": null, "e": 10940, "s": 10829, "text": "It’s not a perfect solution but it does get the job done enough for me to start my downstream NLP task proper." }, { "code": null, "e": 11100, "s": 10940, "text": "Just to show you an example of how the would look like after running the code, I ran the code against a books review corpus with mocked up data quality issues." }, { "code": null, "e": 11150, "s": 11100, "text": "Here’s how the sample and the process looks like:" }, { "code": null, "e": 11172, "s": 11150, "text": "Well, that’s it then!" }, { "code": null, "e": 11213, "s": 11172, "text": "I hope you found this post insightful! 😃" }, { "code": null, "e": 11306, "s": 11213, "text": "Albeit spending close to 2 weeks trying out many methodologies, I had tons of fun with this!" }, { "code": null, "e": 11332, "s": 11306, "text": "Till next time, farewell!" } ]
HTML - Attributes
We have seen few HTML tags and their usage like heading tags <h1>, <h2>, paragraph tag <p> and other tags. We used them so far in their simplest form, but most of the HTML tags can also have attributes, which are extra bits of information. An attribute is used to define the characteristics of an HTML element and is placed inside the element's opening tag. All attributes are made up of two parts − a name and a value The name is the property you want to set. For example, the paragraph <p> element in the example carries an attribute whose name is align, which you can use to indicate the alignment of paragraph on the page. The name is the property you want to set. For example, the paragraph <p> element in the example carries an attribute whose name is align, which you can use to indicate the alignment of paragraph on the page. The value is what you want the value of the property to be set and always put within quotations. The below example shows three possible values of align attribute: left, center and right. The value is what you want the value of the property to be set and always put within quotations. The below example shows three possible values of align attribute: left, center and right. Attribute names and attribute values are case-insensitive. However, the World Wide Web Consortium (W3C) recommends lowercase attributes/attribute values in their HTML 4 recommendation. <!DOCTYPE html> <html> <head> <title>Align Attribute Example</title> </head> <body> <p align = "left">This is left aligned</p> <p align = "center">This is center aligned</p> <p align = "right">This is right aligned</p> </body> </html> This will display the following result − This is left aligned This is center aligned This is right aligned The four core attributes that can be used on the majority of HTML elements (although not all) are − Id Title Class Style The id attribute of an HTML tag can be used to uniquely identify any element within an HTML page. There are two primary reasons that you might want to use an id attribute on an element − If an element carries an id attribute as a unique identifier, it is possible to identify just that element and its content. If an element carries an id attribute as a unique identifier, it is possible to identify just that element and its content. If you have two elements of the same name within a Web page (or style sheet), you can use the id attribute to distinguish between elements that have the same name. If you have two elements of the same name within a Web page (or style sheet), you can use the id attribute to distinguish between elements that have the same name. We will discuss style sheet in separate tutorial. For now, let's use the id attribute to distinguish between two paragraph elements as shown below. Example <p id = "html">This para explains what is HTML</p> <p id = "css">This para explains what is Cascading Style Sheet</p> The title attribute gives a suggested title for the element. They syntax for the title attribute is similar as explained for id attribute − The behavior of this attribute will depend upon the element that carries it, although it is often displayed as a tooltip when cursor comes over the element or while the element is loading. Example <!DOCTYPE html> <html> <head> <title>The title Attribute Example</title> </head> <body> <h3 title = "Hello HTML!">Titled Heading Tag Example</h3> </body> </html> This will produce the following result − Now try to bring your cursor over "Titled Heading Tag Example" and you will see that whatever title you used in your code is coming out as a tooltip of the cursor. The class attribute is used to associate an element with a style sheet, and specifies the class of element. You will learn more about the use of the class attribute when you will learn Cascading Style Sheet (CSS). So for now you can avoid it. The value of the attribute may also be a space-separated list of class names. For example − class = "className1 className2 className3" The style attribute allows you to specify Cascading Style Sheet (CSS) rules within the element. <!DOCTYPE html> <html> <head> <title>The style Attribute</title> </head> <body> <p style = "font-family:arial; color:#FF0000;">Some text...</p> </body> </html> This will produce the following result − Some text... At this point of time, we are not learning CSS, so just let's proceed without bothering much about CSS. Here, you need to understand what are HTML attributes and how they can be used while formatting content. There are three internationalization attributes, which are available for most (although not all) XHTML elements. dir lang xml:lang The dir attribute allows you to indicate to the browser about the direction in which the text should flow. The dir attribute can take one of two values, as you can see in the table that follows − Example <!DOCTYPE html> <html dir = "rtl"> <head> <title>Display Directions</title> </head> <body> This is how IE 5 renders right-to-left directed text. </body> </html> This will produce the following result − When dir attribute is used within the <html> tag, it determines how text will be presented within the entire document. When used within another tag, it controls the text's direction for just the content of that tag. The lang attribute allows you to indicate the main language used in a document, but this attribute was kept in HTML only for backwards compatibility with earlier versions of HTML. This attribute has been replaced by the xml:lang attribute in new XHTML documents. The values of the lang attribute are ISO-639 standard two-character language codes. Check HTML Language Codes: ISO 639 for a complete list of language codes. Example <!DOCTYPE html> <html lang = "en"> <head> <title>English Language Page</title> </head> <body> This page is using English Language </body> </html> This will produce the following result − The xml:lang attribute is the XHTML replacement for the lang attribute. The value of the xml:lang attribute should be an ISO-639 country code as mentioned in previous section. Here's a table of some other attributes that are readily usable with many of the HTML tags. We will see related examples as we will proceed to study other HTML tags. For a complete list of HTML Tags and related attributes please check reference to HTML Tags List. 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2614, "s": 2374, "text": "We have seen few HTML tags and their usage like heading tags <h1>, <h2>, paragraph tag <p> and other tags. We used them so far in their simplest form, but most of the HTML tags can also have attributes, which are extra bits of information." }, { "code": null, "e": 2793, "s": 2614, "text": "An attribute is used to define the characteristics of an HTML element and is placed inside the element's opening tag. All attributes are made up of two parts − a name and a value" }, { "code": null, "e": 3001, "s": 2793, "text": "The name is the property you want to set. For example, the paragraph <p> element in the example carries an attribute whose name is align, which you can use to indicate the alignment of paragraph on the page." }, { "code": null, "e": 3209, "s": 3001, "text": "The name is the property you want to set. For example, the paragraph <p> element in the example carries an attribute whose name is align, which you can use to indicate the alignment of paragraph on the page." }, { "code": null, "e": 3397, "s": 3209, "text": "The value is what you want the value of the property to be set and always put within quotations. The below example shows three possible values of align attribute: left, center and right." }, { "code": null, "e": 3585, "s": 3397, "text": "The value is what you want the value of the property to be set and always put within quotations. The below example shows three possible values of align attribute: left, center and right." }, { "code": null, "e": 3770, "s": 3585, "text": "Attribute names and attribute values are case-insensitive. However, the World Wide Web Consortium (W3C) recommends lowercase attributes/attribute values in their HTML 4 recommendation." }, { "code": null, "e": 4055, "s": 3770, "text": "<!DOCTYPE html> \n<html>\n \n <head> \n <title>Align Attribute Example</title> \n </head>\n\t\n <body> \n <p align = \"left\">This is left aligned</p> \n <p align = \"center\">This is center aligned</p> \n <p align = \"right\">This is right aligned</p> \n </body>\n\t\n</html>" }, { "code": null, "e": 4096, "s": 4055, "text": "This will display the following result −" }, { "code": null, "e": 4117, "s": 4096, "text": "This is left aligned" }, { "code": null, "e": 4140, "s": 4117, "text": "This is center aligned" }, { "code": null, "e": 4162, "s": 4140, "text": "This is right aligned" }, { "code": null, "e": 4262, "s": 4162, "text": "The four core attributes that can be used on the majority of HTML elements (although not all) are −" }, { "code": null, "e": 4265, "s": 4262, "text": "Id" }, { "code": null, "e": 4271, "s": 4265, "text": "Title" }, { "code": null, "e": 4277, "s": 4271, "text": "Class" }, { "code": null, "e": 4283, "s": 4277, "text": "Style" }, { "code": null, "e": 4470, "s": 4283, "text": "The id attribute of an HTML tag can be used to uniquely identify any element within an HTML page. There are two primary reasons that you might want to use an id attribute on an element −" }, { "code": null, "e": 4594, "s": 4470, "text": "If an element carries an id attribute as a unique identifier, it is possible to identify just that element and its content." }, { "code": null, "e": 4718, "s": 4594, "text": "If an element carries an id attribute as a unique identifier, it is possible to identify just that element and its content." }, { "code": null, "e": 4882, "s": 4718, "text": "If you have two elements of the same name within a Web page (or style sheet), you can use the id attribute to distinguish between elements that have the same name." }, { "code": null, "e": 5046, "s": 4882, "text": "If you have two elements of the same name within a Web page (or style sheet), you can use the id attribute to distinguish between elements that have the same name." }, { "code": null, "e": 5194, "s": 5046, "text": "We will discuss style sheet in separate tutorial. For now, let's use the id attribute to distinguish between two paragraph elements as shown below." }, { "code": null, "e": 5202, "s": 5194, "text": "Example" }, { "code": null, "e": 5321, "s": 5202, "text": "<p id = \"html\">This para explains what is HTML</p>\n<p id = \"css\">This para explains what is Cascading Style Sheet</p>\n" }, { "code": null, "e": 5461, "s": 5321, "text": "The title attribute gives a suggested title for the element. They syntax for the title attribute is similar as explained for id attribute −" }, { "code": null, "e": 5650, "s": 5461, "text": "The behavior of this attribute will depend upon the element that carries it, although it is often displayed as a tooltip when cursor comes over the element or while the element is loading." }, { "code": null, "e": 5658, "s": 5650, "text": "Example" }, { "code": null, "e": 5849, "s": 5658, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>The title Attribute Example</title>\n </head>\n\t\n <body>\n <h3 title = \"Hello HTML!\">Titled Heading Tag Example</h3>\n </body>\n\t\n</html>" }, { "code": null, "e": 5890, "s": 5849, "text": "This will produce the following result −" }, { "code": null, "e": 6054, "s": 5890, "text": "Now try to bring your cursor over \"Titled Heading Tag Example\" and you will see that whatever title you used in your code is coming out as a tooltip of the cursor." }, { "code": null, "e": 6297, "s": 6054, "text": "The class attribute is used to associate an element with a style sheet, and specifies the class of element. You will learn more about the use of the class attribute when you will learn Cascading Style Sheet (CSS). So for now you can avoid it." }, { "code": null, "e": 6389, "s": 6297, "text": "The value of the attribute may also be a space-separated list of class names. For example −" }, { "code": null, "e": 6433, "s": 6389, "text": "class = \"className1 className2 className3\"\n" }, { "code": null, "e": 6529, "s": 6433, "text": "The style attribute allows you to specify Cascading Style Sheet (CSS) rules within the element." }, { "code": null, "e": 6718, "s": 6529, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>The style Attribute</title>\n </head>\n\t\n <body>\n <p style = \"font-family:arial; color:#FF0000;\">Some text...</p>\n </body>\n\t\n</html>" }, { "code": null, "e": 6759, "s": 6718, "text": "This will produce the following result −" }, { "code": null, "e": 6772, "s": 6759, "text": "Some text..." }, { "code": null, "e": 6981, "s": 6772, "text": "At this point of time, we are not learning CSS, so just let's proceed without bothering much about CSS. Here, you need to understand what are HTML attributes and how they can be used while formatting content." }, { "code": null, "e": 7094, "s": 6981, "text": "There are three internationalization attributes, which are available for most (although not all) XHTML elements." }, { "code": null, "e": 7098, "s": 7094, "text": "dir" }, { "code": null, "e": 7103, "s": 7098, "text": "lang" }, { "code": null, "e": 7113, "s": 7103, "text": "xml:lang " }, { "code": null, "e": 7309, "s": 7113, "text": "The dir attribute allows you to indicate to the browser about the direction in which the text should flow. The dir attribute can take one of two values, as you can see in the table that follows −" }, { "code": null, "e": 7317, "s": 7309, "text": "Example" }, { "code": null, "e": 7507, "s": 7317, "text": "<!DOCTYPE html>\n<html dir = \"rtl\">\n\n <head>\n <title>Display Directions</title>\n </head>\n\t\n <body>\n This is how IE 5 renders right-to-left directed text.\n </body>\n\t\n</html>" }, { "code": null, "e": 7548, "s": 7507, "text": "This will produce the following result −" }, { "code": null, "e": 7764, "s": 7548, "text": "When dir attribute is used within the <html> tag, it determines how text will be presented within the entire document. When used within another tag, it controls the text's direction for just the content of that tag." }, { "code": null, "e": 8027, "s": 7764, "text": "The lang attribute allows you to indicate the main language used in a document, but this attribute was kept in HTML only for backwards compatibility with earlier versions of HTML. This attribute has been replaced by the xml:lang attribute in new XHTML documents." }, { "code": null, "e": 8185, "s": 8027, "text": "The values of the lang attribute are ISO-639 standard two-character language codes. Check HTML Language Codes: ISO 639 for a complete list of language codes." }, { "code": null, "e": 8193, "s": 8185, "text": "Example" }, { "code": null, "e": 8366, "s": 8193, "text": "<!DOCTYPE html>\n<html lang = \"en\">\n\n <head>\n <title>English Language Page</title>\n </head>\n\n <body>\n This page is using English Language\n </body>\n\n</html>" }, { "code": null, "e": 8407, "s": 8366, "text": "This will produce the following result −" }, { "code": null, "e": 8583, "s": 8407, "text": "The xml:lang attribute is the XHTML replacement for the lang attribute. The value of the xml:lang attribute should be an ISO-639 country code as mentioned in previous section." }, { "code": null, "e": 8675, "s": 8583, "text": "Here's a table of some other attributes that are readily usable with many of the HTML tags." }, { "code": null, "e": 8847, "s": 8675, "text": "We will see related examples as we will proceed to study other HTML tags. For a complete list of HTML Tags and related attributes please check reference to HTML Tags List." }, { "code": null, "e": 8880, "s": 8847, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 8894, "s": 8880, "text": " Anadi Sharma" }, { "code": null, "e": 8929, "s": 8894, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8943, "s": 8929, "text": " Anadi Sharma" }, { "code": null, "e": 8978, "s": 8943, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8995, "s": 8978, "text": " Frahaan Hussain" }, { "code": null, "e": 9030, "s": 8995, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9061, "s": 9030, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 9094, "s": 9061, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 9125, "s": 9094, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 9160, "s": 9125, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9191, "s": 9160, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 9198, "s": 9191, "text": " Print" }, { "code": null, "e": 9209, "s": 9198, "text": " Add Notes" } ]
CSS - list-style-type
The list-style-type property sets the counting (or bullet) style used in the marker for a list item. Here are the values which can be used for an unordered list − none NA disc (default) A filled-in circle circle An empty circle square A filled-in square Here are the values which can be used for an ordered list − All the elements with a display of list-item. object.style.listStyleType = "decimal" Here is the example − <html> <head> </head> <body> <ul style = "list-style-type:circle;"> <li>Maths</li> <li>Social Science</li> <li>Physics</li> </ul> <ul style = "list-style-type:square;"> <li>Maths</li> <li>Social Science</li> <li>Physics</li> </ul> <ol style = "list-style-type:decimal;"> <li>Maths</li> <li>Social Science</li> <li>Physics</li> </ol> <ol style = "list-style-type:lower-alpha;"> <li>Maths</li> <li>Social Science</li> <li>Physics</li> </ol> <ol style = "list-style-type:lower-roman;"> <li>Maths</li> <li>Social Science</li> <li>Physics</li> </ol> </body> </html> This will produce following result − Maths Social Science Physics Maths Social Science Physics Maths Social Science Physics Maths Social Science Physics Maths Social Science Physics Maths Social Science Physics Maths Social Science Physics Maths Social Science Physics 33 Lectures 2.5 hours Anadi Sharma 26 Lectures 2.5 hours Frahaan Hussain 44 Lectures 4.5 hours DigiFisk (Programming Is Fun) 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 51 Lectures 7.5 hours DigiFisk (Programming Is Fun) 52 Lectures 4 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2727, "s": 2626, "text": "The list-style-type property sets the counting (or bullet) style used in the marker for a list item." }, { "code": null, "e": 2789, "s": 2727, "text": "Here are the values which can be used for an unordered list −" }, { "code": null, "e": 2794, "s": 2789, "text": "none" }, { "code": null, "e": 2797, "s": 2794, "text": "NA" }, { "code": null, "e": 2812, "s": 2797, "text": "disc (default)" }, { "code": null, "e": 2831, "s": 2812, "text": "A filled-in circle" }, { "code": null, "e": 2838, "s": 2831, "text": "circle" }, { "code": null, "e": 2854, "s": 2838, "text": "An empty circle" }, { "code": null, "e": 2861, "s": 2854, "text": "square" }, { "code": null, "e": 2880, "s": 2861, "text": "A filled-in square" }, { "code": null, "e": 2940, "s": 2880, "text": "Here are the values which can be used for an ordered list −" }, { "code": null, "e": 2986, "s": 2940, "text": "All the elements with a display of list-item." }, { "code": null, "e": 3026, "s": 2986, "text": "object.style.listStyleType = \"decimal\"\n" }, { "code": null, "e": 3048, "s": 3026, "text": "Here is the example −" }, { "code": null, "e": 3853, "s": 3048, "text": "<html>\n <head>\n </head>\n \n <body>\n <ul style = \"list-style-type:circle;\">\n <li>Maths</li>\n <li>Social Science</li>\n <li>Physics</li>\n </ul>\n \n <ul style = \"list-style-type:square;\">\n <li>Maths</li>\n <li>Social Science</li>\n <li>Physics</li>\n </ul>\n \n <ol style = \"list-style-type:decimal;\">\n <li>Maths</li>\n <li>Social Science</li>\n <li>Physics</li>\n </ol>\n \n <ol style = \"list-style-type:lower-alpha;\">\n <li>Maths</li>\n <li>Social Science</li>\n <li>Physics</li>\n </ol>\n \n <ol style = \"list-style-type:lower-roman;\">\n <li>Maths</li>\n <li>Social Science</li>\n <li>Physics</li>\n </ol>\n \n </body>\n</html> " }, { "code": null, "e": 3890, "s": 3853, "text": "This will produce following result −" }, { "code": null, "e": 3896, "s": 3890, "text": "Maths" }, { "code": null, "e": 3911, "s": 3896, "text": "Social Science" }, { "code": null, "e": 3919, "s": 3911, "text": "Physics" }, { "code": null, "e": 3925, "s": 3919, "text": "Maths" }, { "code": null, "e": 3940, "s": 3925, "text": "Social Science" }, { "code": null, "e": 3948, "s": 3940, "text": "Physics" }, { "code": null, "e": 3979, "s": 3948, "text": "\nMaths\nSocial Science\nPhysics\n" }, { "code": null, "e": 3985, "s": 3979, "text": "Maths" }, { "code": null, "e": 4000, "s": 3985, "text": "Social Science" }, { "code": null, "e": 4008, "s": 4000, "text": "Physics" }, { "code": null, "e": 4039, "s": 4008, "text": "\nMaths\nSocial Science\nPhysics\n" }, { "code": null, "e": 4045, "s": 4039, "text": "Maths" }, { "code": null, "e": 4060, "s": 4045, "text": "Social Science" }, { "code": null, "e": 4068, "s": 4060, "text": "Physics" }, { "code": null, "e": 4099, "s": 4068, "text": "\nMaths\nSocial Science\nPhysics\n" }, { "code": null, "e": 4105, "s": 4099, "text": "Maths" }, { "code": null, "e": 4120, "s": 4105, "text": "Social Science" }, { "code": null, "e": 4128, "s": 4120, "text": "Physics" }, { "code": null, "e": 4163, "s": 4128, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4177, "s": 4163, "text": " Anadi Sharma" }, { "code": null, "e": 4212, "s": 4177, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4229, "s": 4212, "text": " Frahaan Hussain" }, { "code": null, "e": 4264, "s": 4229, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4295, "s": 4264, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4330, "s": 4295, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4361, "s": 4330, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4396, "s": 4361, "text": "\n 51 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4427, "s": 4396, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4460, "s": 4427, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 4491, "s": 4460, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 4498, "s": 4491, "text": " Print" }, { "code": null, "e": 4509, "s": 4498, "text": " Add Notes" } ]
SQL Query to Get a Financial Year Using a Given Date
17 Jun, 2021 Here, we are going to Get a Financial Year Using a Given Date in SQL. In this article, we will be making use of the Microsoft SQL Server as our database. For example, finding the Financial year for the give dates in the table. Here, we will first create a database named “geeks” then we will create a table “department” in that database. After, that we will execute our query on that table. CREATE DATABASE geeks; USE geeks; CREATE TABLE [dbo].[department]( [ID] [int] NULL, [SALARY] [int] NULL, [NAME] [varchar](20) NULL, [JoinDate] [datetime] NULL ) ON [PRIMARY] GO INSERT INTO [dbo].[department] VALUES ( 1, 34000, 'Neha', '2013-09-24') INSERT INTO [dbo].[department] VALUES ( 2, 33000, 'Hema', '2015-02-0' ) INSERT INTO [dbo].[department] VALUES ( 3, 36000, 'Jaya', '2017-09-09' ) INSERT INTO [dbo].[department] VALUES ( 4, 35000, 'Priya', '2018-05-18' ) INSERT INTO [dbo].[department] VALUES ( 5, 34000, 'Ketan', '2019-02-25' ) GO This is our data inside the table: SELECT * FROM department; To check the current financial year using SQL query: DECLARE @FIYear VARCHAR(20) SELECT @FIYear = (CASE WHEN (MONTH(GETDATE())) <= 3 THEN convert(varchar(4), YEAR(GETDATE())-1) + '-' + convert(varchar(4), YEAR(GETDATE())%100) ELSE convert(varchar(4),YEAR(GETDATE()))+ '-' + convert(varchar(4),(YEAR(GETDATE())%100)+1)END) SELECT @FIYear AS F_YEAR Output: To Get a Financial Year Using a Given Date in Table: SELECT (CASE WHEN (MONTH(JoinDate)) <=3 THEN convert(varchar(4), YEAR(JoinDate)-1) + '-' + convert(varchar(4), YEAR(JoinDate)%100) ELSE convert(varchar(4),YEAR(JoinDate))+ '-' + convert(varchar(4), (YEAR(JoinDate)%100)+1)END) AS FinancialYear , * FROM [test].[dbo].[department] Output: surinderdawra388 Picked SQL-Query SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2021" }, { "code": null, "e": 183, "s": 28, "text": "Here, we are going to Get a Financial Year Using a Given Date in SQL. In this article, we will be making use of the Microsoft SQL Server as our database." }, { "code": null, "e": 420, "s": 183, "text": "For example, finding the Financial year for the give dates in the table. Here, we will first create a database named “geeks” then we will create a table “department” in that database. After, that we will execute our query on that table." }, { "code": null, "e": 443, "s": 420, "text": "CREATE DATABASE geeks;" }, { "code": null, "e": 454, "s": 443, "text": "USE geeks;" }, { "code": null, "e": 597, "s": 454, "text": "CREATE TABLE [dbo].[department](\n[ID] [int] NULL,\n[SALARY] [int] NULL,\n[NAME] [varchar](20) NULL,\n[JoinDate] [datetime] NULL\n) ON [PRIMARY]\nGO" }, { "code": null, "e": 972, "s": 597, "text": "INSERT INTO [dbo].[department] VALUES ( 1, 34000, 'Neha', '2013-09-24') \nINSERT INTO [dbo].[department] VALUES ( 2, 33000, 'Hema', '2015-02-0' )\nINSERT INTO [dbo].[department] VALUES ( 3, 36000, 'Jaya', '2017-09-09' )\nINSERT INTO [dbo].[department] VALUES ( 4, 35000, 'Priya', '2018-05-18' )\nINSERT INTO [dbo].[department] VALUES ( 5, 34000, 'Ketan', '2019-02-25' )\nGO" }, { "code": null, "e": 1007, "s": 972, "text": "This is our data inside the table:" }, { "code": null, "e": 1033, "s": 1007, "text": "SELECT * FROM department;" }, { "code": null, "e": 1086, "s": 1033, "text": "To check the current financial year using SQL query:" }, { "code": null, "e": 1400, "s": 1086, "text": "DECLARE @FIYear VARCHAR(20) \n SELECT @FIYear = (CASE WHEN (MONTH(GETDATE()))\n <= 3 THEN convert(varchar(4), YEAR(GETDATE())-1) + '-' + convert(varchar(4), YEAR(GETDATE())%100)\n ELSE convert(varchar(4),YEAR(GETDATE()))+ '-' + convert(varchar(4),(YEAR(GETDATE())%100)+1)END) \n SELECT @FIYear AS F_YEAR " }, { "code": null, "e": 1408, "s": 1400, "text": "Output:" }, { "code": null, "e": 1462, "s": 1408, "text": "To Get a Financial Year Using a Given Date in Table: " }, { "code": null, "e": 1757, "s": 1462, "text": " SELECT (CASE WHEN (MONTH(JoinDate)) <=3 THEN convert(varchar(4),\n YEAR(JoinDate)-1) + '-' + convert(varchar(4), YEAR(JoinDate)%100) \n ELSE convert(varchar(4),YEAR(JoinDate))+ '-' + convert(varchar(4),\n(YEAR(JoinDate)%100)+1)END) AS FinancialYear ,\n* FROM [test].[dbo].[department] " }, { "code": null, "e": 1765, "s": 1757, "text": "Output:" }, { "code": null, "e": 1782, "s": 1765, "text": "surinderdawra388" }, { "code": null, "e": 1789, "s": 1782, "text": "Picked" }, { "code": null, "e": 1799, "s": 1789, "text": "SQL-Query" }, { "code": null, "e": 1803, "s": 1799, "text": "SQL" }, { "code": null, "e": 1807, "s": 1803, "text": "SQL" } ]
Scraping weather data using Python to get umbrella reminder on email
05 Oct, 2021 In this article, we are going to see how to scrape weather data using Python and get reminders on email. If the weather condition is rainy or cloudy this program will send you an “umbrella reminder” to your email reminding you to pack an umbrella before leaving the house. We will scrape the weather information from Google using bs4 and requests libraries in python. Then based on the weather conditions we will send the email using smtplib library. To run this program every day at a specified time we will use the schedule library in python. bs4: Beautiful Soup (bs4) is a Python library for extracting data from HTML and XML files. To install this library, type the following command in IDE/terminal. pip install bs4 requests: This library allows you to send HTTP/1.1 requests very easily. To install this library, type the following command in IDE/terminal. pip install requests smtplib: smtplib is a Python module that defines an SMTP client session object, which can be used to send mail to any machine on the Internet. To install this library, type the following command in the IDE/terminal. pip install smtplib schedule: A schedule is a Python library used to schedule tasks at specific times of the day or specific days of the week. To install this library, type the following command in the IDE/terminal. pip install schedule Step 1: Import schedule, smtplib, requests, and bs4 libraries. Python3 import scheduleimport smtplib import requestsfrom bs4 import BeautifulSoup Step 2: Create a URL with the specified city name and create a requests instance bypassing this URL. Python3 city = "Hyderabad"url = "https://www.google.com/search?q=" + "weather" + cityhtml = requests.get(url).content Step 3: Pass the retrieved HTML document into Beautiful Soup which will return a string stripped of HTML tags and metadata. Using the find function we will retrieve all the necessary data. Python3 soup = BeautifulSoup(html, 'html.parser')temperature = soup.find( 'div', attrs={'class': 'BNeawe iBp4i AP7Wnd'}).texttime_sky = soup.find( 'div', attrs={'class': 'BNeawe tAd8D AP7Wnd'}).text # formatting datasky = time_sky.split('\n')[1] Step 4: If the weather condition turns out to be rainy or cloudy, this program will send an email with an “umbrella reminder” message to the recipient. To encapsulate an SMTP connection I have created an SMTP object with the parameters `smtp.gmail.com` and 587. After creating the SMTP object, you can log in with your email address and password. Note: Different websites use different port numbers. In this article, we are using a Gmail account to send emails. The port number used here is “587”. If you want to send mail using a website other than Gmail, you need to obtain the corresponding information. Python3 if sky == "Rainy" or sky == "Rain And Snow" or sky == "Showers" or sky == "Haze" or sky == "Cloudy": smtp_object = smtplib.SMTP('smtp.gmail.com', 587) Step 5: For security reasons, the SMTP connection is now placed in TLS mode. Transport Layer Security encrypts all SMTP commands. After that, for authentication purposes, you need to pass your Gmail account credentials in the login instance. If you enter an invalid email ID or password, the compiler will display an authentication error. Save the message you need to send to a variable, like msg. Use the sendmail() instance to send your message. sendmail() uses three parameters: sender_email_id, receiver_email_id, and message_to_be_sent. The order of these three parameters must be the same. This will send an email from your account. After completing the task, use quit () to end the SMTP session. Python3 # start TLS for securitysmtp_object.starttls()# Authenticationsmtp_object.login("YOUR EMAIL", "PASSWORD")subject = "Umbrella Reminder"body = f"Take an umbrella before leaving the house.\Weather condition for today is ", { sky}, " and temperature is {temperature} in {city}."msg = f"Subject:{subject}\n\n{body}\n\nRegards,\\nGeeksforGeeks".encode('utf-8') # sending the mailsmtp_object.sendmail("FROM EMAIL ADDRESS", "TO EMAIL ADDRESS", msg)# terminating the sessionsmtp_object.quit()print("Email Sent!") Step 6: Using the schedule library, Schedule the task every day at a specific time. schedule.run_pending() Checks whether a scheduled task is pending to run or not. Python3 # Every day at 06:00AM time umbrellaReminder() is called.schedule.every().day.at("06:00").do(umbrellaReminder) while True: schedule.run_pending() Note: When you execute this program it will throw you a smtplib.SMTPAuthenticationError and also sends you a Critical Security alert to your email because, In a nutshell, Google is not allowing you to log in via smtplib because it has flagged this sort of login as “less secure”, so what you have to do is go to this link while you’re logged in to your google account, and allow the access: Below is the full implementation: Python3 import scheduleimport smtplibimport requestsfrom bs4 import BeautifulSoup def umbrellaReminder(): city = "Hyderabad" # creating url and requests instance url = "https://www.google.com/search?q=" + "weather" + city html = requests.get(url).content # getting raw data soup = BeautifulSoup(html, 'html.parser') temperature = soup.find('div', attrs={'class': 'BNeawe iBp4i AP7Wnd'}).text time_sky = soup.find('div', attrs={'class': 'BNeawe tAd8D AP7Wnd'}).text # formatting data sky = time_sky.split('\n')[1] if sky == "Rainy" or sky == "Rain And Snow" or sky == "Showers" or sky == "Haze" or sky == "Cloudy": smtp_object = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security smtp_object.starttls() # Authentication smtp_object.login("YOUR EMAIL", "PASSWORD") subject = "GeeksforGeeks Umbrella Reminder" body = f"Take an umbrella before leaving the house.\ Weather condition for today is {sky} and temperature is\ {temperature} in {city}." msg = f"Subject:{subject}\n\n{body}\n\nRegards,\nGeeksforGeeks".encode( 'utf-8') # sending the mail smtp_object.sendmail("FROM EMAIL", "TO EMAIL", msg) # terminating the session smtp_object.quit() print("Email Sent!") # Every day at 06:00AM time umbrellaReminder() is called.schedule.every().day.at("06:00").do(umbrellaReminder) while True: schedule.run_pending() Output: Sample Umbrella Reminder Email Picked Python BeautifulSoup Python-requests python-utility Web-scraping Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Oct, 2021" }, { "code": null, "e": 424, "s": 54, "text": "In this article, we are going to see how to scrape weather data using Python and get reminders on email. If the weather condition is rainy or cloudy this program will send you an “umbrella reminder” to your email reminding you to pack an umbrella before leaving the house. We will scrape the weather information from Google using bs4 and requests libraries in python. " }, { "code": null, "e": 601, "s": 424, "text": "Then based on the weather conditions we will send the email using smtplib library. To run this program every day at a specified time we will use the schedule library in python." }, { "code": null, "e": 761, "s": 601, "text": "bs4: Beautiful Soup (bs4) is a Python library for extracting data from HTML and XML files. To install this library, type the following command in IDE/terminal." }, { "code": null, "e": 777, "s": 761, "text": "pip install bs4" }, { "code": null, "e": 919, "s": 777, "text": "requests: This library allows you to send HTTP/1.1 requests very easily. To install this library, type the following command in IDE/terminal." }, { "code": null, "e": 940, "s": 919, "text": "pip install requests" }, { "code": null, "e": 1156, "s": 940, "text": "smtplib: smtplib is a Python module that defines an SMTP client session object, which can be used to send mail to any machine on the Internet. To install this library, type the following command in the IDE/terminal." }, { "code": null, "e": 1176, "s": 1156, "text": "pip install smtplib" }, { "code": null, "e": 1372, "s": 1176, "text": "schedule: A schedule is a Python library used to schedule tasks at specific times of the day or specific days of the week. To install this library, type the following command in the IDE/terminal." }, { "code": null, "e": 1393, "s": 1372, "text": "pip install schedule" }, { "code": null, "e": 1456, "s": 1393, "text": "Step 1: Import schedule, smtplib, requests, and bs4 libraries." }, { "code": null, "e": 1464, "s": 1456, "text": "Python3" }, { "code": "import scheduleimport smtplib import requestsfrom bs4 import BeautifulSoup", "e": 1541, "s": 1464, "text": null }, { "code": null, "e": 1642, "s": 1541, "text": "Step 2: Create a URL with the specified city name and create a requests instance bypassing this URL." }, { "code": null, "e": 1650, "s": 1642, "text": "Python3" }, { "code": "city = \"Hyderabad\"url = \"https://www.google.com/search?q=\" + \"weather\" + cityhtml = requests.get(url).content", "e": 1760, "s": 1650, "text": null }, { "code": null, "e": 1951, "s": 1760, "text": "Step 3: Pass the retrieved HTML document into Beautiful Soup which will return a string stripped of HTML tags and metadata. Using the find function we will retrieve all the necessary data." }, { "code": null, "e": 1959, "s": 1951, "text": "Python3" }, { "code": "soup = BeautifulSoup(html, 'html.parser')temperature = soup.find( 'div', attrs={'class': 'BNeawe iBp4i AP7Wnd'}).texttime_sky = soup.find( 'div', attrs={'class': 'BNeawe tAd8D AP7Wnd'}).text # formatting datasky = time_sky.split('\\n')[1]", "e": 2220, "s": 1959, "text": null }, { "code": null, "e": 2567, "s": 2220, "text": "Step 4: If the weather condition turns out to be rainy or cloudy, this program will send an email with an “umbrella reminder” message to the recipient. To encapsulate an SMTP connection I have created an SMTP object with the parameters `smtp.gmail.com` and 587. After creating the SMTP object, you can log in with your email address and password." }, { "code": null, "e": 2827, "s": 2567, "text": "Note: Different websites use different port numbers. In this article, we are using a Gmail account to send emails. The port number used here is “587”. If you want to send mail using a website other than Gmail, you need to obtain the corresponding information." }, { "code": null, "e": 2835, "s": 2827, "text": "Python3" }, { "code": "if sky == \"Rainy\" or sky == \"Rain And Snow\" or sky == \"Showers\" or sky == \"Haze\" or sky == \"Cloudy\": smtp_object = smtplib.SMTP('smtp.gmail.com', 587)", "e": 2989, "s": 2835, "text": null }, { "code": null, "e": 3330, "s": 2989, "text": "Step 5: For security reasons, the SMTP connection is now placed in TLS mode. Transport Layer Security encrypts all SMTP commands. After that, for authentication purposes, you need to pass your Gmail account credentials in the login instance. If you enter an invalid email ID or password, the compiler will display an authentication error. " }, { "code": null, "e": 3694, "s": 3330, "text": "Save the message you need to send to a variable, like msg. Use the sendmail() instance to send your message. sendmail() uses three parameters: sender_email_id, receiver_email_id, and message_to_be_sent. The order of these three parameters must be the same. This will send an email from your account. After completing the task, use quit () to end the SMTP session." }, { "code": null, "e": 3702, "s": 3694, "text": "Python3" }, { "code": "# start TLS for securitysmtp_object.starttls()# Authenticationsmtp_object.login(\"YOUR EMAIL\", \"PASSWORD\")subject = \"Umbrella Reminder\"body = f\"Take an umbrella before leaving the house.\\Weather condition for today is \", { sky}, \" and temperature is {temperature} in {city}.\"msg = f\"Subject:{subject}\\n\\n{body}\\n\\nRegards,\\\\nGeeksforGeeks\".encode('utf-8') # sending the mailsmtp_object.sendmail(\"FROM EMAIL ADDRESS\", \"TO EMAIL ADDRESS\", msg)# terminating the sessionsmtp_object.quit()print(\"Email Sent!\")", "e": 4230, "s": 3702, "text": null }, { "code": null, "e": 4396, "s": 4230, "text": "Step 6: Using the schedule library, Schedule the task every day at a specific time. schedule.run_pending() Checks whether a scheduled task is pending to run or not." }, { "code": null, "e": 4404, "s": 4396, "text": "Python3" }, { "code": "# Every day at 06:00AM time umbrellaReminder() is called.schedule.every().day.at(\"06:00\").do(umbrellaReminder) while True: schedule.run_pending()", "e": 4554, "s": 4404, "text": null }, { "code": null, "e": 4945, "s": 4554, "text": "Note: When you execute this program it will throw you a smtplib.SMTPAuthenticationError and also sends you a Critical Security alert to your email because, In a nutshell, Google is not allowing you to log in via smtplib because it has flagged this sort of login as “less secure”, so what you have to do is go to this link while you’re logged in to your google account, and allow the access:" }, { "code": null, "e": 4979, "s": 4945, "text": "Below is the full implementation:" }, { "code": null, "e": 4987, "s": 4979, "text": "Python3" }, { "code": "import scheduleimport smtplibimport requestsfrom bs4 import BeautifulSoup def umbrellaReminder(): city = \"Hyderabad\" # creating url and requests instance url = \"https://www.google.com/search?q=\" + \"weather\" + city html = requests.get(url).content # getting raw data soup = BeautifulSoup(html, 'html.parser') temperature = soup.find('div', attrs={'class': 'BNeawe iBp4i AP7Wnd'}).text time_sky = soup.find('div', attrs={'class': 'BNeawe tAd8D AP7Wnd'}).text # formatting data sky = time_sky.split('\\n')[1] if sky == \"Rainy\" or sky == \"Rain And Snow\" or sky == \"Showers\" or sky == \"Haze\" or sky == \"Cloudy\": smtp_object = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security smtp_object.starttls() # Authentication smtp_object.login(\"YOUR EMAIL\", \"PASSWORD\") subject = \"GeeksforGeeks Umbrella Reminder\" body = f\"Take an umbrella before leaving the house.\\ Weather condition for today is {sky} and temperature is\\ {temperature} in {city}.\" msg = f\"Subject:{subject}\\n\\n{body}\\n\\nRegards,\\nGeeksforGeeks\".encode( 'utf-8') # sending the mail smtp_object.sendmail(\"FROM EMAIL\", \"TO EMAIL\", msg) # terminating the session smtp_object.quit() print(\"Email Sent!\") # Every day at 06:00AM time umbrellaReminder() is called.schedule.every().day.at(\"06:00\").do(umbrellaReminder) while True: schedule.run_pending()", "e": 6595, "s": 4987, "text": null }, { "code": null, "e": 6603, "s": 6595, "text": "Output:" }, { "code": null, "e": 6634, "s": 6603, "text": "Sample Umbrella Reminder Email" }, { "code": null, "e": 6641, "s": 6634, "text": "Picked" }, { "code": null, "e": 6662, "s": 6641, "text": "Python BeautifulSoup" }, { "code": null, "e": 6678, "s": 6662, "text": "Python-requests" }, { "code": null, "e": 6693, "s": 6678, "text": "python-utility" }, { "code": null, "e": 6706, "s": 6693, "text": "Web-scraping" }, { "code": null, "e": 6713, "s": 6706, "text": "Python" } ]
Microsoft Azure – Graph Query to Get Properties of Azure VM Resource
29 Dec, 2021 The following are the Azure Resource Graph Queries where we will be used to fetch the static JSON data using azure KQL Queries. You can run the below queries in Azure Resource Graph Explorer in Azure Portal to fetch the results based on Query. Example 1: To get the complete properties of Azure VMs – resources | where type == "microsoft.compute/virtualmachines" This query returns the details and the total number of results. id name type tenantId kind location resourceGroup subscriptionId managedBy sku plan properties tags identity zones extendedLocation Sample Output: Example 2: To get the properties of Azure VM Name, Resource Group, VM Admin User Name of all the VMs from the select scope. resources | where type == "microsoft.compute/virtualmachines" | project name,resourceGroup,AdminUserName=tostring(properties.osProfile.adminUsername) This query returns the output of VM Computer Name, Resource Group, and VM Admin Admin User Name of all the Azure VMs from the scope selected. Sample Output: Example 3: To get the properties of Azure VM Name, Resource Group, VM Admin User Name of a specific Azure VM from the select scope. resources | where type == "microsoft.compute/virtualmachines" | where name == "CloudOpsVM" | project name,resourceGroup,AdminUserName=tostring(properties.osProfile.adminUsername) this query returns the output of VM Computer Name, Resource Group, and VM Admin Admin User Name of a Specific select VM. Sample Output: azure-virtual-machine Cloud-Computing Microsoft Azure Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Dec, 2021" }, { "code": null, "e": 272, "s": 28, "text": "The following are the Azure Resource Graph Queries where we will be used to fetch the static JSON data using azure KQL Queries. You can run the below queries in Azure Resource Graph Explorer in Azure Portal to fetch the results based on Query." }, { "code": null, "e": 283, "s": 272, "text": "Example 1:" }, { "code": null, "e": 329, "s": 283, "text": "To get the complete properties of Azure VMs –" }, { "code": null, "e": 391, "s": 329, "text": "resources\n| where type == \"microsoft.compute/virtualmachines\"" }, { "code": null, "e": 455, "s": 391, "text": "This query returns the details and the total number of results." }, { "code": null, "e": 458, "s": 455, "text": "id" }, { "code": null, "e": 463, "s": 458, "text": "name" }, { "code": null, "e": 468, "s": 463, "text": "type" }, { "code": null, "e": 477, "s": 468, "text": "tenantId" }, { "code": null, "e": 482, "s": 477, "text": "kind" }, { "code": null, "e": 491, "s": 482, "text": "location" }, { "code": null, "e": 505, "s": 491, "text": "resourceGroup" }, { "code": null, "e": 520, "s": 505, "text": "subscriptionId" }, { "code": null, "e": 530, "s": 520, "text": "managedBy" }, { "code": null, "e": 534, "s": 530, "text": "sku" }, { "code": null, "e": 539, "s": 534, "text": "plan" }, { "code": null, "e": 550, "s": 539, "text": "properties" }, { "code": null, "e": 555, "s": 550, "text": "tags" }, { "code": null, "e": 564, "s": 555, "text": "identity" }, { "code": null, "e": 570, "s": 564, "text": "zones" }, { "code": null, "e": 587, "s": 570, "text": "extendedLocation" }, { "code": null, "e": 602, "s": 587, "text": "Sample Output:" }, { "code": null, "e": 726, "s": 602, "text": "Example 2: To get the properties of Azure VM Name, Resource Group, VM Admin User Name of all the VMs from the select scope." }, { "code": null, "e": 876, "s": 726, "text": "resources\n| where type == \"microsoft.compute/virtualmachines\"\n| project name,resourceGroup,AdminUserName=tostring(properties.osProfile.adminUsername)" }, { "code": null, "e": 1018, "s": 876, "text": "This query returns the output of VM Computer Name, Resource Group, and VM Admin Admin User Name of all the Azure VMs from the scope selected." }, { "code": null, "e": 1033, "s": 1018, "text": "Sample Output:" }, { "code": null, "e": 1165, "s": 1033, "text": "Example 3: To get the properties of Azure VM Name, Resource Group, VM Admin User Name of a specific Azure VM from the select scope." }, { "code": null, "e": 1344, "s": 1165, "text": "resources\n| where type == \"microsoft.compute/virtualmachines\"\n| where name == \"CloudOpsVM\"\n| project name,resourceGroup,AdminUserName=tostring(properties.osProfile.adminUsername)" }, { "code": null, "e": 1465, "s": 1344, "text": "this query returns the output of VM Computer Name, Resource Group, and VM Admin Admin User Name of a Specific select VM." }, { "code": null, "e": 1480, "s": 1465, "text": "Sample Output:" }, { "code": null, "e": 1502, "s": 1480, "text": "azure-virtual-machine" }, { "code": null, "e": 1518, "s": 1502, "text": "Cloud-Computing" }, { "code": null, "e": 1534, "s": 1518, "text": "Microsoft Azure" } ]
Using predefined class name as Class or Variable name in Java
31 Jan, 2019 In Java, Using predefined class name as Class or Variable name is allowed. However, According to Java Specification Language(§3.9) the basic rule for naming in Java is that you cannot use a keyword as name of a class, name of a variable nor the name of a folder used for package.Using any predefined class in Java won’t cause such compiler error as Java predefined classes are not keywords. Following are some invalid variable declarations in Java: boolean break = false; // not allowed as break is keyword int boolean = 8; // not allowed as boolean is keyword boolean goto = false; // not allowed as goto is keyword String final = "hi"; // not allowed as final is keyword Using predefined class name as User defined class name Question : Can we have our class name as one of the predefined class name in our program?Answer : Yes we can have it. Below is example of using Number as user defined class// Number is predefined class name in java.lang package// Note : java.lang package is included in every java program by defaultpublic class Number{ public static void main (String[] args) { System.out.println("It works"); }}Output:It works Using String as User Defined Class:// String is predefined class name in java.lang package// Note : java.lang package is included in every java program by defaultpublic class String{ public static void main (String[] args) { System.out.println("I got confused"); }}However, in this case you will get run-time error like this :Error: Main method not found in class String, please define the main method as: public static void main(String[] args) Explanation : This is because Main thread is looking for main method() with predefined String class array argument. But here, it got main method() with user defined String class. Whenever Main thread will see a class name, it tries to search that class scope by scope. First it will see in your program, then in your package.If not found, then JVM follows delegation hierarchy principle to load that class.Hence you will get run-time error.To run above program, we can also provide full path of String class, i.e. java.lang.String .// String is predefined class name in java.lang package// Note : java.lang package is included in every java program by defaultpublic class String{ public static void main (java.lang.String[] args) { System.out.println("I got confused"); }}Output:I got confused Question : Can we have our class name as one of the predefined class name in our program?Answer : Yes we can have it. Below is example of using Number as user defined class// Number is predefined class name in java.lang package// Note : java.lang package is included in every java program by defaultpublic class Number{ public static void main (String[] args) { System.out.println("It works"); }}Output:It works // Number is predefined class name in java.lang package// Note : java.lang package is included in every java program by defaultpublic class Number{ public static void main (String[] args) { System.out.println("It works"); }} Output: It works Using String as User Defined Class:// String is predefined class name in java.lang package// Note : java.lang package is included in every java program by defaultpublic class String{ public static void main (String[] args) { System.out.println("I got confused"); }}However, in this case you will get run-time error like this :Error: Main method not found in class String, please define the main method as: public static void main(String[] args) Explanation : This is because Main thread is looking for main method() with predefined String class array argument. But here, it got main method() with user defined String class. Whenever Main thread will see a class name, it tries to search that class scope by scope. First it will see in your program, then in your package.If not found, then JVM follows delegation hierarchy principle to load that class.Hence you will get run-time error.To run above program, we can also provide full path of String class, i.e. java.lang.String .// String is predefined class name in java.lang package// Note : java.lang package is included in every java program by defaultpublic class String{ public static void main (java.lang.String[] args) { System.out.println("I got confused"); }}Output:I got confused // String is predefined class name in java.lang package// Note : java.lang package is included in every java program by defaultpublic class String{ public static void main (String[] args) { System.out.println("I got confused"); }} However, in this case you will get run-time error like this : Error: Main method not found in class String, please define the main method as: public static void main(String[] args) Explanation : This is because Main thread is looking for main method() with predefined String class array argument. But here, it got main method() with user defined String class. Whenever Main thread will see a class name, it tries to search that class scope by scope. First it will see in your program, then in your package.If not found, then JVM follows delegation hierarchy principle to load that class.Hence you will get run-time error.To run above program, we can also provide full path of String class, i.e. java.lang.String . // String is predefined class name in java.lang package// Note : java.lang package is included in every java program by defaultpublic class String{ public static void main (java.lang.String[] args) { System.out.println("I got confused"); }} Output: I got confused Using predefined class name as User defined Variable name Question : Can we have a variable name as one of the predefined class name in our program?Answer : Yes we can have it. // Number is predefined class name in java.lang package// Note : java.lang package is included in every java program by defaultpublic class Number{ // instance variable int Number = 20; public static void main (String[] args) { // reference variable Number Number = new Number(); // printing reference System.out.println(Number); // printing instance variable System.out.println(Number.Number); }} Output: Number@15db9742 20 This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. atishkadu12 Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n31 Jan, 2019" }, { "code": null, "e": 445, "s": 54, "text": "In Java, Using predefined class name as Class or Variable name is allowed. However, According to Java Specification Language(§3.9) the basic rule for naming in Java is that you cannot use a keyword as name of a class, name of a variable nor the name of a folder used for package.Using any predefined class in Java won’t cause such compiler error as Java predefined classes are not keywords." }, { "code": null, "e": 503, "s": 445, "text": "Following are some invalid variable declarations in Java:" }, { "code": null, "e": 727, "s": 503, "text": "boolean break = false; // not allowed as break is keyword\nint boolean = 8; // not allowed as boolean is keyword\nboolean goto = false; // not allowed as goto is keyword\nString final = \"hi\"; // not allowed as final is keyword" }, { "code": null, "e": 782, "s": 727, "text": "Using predefined class name as User defined class name" }, { "code": null, "e": 2486, "s": 782, "text": "Question : Can we have our class name as one of the predefined class name in our program?Answer : Yes we can have it. Below is example of using Number as user defined class// Number is predefined class name in java.lang package// Note : java.lang package is included in every java program by defaultpublic class Number{ public static void main (String[] args) { System.out.println(\"It works\"); }}Output:It works\nUsing String as User Defined Class:// String is predefined class name in java.lang package// Note : java.lang package is included in every java program by defaultpublic class String{ public static void main (String[] args) { System.out.println(\"I got confused\"); }}However, in this case you will get run-time error like this :Error: Main method not found in class String, please define \nthe main method as:\n public static void main(String[] args)\nExplanation : This is because Main thread is looking for main method() with predefined String class array argument. But here, it got main method() with user defined String class. Whenever Main thread will see a class name, it tries to search that class scope by scope. First it will see in your program, then in your package.If not found, then JVM follows delegation hierarchy principle to load that class.Hence you will get run-time error.To run above program, we can also provide full path of String class, i.e. java.lang.String .// String is predefined class name in java.lang package// Note : java.lang package is included in every java program by defaultpublic class String{ public static void main (java.lang.String[] args) { System.out.println(\"I got confused\"); }}Output:I got confused\n" }, { "code": null, "e": 2915, "s": 2486, "text": "Question : Can we have our class name as one of the predefined class name in our program?Answer : Yes we can have it. Below is example of using Number as user defined class// Number is predefined class name in java.lang package// Note : java.lang package is included in every java program by defaultpublic class Number{ public static void main (String[] args) { System.out.println(\"It works\"); }}Output:It works\n" }, { "code": "// Number is predefined class name in java.lang package// Note : java.lang package is included in every java program by defaultpublic class Number{ public static void main (String[] args) { System.out.println(\"It works\"); }}", "e": 3156, "s": 2915, "text": null }, { "code": null, "e": 3164, "s": 3156, "text": "Output:" }, { "code": null, "e": 3174, "s": 3164, "text": "It works\n" }, { "code": null, "e": 4450, "s": 3174, "text": "Using String as User Defined Class:// String is predefined class name in java.lang package// Note : java.lang package is included in every java program by defaultpublic class String{ public static void main (String[] args) { System.out.println(\"I got confused\"); }}However, in this case you will get run-time error like this :Error: Main method not found in class String, please define \nthe main method as:\n public static void main(String[] args)\nExplanation : This is because Main thread is looking for main method() with predefined String class array argument. But here, it got main method() with user defined String class. Whenever Main thread will see a class name, it tries to search that class scope by scope. First it will see in your program, then in your package.If not found, then JVM follows delegation hierarchy principle to load that class.Hence you will get run-time error.To run above program, we can also provide full path of String class, i.e. java.lang.String .// String is predefined class name in java.lang package// Note : java.lang package is included in every java program by defaultpublic class String{ public static void main (java.lang.String[] args) { System.out.println(\"I got confused\"); }}Output:I got confused\n" }, { "code": "// String is predefined class name in java.lang package// Note : java.lang package is included in every java program by defaultpublic class String{ public static void main (String[] args) { System.out.println(\"I got confused\"); }}", "e": 4697, "s": 4450, "text": null }, { "code": null, "e": 4759, "s": 4697, "text": "However, in this case you will get run-time error like this :" }, { "code": null, "e": 4883, "s": 4759, "text": "Error: Main method not found in class String, please define \nthe main method as:\n public static void main(String[] args)\n" }, { "code": null, "e": 5416, "s": 4883, "text": "Explanation : This is because Main thread is looking for main method() with predefined String class array argument. But here, it got main method() with user defined String class. Whenever Main thread will see a class name, it tries to search that class scope by scope. First it will see in your program, then in your package.If not found, then JVM follows delegation hierarchy principle to load that class.Hence you will get run-time error.To run above program, we can also provide full path of String class, i.e. java.lang.String ." }, { "code": "// String is predefined class name in java.lang package// Note : java.lang package is included in every java program by defaultpublic class String{ public static void main (java.lang.String[] args) { System.out.println(\"I got confused\"); }}", "e": 5673, "s": 5416, "text": null }, { "code": null, "e": 5681, "s": 5673, "text": "Output:" }, { "code": null, "e": 5697, "s": 5681, "text": "I got confused\n" }, { "code": null, "e": 5755, "s": 5697, "text": "Using predefined class name as User defined Variable name" }, { "code": null, "e": 5874, "s": 5755, "text": "Question : Can we have a variable name as one of the predefined class name in our program?Answer : Yes we can have it." }, { "code": "// Number is predefined class name in java.lang package// Note : java.lang package is included in every java program by defaultpublic class Number{ // instance variable int Number = 20; public static void main (String[] args) { // reference variable Number Number = new Number(); // printing reference System.out.println(Number); // printing instance variable System.out.println(Number.Number); }}", "e": 6355, "s": 5874, "text": null }, { "code": null, "e": 6363, "s": 6355, "text": "Output:" }, { "code": null, "e": 6383, "s": 6363, "text": "Number@15db9742\n20\n" }, { "code": null, "e": 6685, "s": 6383, "text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 6810, "s": 6685, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 6822, "s": 6810, "text": "atishkadu12" }, { "code": null, "e": 6827, "s": 6822, "text": "Java" }, { "code": null, "e": 6832, "s": 6827, "text": "Java" } ]
Path getFileName() method in Java with Examples
16 Jul, 2019 The Path interface was added to Java NIO in Java 7. The Path interface is located in the java.nio.file package, so the fully qualified name of the Java Path interface is java.nio.file.Path. A Java Path instance represents a path in the file system. A path can use to locate either a file or a directory.path of an entity could be of two types one is an absolute path and other is a relative path. The absolute path is the location address from the root to the entity while the relative path is the location address which is relative to some other path. getFileName() method of java.nio.file.Path used to return the name of the file or directory pointed by this path object. The file name is the farthest element from the root in the directory hierarchy. Syntax: Path getFileName() Parameters: This method accepts nothing. Return value: This method returns the name of the file or directory pointed by this path object. Below programs illustrate getFileName() method:Program 1: // Java program to demonstrate// java.nio.file.Path.getFileName() method import java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) throws IOException { // create object of Path Path path = Paths.get("D:/workspace/AmanCV.docx"); // call getFileName() and get FileName path object Path fileName = path.getFileName(); // print FileName System.out.println("FileName: " + fileName.toString()); }} FileName: AmanCV.docx Program 2: // Java program to demonstrate// java.nio.file.Path.getFileName() method import java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) throws IOException { // create object of Path Path path = Paths.get("D:/Resume.pdf"); // call getFileName() and get FileName path object Path fileName = path.getFileName(); // print FileName System.out.println("FileName: " + fileName.toString()); }} FileName: Resume.pdf References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#getFileName() Java-Functions Java-Path java.nio.file package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jul, 2019" }, { "code": null, "e": 581, "s": 28, "text": "The Path interface was added to Java NIO in Java 7. The Path interface is located in the java.nio.file package, so the fully qualified name of the Java Path interface is java.nio.file.Path. A Java Path instance represents a path in the file system. A path can use to locate either a file or a directory.path of an entity could be of two types one is an absolute path and other is a relative path. The absolute path is the location address from the root to the entity while the relative path is the location address which is relative to some other path." }, { "code": null, "e": 782, "s": 581, "text": "getFileName() method of java.nio.file.Path used to return the name of the file or directory pointed by this path object. The file name is the farthest element from the root in the directory hierarchy." }, { "code": null, "e": 790, "s": 782, "text": "Syntax:" }, { "code": null, "e": 810, "s": 790, "text": "Path getFileName()\n" }, { "code": null, "e": 851, "s": 810, "text": "Parameters: This method accepts nothing." }, { "code": null, "e": 948, "s": 851, "text": "Return value: This method returns the name of the file or directory pointed by this path object." }, { "code": null, "e": 1006, "s": 948, "text": "Below programs illustrate getFileName() method:Program 1:" }, { "code": "// Java program to demonstrate// java.nio.file.Path.getFileName() method import java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) throws IOException { // create object of Path Path path = Paths.get(\"D:/workspace/AmanCV.docx\"); // call getFileName() and get FileName path object Path fileName = path.getFileName(); // print FileName System.out.println(\"FileName: \" + fileName.toString()); }}", "e": 1569, "s": 1006, "text": null }, { "code": null, "e": 1592, "s": 1569, "text": "FileName: AmanCV.docx\n" }, { "code": null, "e": 1603, "s": 1592, "text": "Program 2:" }, { "code": "// Java program to demonstrate// java.nio.file.Path.getFileName() method import java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths;public class GFG { public static void main(String[] args) throws IOException { // create object of Path Path path = Paths.get(\"D:/Resume.pdf\"); // call getFileName() and get FileName path object Path fileName = path.getFileName(); // print FileName System.out.println(\"FileName: \" + fileName.toString()); }}", "e": 2155, "s": 1603, "text": null }, { "code": null, "e": 2177, "s": 2155, "text": "FileName: Resume.pdf\n" }, { "code": null, "e": 2270, "s": 2177, "text": "References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#getFileName()" }, { "code": null, "e": 2285, "s": 2270, "text": "Java-Functions" }, { "code": null, "e": 2295, "s": 2285, "text": "Java-Path" }, { "code": null, "e": 2317, "s": 2295, "text": "java.nio.file package" }, { "code": null, "e": 2322, "s": 2317, "text": "Java" }, { "code": null, "e": 2327, "s": 2322, "text": "Java" } ]
What are the key features of Node.js ?
31 Oct, 2021 Node.js is a cross-platform runtime environment that allows you to create server-side and networking applications. Node.js apps are written in JavaScript and run on OS X, Microsoft Windows, and Linux utilizing the Node.js runtime. Node.js also comes with a large library of JavaScript modules, making it much easier to construct web applications with it. It enhances the functionalities of Node.js. NodeJs facilitates the integration of programming languages with APIs, other languages, and a variety of third-party libraries. It is used exclusively in the ‘JavaScript everywhere’ paradigm for web app development and can handle both server-side scripting and client-side programming. Web development is a constantly evolving process that demands ongoing innovation and updates to keep up with the desire for game-changing technologies as each year passes. Most developers favor JavaScript for front-end programming, which has recently been boosted by NodeJS for back-end development. NodeJS is being used in mobile application development in addition to online development. NodeJs = Runtime Environment + Javascript library Working with Nodejs Step 1: Run the following command in the terminal to verify if the node.js is installed. This command will show the installed version of NodeJs to our system. node --version Step 2: Create package.json by using the following command to store the metadata of the project. npm init -y Step 3: Now install express in the root directory using the following command in the terminal. npm install express --save Step 4: Create app.js file in the root directory. Our folder structure is shown below: Javascript // app.jsconst express = require('express'); // Importing express module const app = express(); // Creating an express objectconst port = 5000; // Setting an port for this application // Handing the route to the server app.get('/', function (req, res) { res.send('Welcome to Geeksforgeeks Article');}); // Starting server using listen functionapp.listen(port, function (err) { if (err) { console.log("Error!!!"); } else { console.log("Server is running at port " + port); }}); Step 5: Run the above code and start the server using the following command. node app.js Output: Functions of Node.js Following are some of the functions that can be performed by Node.js – Collects data from forms.Data in the database is added, deleted, and changed.Renders dynamic content for web pages.Files on the server are created, read, written, deleted, and closed. Collects data from forms. Data in the database is added, deleted, and changed. Renders dynamic content for web pages. Files on the server are created, read, written, deleted, and closed. Key Features of Node.js Key Features of NodeJs Asynchronous and Event-Driven: The Node.js library’s APIs are all asynchronous (non-blocking) in nature. A server built with Node.JS never waits for data from an API. from an API. After accessing an API, the server moves on to the next one. In order to receive and track responses of previous API requests, it uses a notification mechanism called Events.Single-Threaded: Node.js employs a single-threaded architecture with event looping, making it very scalable. In contrast to typical servers, which create limited threads to process requests, the event mechanism allows the node.js server to reply in a non-blocking manner and makes it more scalable. When compared to traditional servers like Apache HTTP Server, Node.js uses a single-threaded program that can handle a considerably larger number of requests.Scalable: NodeJs addresses one of the most pressing concerns in software development: scalability. Nowadays, most organizations demand scalable software. NodeJs can also handle concurrent requests efficiently. It has a cluster module that manages load balancing for all CPU cores that are active. The capability of NodeJs to partition applications horizontally is its most appealing feature. It achieves this through the use of child processes. This allows the organizations to provide distinct app versions to different target audiences, allowing them to cater to client preferences for customization.Quick execution of code: Node.js makes use of the V8 JavaScript Runtime motor, which is also used by Google Chrome. Hub provides a wrapper for the JavaScript motor, which makes the runtime motor faster. As a result, the preparation of requests inside Node.js becomes faster as well.Cross-platform compatibility: NodeJS may be used on a variety of systems, including Windows, Unix, Linux, Mac OS X, and mobile devices. It can be paired with the appropriate package to generate a self-sufficient executable.Uses JavaScript: JavaScript is used by the Node.js library, which is another important aspect of Node.js from the engineer’s perspective. Most of the engineers are already familiar with JavaScript. As a result, a designer who is familiar with JavaScript will find that working with Node.js is much easier.Fast data streaming: When data is transmitted in multiple streams, processing them takes a long time. Node.js processes data at a very fast rate. It processes and uploads a file simultaneously, thereby saving a lot of time. As a result, NodeJs improves the overall speed of data and video streaming.No Buffering: In a Node.js application, data is never buffered. Asynchronous and Event-Driven: The Node.js library’s APIs are all asynchronous (non-blocking) in nature. A server built with Node.JS never waits for data from an API. from an API. After accessing an API, the server moves on to the next one. In order to receive and track responses of previous API requests, it uses a notification mechanism called Events. Single-Threaded: Node.js employs a single-threaded architecture with event looping, making it very scalable. In contrast to typical servers, which create limited threads to process requests, the event mechanism allows the node.js server to reply in a non-blocking manner and makes it more scalable. When compared to traditional servers like Apache HTTP Server, Node.js uses a single-threaded program that can handle a considerably larger number of requests. Scalable: NodeJs addresses one of the most pressing concerns in software development: scalability. Nowadays, most organizations demand scalable software. NodeJs can also handle concurrent requests efficiently. It has a cluster module that manages load balancing for all CPU cores that are active. The capability of NodeJs to partition applications horizontally is its most appealing feature. It achieves this through the use of child processes. This allows the organizations to provide distinct app versions to different target audiences, allowing them to cater to client preferences for customization. Quick execution of code: Node.js makes use of the V8 JavaScript Runtime motor, which is also used by Google Chrome. Hub provides a wrapper for the JavaScript motor, which makes the runtime motor faster. As a result, the preparation of requests inside Node.js becomes faster as well. Cross-platform compatibility: NodeJS may be used on a variety of systems, including Windows, Unix, Linux, Mac OS X, and mobile devices. It can be paired with the appropriate package to generate a self-sufficient executable. Uses JavaScript: JavaScript is used by the Node.js library, which is another important aspect of Node.js from the engineer’s perspective. Most of the engineers are already familiar with JavaScript. As a result, a designer who is familiar with JavaScript will find that working with Node.js is much easier. Fast data streaming: When data is transmitted in multiple streams, processing them takes a long time. Node.js processes data at a very fast rate. It processes and uploads a file simultaneously, thereby saving a lot of time. As a result, NodeJs improves the overall speed of data and video streaming. No Buffering: In a Node.js application, data is never buffered. Disadvantages of Node.js API is not stable and keeps changing for NodeJs.Code for large applications is complex due to the asynchronous nature of NodeJs.Does not have a strong library support system API is not stable and keeps changing for NodeJs. Code for large applications is complex due to the asynchronous nature of NodeJs. Does not have a strong library support system Applications of Node.js The following are some of the areas where Node.js is proving to be an effective technology partner- Single Page ApplicationsData-Intensive Real-time ApplicationsI/O bound ApplicationsJSON APIs based ApplicationsData Streaming Applications Single Page Applications Data-Intensive Real-time Applications I/O bound Applications JSON APIs based Applications Data Streaming Applications NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Oct, 2021" }, { "code": null, "e": 259, "s": 28, "text": "Node.js is a cross-platform runtime environment that allows you to create server-side and networking applications. Node.js apps are written in JavaScript and run on OS X, Microsoft Windows, and Linux utilizing the Node.js runtime." }, { "code": null, "e": 713, "s": 259, "text": "Node.js also comes with a large library of JavaScript modules, making it much easier to construct web applications with it. It enhances the functionalities of Node.js. NodeJs facilitates the integration of programming languages with APIs, other languages, and a variety of third-party libraries. It is used exclusively in the ‘JavaScript everywhere’ paradigm for web app development and can handle both server-side scripting and client-side programming." }, { "code": null, "e": 1105, "s": 713, "text": "Web development is a constantly evolving process that demands ongoing innovation and updates to keep up with the desire for game-changing technologies as each year passes. Most developers favor JavaScript for front-end programming, which has recently been boosted by NodeJS for back-end development. NodeJS is being used in mobile application development in addition to online development. " }, { "code": null, "e": 1155, "s": 1105, "text": "NodeJs = Runtime Environment + Javascript library" }, { "code": null, "e": 1175, "s": 1155, "text": "Working with Nodejs" }, { "code": null, "e": 1334, "s": 1175, "text": "Step 1: Run the following command in the terminal to verify if the node.js is installed. This command will show the installed version of NodeJs to our system." }, { "code": null, "e": 1353, "s": 1334, "text": "node --version " }, { "code": null, "e": 1451, "s": 1353, "text": "Step 2: Create package.json by using the following command to store the metadata of the project." }, { "code": null, "e": 1463, "s": 1451, "text": "npm init -y" }, { "code": null, "e": 1559, "s": 1463, "text": "Step 3: Now install express in the root directory using the following command in the terminal." }, { "code": null, "e": 1586, "s": 1559, "text": "npm install express --save" }, { "code": null, "e": 1673, "s": 1586, "text": "Step 4: Create app.js file in the root directory. Our folder structure is shown below:" }, { "code": null, "e": 1687, "s": 1676, "text": "Javascript" }, { "code": "// app.jsconst express = require('express'); // Importing express module const app = express(); // Creating an express objectconst port = 5000; // Setting an port for this application // Handing the route to the server app.get('/', function (req, res) { res.send('Welcome to Geeksforgeeks Article');}); // Starting server using listen functionapp.listen(port, function (err) { if (err) { console.log(\"Error!!!\"); } else { console.log(\"Server is running at port \" + port); }});", "e": 2197, "s": 1687, "text": null }, { "code": null, "e": 2274, "s": 2197, "text": "Step 5: Run the above code and start the server using the following command." }, { "code": null, "e": 2286, "s": 2274, "text": "node app.js" }, { "code": null, "e": 2294, "s": 2286, "text": "Output:" }, { "code": null, "e": 2315, "s": 2294, "text": "Functions of Node.js" }, { "code": null, "e": 2388, "s": 2315, "text": "Following are some of the functions that can be performed by Node.js – " }, { "code": null, "e": 2572, "s": 2388, "text": "Collects data from forms.Data in the database is added, deleted, and changed.Renders dynamic content for web pages.Files on the server are created, read, written, deleted, and closed." }, { "code": null, "e": 2598, "s": 2572, "text": "Collects data from forms." }, { "code": null, "e": 2651, "s": 2598, "text": "Data in the database is added, deleted, and changed." }, { "code": null, "e": 2690, "s": 2651, "text": "Renders dynamic content for web pages." }, { "code": null, "e": 2759, "s": 2690, "text": "Files on the server are created, read, written, deleted, and closed." }, { "code": null, "e": 2783, "s": 2759, "text": "Key Features of Node.js" }, { "code": null, "e": 2806, "s": 2783, "text": "Key Features of NodeJs" }, { "code": null, "e": 5392, "s": 2806, "text": "Asynchronous and Event-Driven: The Node.js library’s APIs are all asynchronous (non-blocking) in nature. A server built with Node.JS never waits for data from an API. from an API. After accessing an API, the server moves on to the next one. In order to receive and track responses of previous API requests, it uses a notification mechanism called Events.Single-Threaded: Node.js employs a single-threaded architecture with event looping, making it very scalable. In contrast to typical servers, which create limited threads to process requests, the event mechanism allows the node.js server to reply in a non-blocking manner and makes it more scalable. When compared to traditional servers like Apache HTTP Server, Node.js uses a single-threaded program that can handle a considerably larger number of requests.Scalable: NodeJs addresses one of the most pressing concerns in software development: scalability. Nowadays, most organizations demand scalable software. NodeJs can also handle concurrent requests efficiently. It has a cluster module that manages load balancing for all CPU cores that are active. The capability of NodeJs to partition applications horizontally is its most appealing feature. It achieves this through the use of child processes. This allows the organizations to provide distinct app versions to different target audiences, allowing them to cater to client preferences for customization.Quick execution of code: Node.js makes use of the V8 JavaScript Runtime motor, which is also used by Google Chrome. Hub provides a wrapper for the JavaScript motor, which makes the runtime motor faster. As a result, the preparation of requests inside Node.js becomes faster as well.Cross-platform compatibility: NodeJS may be used on a variety of systems, including Windows, Unix, Linux, Mac OS X, and mobile devices. It can be paired with the appropriate package to generate a self-sufficient executable.Uses JavaScript: JavaScript is used by the Node.js library, which is another important aspect of Node.js from the engineer’s perspective. Most of the engineers are already familiar with JavaScript. As a result, a designer who is familiar with JavaScript will find that working with Node.js is much easier.Fast data streaming: When data is transmitted in multiple streams, processing them takes a long time. Node.js processes data at a very fast rate. It processes and uploads a file simultaneously, thereby saving a lot of time. As a result, NodeJs improves the overall speed of data and video streaming.No Buffering: In a Node.js application, data is never buffered." }, { "code": null, "e": 5747, "s": 5392, "text": "Asynchronous and Event-Driven: The Node.js library’s APIs are all asynchronous (non-blocking) in nature. A server built with Node.JS never waits for data from an API. from an API. After accessing an API, the server moves on to the next one. In order to receive and track responses of previous API requests, it uses a notification mechanism called Events." }, { "code": null, "e": 6205, "s": 5747, "text": "Single-Threaded: Node.js employs a single-threaded architecture with event looping, making it very scalable. In contrast to typical servers, which create limited threads to process requests, the event mechanism allows the node.js server to reply in a non-blocking manner and makes it more scalable. When compared to traditional servers like Apache HTTP Server, Node.js uses a single-threaded program that can handle a considerably larger number of requests." }, { "code": null, "e": 6808, "s": 6205, "text": "Scalable: NodeJs addresses one of the most pressing concerns in software development: scalability. Nowadays, most organizations demand scalable software. NodeJs can also handle concurrent requests efficiently. It has a cluster module that manages load balancing for all CPU cores that are active. The capability of NodeJs to partition applications horizontally is its most appealing feature. It achieves this through the use of child processes. This allows the organizations to provide distinct app versions to different target audiences, allowing them to cater to client preferences for customization." }, { "code": null, "e": 7091, "s": 6808, "text": "Quick execution of code: Node.js makes use of the V8 JavaScript Runtime motor, which is also used by Google Chrome. Hub provides a wrapper for the JavaScript motor, which makes the runtime motor faster. As a result, the preparation of requests inside Node.js becomes faster as well." }, { "code": null, "e": 7315, "s": 7091, "text": "Cross-platform compatibility: NodeJS may be used on a variety of systems, including Windows, Unix, Linux, Mac OS X, and mobile devices. It can be paired with the appropriate package to generate a self-sufficient executable." }, { "code": null, "e": 7621, "s": 7315, "text": "Uses JavaScript: JavaScript is used by the Node.js library, which is another important aspect of Node.js from the engineer’s perspective. Most of the engineers are already familiar with JavaScript. As a result, a designer who is familiar with JavaScript will find that working with Node.js is much easier." }, { "code": null, "e": 7921, "s": 7621, "text": "Fast data streaming: When data is transmitted in multiple streams, processing them takes a long time. Node.js processes data at a very fast rate. It processes and uploads a file simultaneously, thereby saving a lot of time. As a result, NodeJs improves the overall speed of data and video streaming." }, { "code": null, "e": 7985, "s": 7921, "text": "No Buffering: In a Node.js application, data is never buffered." }, { "code": null, "e": 8010, "s": 7985, "text": "Disadvantages of Node.js" }, { "code": null, "e": 8184, "s": 8010, "text": "API is not stable and keeps changing for NodeJs.Code for large applications is complex due to the asynchronous nature of NodeJs.Does not have a strong library support system" }, { "code": null, "e": 8233, "s": 8184, "text": "API is not stable and keeps changing for NodeJs." }, { "code": null, "e": 8314, "s": 8233, "text": "Code for large applications is complex due to the asynchronous nature of NodeJs." }, { "code": null, "e": 8360, "s": 8314, "text": "Does not have a strong library support system" }, { "code": null, "e": 8384, "s": 8360, "text": "Applications of Node.js" }, { "code": null, "e": 8485, "s": 8384, "text": "The following are some of the areas where Node.js is proving to be an effective technology partner- " }, { "code": null, "e": 8624, "s": 8485, "text": "Single Page ApplicationsData-Intensive Real-time ApplicationsI/O bound ApplicationsJSON APIs based ApplicationsData Streaming Applications" }, { "code": null, "e": 8649, "s": 8624, "text": "Single Page Applications" }, { "code": null, "e": 8687, "s": 8649, "text": "Data-Intensive Real-time Applications" }, { "code": null, "e": 8710, "s": 8687, "text": "I/O bound Applications" }, { "code": null, "e": 8739, "s": 8710, "text": "JSON APIs based Applications" }, { "code": null, "e": 8767, "s": 8739, "text": "Data Streaming Applications" }, { "code": null, "e": 8784, "s": 8767, "text": "NodeJS-Questions" }, { "code": null, "e": 8791, "s": 8784, "text": "Picked" }, { "code": null, "e": 8799, "s": 8791, "text": "Node.js" }, { "code": null, "e": 8816, "s": 8799, "text": "Web Technologies" } ]
PHP | number_format() Function
03 Jul, 2018 The number_format() function is an inbuilt function in PHP which is used to format a number with grouped thousands. It returns the formatted number on success otherwise it gives E_WARNING on failure. Syntax: string number_format ( $number, $decimals, $decimalpoint, $sep ) Parameters: This function accepts four parameters as mentioned above and described below: $number: It is required parameter which specified the number to be formatted. If no other parameters are set, the number will be formatted without decimals and with the comma (, ) as the thousands separator. $decimals: It is optional parameter and used to specifies decimals. If this parameter is set, the number will be formatted with a dot (.) as the decimal point. $decimalpoint: It is optional parameter and used to specifies the string to use for the decimal point. $sep: It is optional parameter and used to specifies string to use for thousands separator. If this parameter is given, then all other parameters are required. Return Value: It returns Formatted Number in case success, otherwise it gives E_WARNING in failure. Examples: Input: $number = 100000 Output: 10, 000 Input: $number = 10000 $decimals = 3 $decimalpoints = "." $sep =, Output: 10, 0000.000 Below programs illustrate The number_format() function in PHP: Program 1: <?php$num1 = "999999.49"; // With out decimal point parameterecho number_format($num1)."\n"; // With decimal Point parameterecho number_format($num1, 3)."\n"; $num2 = "9999999.99"; // With out decimal point parameter// return Round valueecho number_format($num2)."\n"; // With decimal Point parameterecho number_format($num2, 3)."\n"; // With All four parametersecho number_format("1000000.99", 3, "#", "GGG"); ?> 999,999 999,999.490 10,000,000 9,999,999.990 1GGG000GGG000#990 Program 2: If pass anything instead of numbers it gives warning. <?php$num = "GFG"; // With out decimal point parameterecho number_format($num)."\n\n"; // With decimal Point parameterecho number_format($num, 3); ?> PHP Warning: number_format() expects parameter 1 to be float, string given in /home/ac476aaecea758334cb8ed146bcbb8f6.php on line 5 PHP Warning: number_format() expects parameter 1 to be float, string given in /home/ac476aaecea758334cb8ed146bcbb8f6.php on line 8 Program 3: This function does not accept three parameters, only accept 1, 2 or 4 parameters. <?php$num = 1000000; // passing 3 parameters It gives errors because function// accepting only 1, 2 or 4 parametersecho number_format($num, 3, ", ");?> PHP Warning: Wrong parameter count for number_format() in /home/e426108b066d9a86366249bf7b626d19.php on line 6 Reference: http://php.net/manual/en/function.number-format.php PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jul, 2018" }, { "code": null, "e": 228, "s": 28, "text": "The number_format() function is an inbuilt function in PHP which is used to format a number with grouped thousands. It returns the formatted number on success otherwise it gives E_WARNING on failure." }, { "code": null, "e": 236, "s": 228, "text": "Syntax:" }, { "code": null, "e": 301, "s": 236, "text": "string number_format ( $number, $decimals, $decimalpoint, $sep )" }, { "code": null, "e": 391, "s": 301, "text": "Parameters: This function accepts four parameters as mentioned above and described below:" }, { "code": null, "e": 599, "s": 391, "text": "$number: It is required parameter which specified the number to be formatted. If no other parameters are set, the number will be formatted without decimals and with the comma (, ) as the thousands separator." }, { "code": null, "e": 759, "s": 599, "text": "$decimals: It is optional parameter and used to specifies decimals. If this parameter is set, the number will be formatted with a dot (.) as the decimal point." }, { "code": null, "e": 862, "s": 759, "text": "$decimalpoint: It is optional parameter and used to specifies the string to use for the decimal point." }, { "code": null, "e": 1022, "s": 862, "text": "$sep: It is optional parameter and used to specifies string to use for thousands separator. If this parameter is given, then all other parameters are required." }, { "code": null, "e": 1122, "s": 1022, "text": "Return Value: It returns Formatted Number in case success, otherwise it gives E_WARNING in failure." }, { "code": null, "e": 1132, "s": 1122, "text": "Examples:" }, { "code": null, "e": 1278, "s": 1132, "text": "Input: $number = 100000\nOutput: 10, 000\n\nInput: $number = 10000 \n $decimals = 3 \n $decimalpoints = \".\" $sep =,\nOutput: 10, 0000.000 \n" }, { "code": null, "e": 1341, "s": 1278, "text": "Below programs illustrate The number_format() function in PHP:" }, { "code": null, "e": 1352, "s": 1341, "text": "Program 1:" }, { "code": "<?php$num1 = \"999999.49\"; // With out decimal point parameterecho number_format($num1).\"\\n\"; // With decimal Point parameterecho number_format($num1, 3).\"\\n\"; $num2 = \"9999999.99\"; // With out decimal point parameter// return Round valueecho number_format($num2).\"\\n\"; // With decimal Point parameterecho number_format($num2, 3).\"\\n\"; // With All four parametersecho number_format(\"1000000.99\", 3, \"#\", \"GGG\"); ?>", "e": 1778, "s": 1352, "text": null }, { "code": null, "e": 1842, "s": 1778, "text": "999,999\n999,999.490\n10,000,000\n9,999,999.990\n1GGG000GGG000#990\n" }, { "code": null, "e": 1907, "s": 1842, "text": "Program 2: If pass anything instead of numbers it gives warning." }, { "code": "<?php$num = \"GFG\"; // With out decimal point parameterecho number_format($num).\"\\n\\n\"; // With decimal Point parameterecho number_format($num, 3); ?>", "e": 2061, "s": 1907, "text": null }, { "code": null, "e": 2328, "s": 2061, "text": "PHP Warning: number_format() expects parameter 1 to be float,\nstring given in /home/ac476aaecea758334cb8ed146bcbb8f6.php on line 5\n\nPHP Warning: number_format() expects parameter 1 to be float, \nstring given in /home/ac476aaecea758334cb8ed146bcbb8f6.php on line 8\n" }, { "code": null, "e": 2421, "s": 2328, "text": "Program 3: This function does not accept three parameters, only accept 1, 2 or 4 parameters." }, { "code": "<?php$num = 1000000; // passing 3 parameters It gives errors because function// accepting only 1, 2 or 4 parametersecho number_format($num, 3, \", \");?>", "e": 2574, "s": 2421, "text": null }, { "code": null, "e": 2688, "s": 2574, "text": "PHP Warning: Wrong parameter count for number_format() \nin /home/e426108b066d9a86366249bf7b626d19.php on line 6\n" }, { "code": null, "e": 2751, "s": 2688, "text": "Reference: http://php.net/manual/en/function.number-format.php" }, { "code": null, "e": 2764, "s": 2751, "text": "PHP-function" }, { "code": null, "e": 2768, "s": 2764, "text": "PHP" }, { "code": null, "e": 2785, "s": 2768, "text": "Web Technologies" }, { "code": null, "e": 2789, "s": 2785, "text": "PHP" } ]
How does await and async works in ES6 ?
07 Dec, 2021 In this article, we will try to understand how exactly async and await works in ES6. Let us first try to understand what exactly async and await are along with their usage and then further we will see some examples in which we would see how we may use async and await along with the normal functions. Async and Await: Async and Await both are considered as special keywords which are provided by ES6 in order to perform some asynchronous data operations. Even synchronous operations could also be performed using these keywords. Async keyword is used along with the function declaration which specifies that this function is now able to accept all types of asynchronous events on itself. In other words, the async keyword is used along with functions (or methods) which enables them to receive all types of asynchronous data easily. Async keyword usage along with the functions always returns a promise at the end along with its state (pending or resolved or rejected). Await is used inside the async function which is though useful for the waiting purpose of the result. Await basically waits for the results which are particularly to be fetched from the source from which that async function is about to fetch the data. Await takes a little time to fetch the results from the source (like API) and thereafter along with the async function returns the result in the form of a promise. Await can also be used if Async is used along with the function declaration. Working of Async and Await: Whenever a user declares a function with the async keyword in its declaration, it automatically implies a fact that this function or a method is ready to receive all of the asynchronous events on itself. After this, we generally use await keyword which then waits for the results and then fetches it successfully. After that, we store the fetched result in some random variable then display the result or use that result for several other purposes as per the requirement. A function that uses Async/Await keywords will eventually hold their results for some little amount of time as compared with other normal functions. Upon successful completion, the result may be used for further data operations within the code itself or may be displayed on the browser’s console successfully. Now that we have understood details associated with the Async/Await usage in normal functions let us see some of the following examples which would eventually help us to understand things in a much better way. Example 1: In this example, we would be using async and await inside a regular function (or method). Along with that, we would be displaying some other results. The output below will show us one thing that due to the usage of await keyword our result will be delayed a little bit as compared to the other results which we are displaying. HTML <script> let dataDisplay = async () => { let data = await "GeeksforGeeks"; console.log(data); }; console.log(1); dataDisplay(); console.log("Hello");</script> Output: 1 Hello GeeksforGeeks Example 2: In this example, we would be using an open-source API which is a freely available API and can be accessed by all. We will fetch the results from that API in our browser’s console. This example clearly demonstrates how we will use the async/await in general while working with several real-time APIs. The output will be displayed in the following shown image. HTML <script> async function fetchMethod() { let response = await fetch( "https://reqres.in/api/products/3"); let data = await response.json(); console.log(data); } fetchMethod();</script> Output: ES6 JavaScript-Questions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Dec, 2021" }, { "code": null, "e": 329, "s": 28, "text": "In this article, we will try to understand how exactly async and await works in ES6. Let us first try to understand what exactly async and await are along with their usage and then further we will see some examples in which we would see how we may use async and await along with the normal functions." }, { "code": null, "e": 346, "s": 329, "text": "Async and Await:" }, { "code": null, "e": 557, "s": 346, "text": "Async and Await both are considered as special keywords which are provided by ES6 in order to perform some asynchronous data operations. Even synchronous operations could also be performed using these keywords." }, { "code": null, "e": 716, "s": 557, "text": "Async keyword is used along with the function declaration which specifies that this function is now able to accept all types of asynchronous events on itself." }, { "code": null, "e": 861, "s": 716, "text": "In other words, the async keyword is used along with functions (or methods) which enables them to receive all types of asynchronous data easily." }, { "code": null, "e": 998, "s": 861, "text": "Async keyword usage along with the functions always returns a promise at the end along with its state (pending or resolved or rejected)." }, { "code": null, "e": 1100, "s": 998, "text": "Await is used inside the async function which is though useful for the waiting purpose of the result." }, { "code": null, "e": 1250, "s": 1100, "text": "Await basically waits for the results which are particularly to be fetched from the source from which that async function is about to fetch the data." }, { "code": null, "e": 1414, "s": 1250, "text": "Await takes a little time to fetch the results from the source (like API) and thereafter along with the async function returns the result in the form of a promise." }, { "code": null, "e": 1491, "s": 1414, "text": "Await can also be used if Async is used along with the function declaration." }, { "code": null, "e": 1519, "s": 1491, "text": "Working of Async and Await:" }, { "code": null, "e": 1723, "s": 1519, "text": "Whenever a user declares a function with the async keyword in its declaration, it automatically implies a fact that this function or a method is ready to receive all of the asynchronous events on itself." }, { "code": null, "e": 1833, "s": 1723, "text": "After this, we generally use await keyword which then waits for the results and then fetches it successfully." }, { "code": null, "e": 1991, "s": 1833, "text": "After that, we store the fetched result in some random variable then display the result or use that result for several other purposes as per the requirement." }, { "code": null, "e": 2140, "s": 1991, "text": "A function that uses Async/Await keywords will eventually hold their results for some little amount of time as compared with other normal functions." }, { "code": null, "e": 2301, "s": 2140, "text": "Upon successful completion, the result may be used for further data operations within the code itself or may be displayed on the browser’s console successfully." }, { "code": null, "e": 2511, "s": 2301, "text": "Now that we have understood details associated with the Async/Await usage in normal functions let us see some of the following examples which would eventually help us to understand things in a much better way." }, { "code": null, "e": 2849, "s": 2511, "text": "Example 1: In this example, we would be using async and await inside a regular function (or method). Along with that, we would be displaying some other results. The output below will show us one thing that due to the usage of await keyword our result will be delayed a little bit as compared to the other results which we are displaying." }, { "code": null, "e": 2854, "s": 2849, "text": "HTML" }, { "code": "<script> let dataDisplay = async () => { let data = await \"GeeksforGeeks\"; console.log(data); }; console.log(1); dataDisplay(); console.log(\"Hello\");</script>", "e": 3038, "s": 2854, "text": null }, { "code": null, "e": 3046, "s": 3038, "text": "Output:" }, { "code": null, "e": 3068, "s": 3046, "text": "1\nHello\nGeeksforGeeks" }, { "code": null, "e": 3438, "s": 3068, "text": "Example 2: In this example, we would be using an open-source API which is a freely available API and can be accessed by all. We will fetch the results from that API in our browser’s console. This example clearly demonstrates how we will use the async/await in general while working with several real-time APIs. The output will be displayed in the following shown image." }, { "code": null, "e": 3443, "s": 3438, "text": "HTML" }, { "code": "<script> async function fetchMethod() { let response = await fetch( \"https://reqres.in/api/products/3\"); let data = await response.json(); console.log(data); } fetchMethod();</script>", "e": 3658, "s": 3443, "text": null }, { "code": null, "e": 3666, "s": 3658, "text": "Output:" }, { "code": null, "e": 3670, "s": 3666, "text": "ES6" }, { "code": null, "e": 3691, "s": 3670, "text": "JavaScript-Questions" }, { "code": null, "e": 3698, "s": 3691, "text": "Picked" }, { "code": null, "e": 3709, "s": 3698, "text": "JavaScript" }, { "code": null, "e": 3726, "s": 3709, "text": "Web Technologies" } ]
Python – Draw Hexagon Using Turtle Graphics
16 Oct, 2020 In this article, we will learn how to make a Hexagon using Turtle Graphics in Python. For that lets first know what is Turtle Graphics. Turtle is a Python feature like a drawing board, which let us command a turtle to draw all over it! We can use many turtle functions which can move the turtle around. Turtle comes in the turtle library.The turtle module can be used in both object-oriented and procedure-oriented ways. Some of the commonly used methods are: forward(length): moves the pen in the forward direction by x unit. backward(length): moves the pen in the backward direction by x unit. right(angle): rotate the pen in the clockwise direction by an angle x. left(angle): rotate the pen in the anticlockwise direction by an angle x. penup(): stop drawing of the turtle pen. pendown(): start drawing of the turtle pen. Define an instance for turtle. For a hexagon execute a loop 6 times. In every iteration move turtle 90 units forward and move it left 300 degrees. This will make up Hexagon . Below is the python implementation of above approach. Python3 # import the turtle modulesimport turtle # Start a work Screenws = turtle.Screen() # Define a Turtle InstancegeekyTurtle = turtle.Turtle() # executing loop 6 times for 6 sidesfor i in range(6): # Move forward by 90 units geekyTurtle.forward(90) # Turn left the turtle by 300 degrees geekyTurtle.left(300) Turtle Making Hexagon anshitaagarwal Python-turtle Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Oct, 2020" }, { "code": null, "e": 164, "s": 28, "text": "In this article, we will learn how to make a Hexagon using Turtle Graphics in Python. For that lets first know what is Turtle Graphics." }, { "code": null, "e": 449, "s": 164, "text": "Turtle is a Python feature like a drawing board, which let us command a turtle to draw all over it! We can use many turtle functions which can move the turtle around. Turtle comes in the turtle library.The turtle module can be used in both object-oriented and procedure-oriented ways." }, { "code": null, "e": 488, "s": 449, "text": "Some of the commonly used methods are:" }, { "code": null, "e": 555, "s": 488, "text": "forward(length): moves the pen in the forward direction by x unit." }, { "code": null, "e": 624, "s": 555, "text": "backward(length): moves the pen in the backward direction by x unit." }, { "code": null, "e": 695, "s": 624, "text": "right(angle): rotate the pen in the clockwise direction by an angle x." }, { "code": null, "e": 769, "s": 695, "text": "left(angle): rotate the pen in the anticlockwise direction by an angle x." }, { "code": null, "e": 810, "s": 769, "text": "penup(): stop drawing of the turtle pen." }, { "code": null, "e": 854, "s": 810, "text": "pendown(): start drawing of the turtle pen." }, { "code": null, "e": 885, "s": 854, "text": "Define an instance for turtle." }, { "code": null, "e": 923, "s": 885, "text": "For a hexagon execute a loop 6 times." }, { "code": null, "e": 1001, "s": 923, "text": "In every iteration move turtle 90 units forward and move it left 300 degrees." }, { "code": null, "e": 1029, "s": 1001, "text": "This will make up Hexagon ." }, { "code": null, "e": 1083, "s": 1029, "text": "Below is the python implementation of above approach." }, { "code": null, "e": 1091, "s": 1083, "text": "Python3" }, { "code": "# import the turtle modulesimport turtle # Start a work Screenws = turtle.Screen() # Define a Turtle InstancegeekyTurtle = turtle.Turtle() # executing loop 6 times for 6 sidesfor i in range(6): # Move forward by 90 units geekyTurtle.forward(90) # Turn left the turtle by 300 degrees geekyTurtle.left(300)", "e": 1410, "s": 1091, "text": null }, { "code": null, "e": 1435, "s": 1413, "text": "Turtle Making Hexagon" }, { "code": null, "e": 1452, "s": 1437, "text": "anshitaagarwal" }, { "code": null, "e": 1466, "s": 1452, "text": "Python-turtle" }, { "code": null, "e": 1473, "s": 1466, "text": "Python" }, { "code": null, "e": 1489, "s": 1473, "text": "Python Programs" } ]
Removing last element from ArrayList in Java
26 Jan, 2020 Given an ArrayList collection in Java, the task is to remove the last element from the ArrayList. Example: Input: ArrayList[] = [10, 20, 30, 1, 2] Output: [10, 20, 30, 1] After removing the last element 2, the ArrayList is: [10, 20, 30, 1] Input: ArrayList[] = [1, 1, 2, 2, 3] Output: [1, 1, 2, 2] After removing the last element 3, the ArrayList is: [1, 1, 2, 2] We can use the remove() method of ArrayList container in Java to remove the last element. ArrayList provides two overloaded remove() method: remove(int index) : Accept index of the object to be removed. We can pass the last elements index to the remove() method to delete the last element. remove(Object obj) : Accept object to be removed. If the ArrayList does not contain duplicates, we can simply pass the last element value to be deleted to the remove() method, and it will delete that value.Note: Incase the ArrayList contains duplicates, it will delete the first occurrence of the object passed as a parameter to the remove() method. Note: Incase the ArrayList contains duplicates, it will delete the first occurrence of the object passed as a parameter to the remove() method. Below is the implementation to delete the last element using the two approaches: Program 1: Using remove(int index). Calculate the last element’s index using the size() method as:index = ArrayList.size() - 1; // Java program to delete last element of ArrayListimport java.util.List;import java.util.ArrayList; public class GFG { public static void main(String[] args) { List<Integer> al = new ArrayList<>(); al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // Calculate index of last element int index = al.size() - 1; // Delete last element by passing index al.remove(index); System.out.println("Modified ArrayList : " + al); }}Output:Modified ArrayList : [10, 20, 30, 1] index = ArrayList.size() - 1; // Java program to delete last element of ArrayListimport java.util.List;import java.util.ArrayList; public class GFG { public static void main(String[] args) { List<Integer> al = new ArrayList<>(); al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // Calculate index of last element int index = al.size() - 1; // Delete last element by passing index al.remove(index); System.out.println("Modified ArrayList : " + al); }} Modified ArrayList : [10, 20, 30, 1] Program 2: Using remove(Object obj).// Java program to delete last element of ArrayListimport java.util.List;import java.util.ArrayList; public class GFG { public static void main(String[] args) { List<Integer> al = new ArrayList<>(); al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // Since all elements are unique, pass the last // elements value to delete it // Note: values are integer object al.remove(new Integer(2)); System.out.println("Modified ArrayList : " + al); }}Output:Modified ArrayList : [10, 20, 30, 1] // Java program to delete last element of ArrayListimport java.util.List;import java.util.ArrayList; public class GFG { public static void main(String[] args) { List<Integer> al = new ArrayList<>(); al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // Since all elements are unique, pass the last // elements value to delete it // Note: values are integer object al.remove(new Integer(2)); System.out.println("Modified ArrayList : " + al); }} Modified ArrayList : [10, 20, 30, 1] Java-ArrayList Java Java Programs 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 Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jan, 2020" }, { "code": null, "e": 126, "s": 28, "text": "Given an ArrayList collection in Java, the task is to remove the last element from the ArrayList." }, { "code": null, "e": 135, "s": 126, "text": "Example:" }, { "code": null, "e": 394, "s": 135, "text": "Input: ArrayList[] = [10, 20, 30, 1, 2]\nOutput: [10, 20, 30, 1]\nAfter removing the last element 2, the ArrayList is:\n[10, 20, 30, 1]\n\nInput: ArrayList[] = [1, 1, 2, 2, 3]\nOutput: [1, 1, 2, 2]\nAfter removing the last element 3, the ArrayList is:\n[1, 1, 2, 2]\n" }, { "code": null, "e": 484, "s": 394, "text": "We can use the remove() method of ArrayList container in Java to remove the last element." }, { "code": null, "e": 535, "s": 484, "text": "ArrayList provides two overloaded remove() method:" }, { "code": null, "e": 684, "s": 535, "text": "remove(int index) : Accept index of the object to be removed. We can pass the last elements index to the remove() method to delete the last element." }, { "code": null, "e": 1034, "s": 684, "text": "remove(Object obj) : Accept object to be removed. If the ArrayList does not contain duplicates, we can simply pass the last element value to be deleted to the remove() method, and it will delete that value.Note: Incase the ArrayList contains duplicates, it will delete the first occurrence of the object passed as a parameter to the remove() method." }, { "code": null, "e": 1178, "s": 1034, "text": "Note: Incase the ArrayList contains duplicates, it will delete the first occurrence of the object passed as a parameter to the remove() method." }, { "code": null, "e": 1259, "s": 1178, "text": "Below is the implementation to delete the last element using the two approaches:" }, { "code": null, "e": 1954, "s": 1259, "text": "Program 1: Using remove(int index). Calculate the last element’s index using the size() method as:index = ArrayList.size() - 1;\n// Java program to delete last element of ArrayListimport java.util.List;import java.util.ArrayList; public class GFG { public static void main(String[] args) { List<Integer> al = new ArrayList<>(); al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // Calculate index of last element int index = al.size() - 1; // Delete last element by passing index al.remove(index); System.out.println(\"Modified ArrayList : \" + al); }}Output:Modified ArrayList : [10, 20, 30, 1]\n" }, { "code": null, "e": 1985, "s": 1954, "text": "index = ArrayList.size() - 1;\n" }, { "code": "// Java program to delete last element of ArrayListimport java.util.List;import java.util.ArrayList; public class GFG { public static void main(String[] args) { List<Integer> al = new ArrayList<>(); al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // Calculate index of last element int index = al.size() - 1; // Delete last element by passing index al.remove(index); System.out.println(\"Modified ArrayList : \" + al); }}", "e": 2508, "s": 1985, "text": null }, { "code": null, "e": 2546, "s": 2508, "text": "Modified ArrayList : [10, 20, 30, 1]\n" }, { "code": null, "e": 3168, "s": 2546, "text": "Program 2: Using remove(Object obj).// Java program to delete last element of ArrayListimport java.util.List;import java.util.ArrayList; public class GFG { public static void main(String[] args) { List<Integer> al = new ArrayList<>(); al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // Since all elements are unique, pass the last // elements value to delete it // Note: values are integer object al.remove(new Integer(2)); System.out.println(\"Modified ArrayList : \" + al); }}Output:Modified ArrayList : [10, 20, 30, 1]\n" }, { "code": "// Java program to delete last element of ArrayListimport java.util.List;import java.util.ArrayList; public class GFG { public static void main(String[] args) { List<Integer> al = new ArrayList<>(); al.add(10); al.add(20); al.add(30); al.add(1); al.add(2); // Since all elements are unique, pass the last // elements value to delete it // Note: values are integer object al.remove(new Integer(2)); System.out.println(\"Modified ArrayList : \" + al); }}", "e": 3710, "s": 3168, "text": null }, { "code": null, "e": 3748, "s": 3710, "text": "Modified ArrayList : [10, 20, 30, 1]\n" }, { "code": null, "e": 3763, "s": 3748, "text": "Java-ArrayList" }, { "code": null, "e": 3768, "s": 3763, "text": "Java" }, { "code": null, "e": 3782, "s": 3768, "text": "Java Programs" }, { "code": null, "e": 3787, "s": 3782, "text": "Java" }, { "code": null, "e": 3885, "s": 3787, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3936, "s": 3885, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3967, "s": 3936, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3986, "s": 3967, "text": "Interfaces in Java" }, { "code": null, "e": 4016, "s": 3986, "text": "HashMap in Java with Examples" }, { "code": null, "e": 4034, "s": 4016, "text": "ArrayList in Java" }, { "code": null, "e": 4062, "s": 4034, "text": "Initializing a List in Java" }, { "code": null, "e": 4088, "s": 4062, "text": "Java Programming Examples" }, { "code": null, "e": 4132, "s": 4088, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 4166, "s": 4132, "text": "Convert Double to Integer in Java" } ]
Scala Type Hierarchy
01 Apr, 2019 There are no primitive types in Scala(unlike java). All data types in Scala are objects that have methods to operate on their data. All of Scala’s types exist as part of a type hierarchy. Every class that we define in Scala will also belong to this hierarchy automatically. Any is the superclass of all classes, also called the top class. It defines certain universal methods such as equals, hashCode, and toString. Any has two direct subclasses: AnyVal AnyRef .Example: // Scala program of Scala Type hierarchy // Creating objectobject Geeks { // Main method def main(args: Array[String]) { val list: List[Any] = List( false, 66677, 732, 'a', "abs" ) list.foreach(element => println(element)) }} false 66677 732 a abs AnyVal represents value classes. All value classes are predefined; they correspond to the primitive types of Java-like languages. There are nine predefined value types and they are non-null able: Double, Float, Long, Int, Short, Byte, Char, Unit, and Boolean. Scala has both numeric (e.g., Int and Double) and non-numeric types (e.g., String) that can be used to define values and variables. Boolean variables can only be true or false. Char literals are written with single-quotes. Example: // Scala program of Scala Type hierarchy// Using AnyVal. // Creating Objectobject Geeks { // Main method def main(args: Array[String]) { val list: List[AnyVal] = List( 333, true, false ) list.foreach(element => println(element)) }} 333 true false AnyRef represents reference classes. All non-value types are defined as reference types. User-defined classes define reference types by default; i.e. they always (indirectly) subclass scala.AnyRef. scala.AnyRef in java programming corresponds to java.lang.Object. Example: // Scala program of Scala Type hierarchy // Using AnyRef // Creating objectobject Geeks{ // Main method def main(args: Array[String]) { val list: List[AnyRef] = List( "GFG", "GEEKSFORGEEKS" ) list.foreach(element => println(element)) }} GFG GEEKSFORGEEKS Nothing and Null:Nothing is a subclassify of all value types, it is also called the bottom type. Type Nothing That has no value. we can use Nothing to signal non-termination such as a thrown exception, program exit, or an infinite loop . Null is a subclassify of all reference types. the keyword literal null can identify a single value. Null is provided mostly for interoperability with other JVM languages. Picked Scala scala-parameterized-type Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Apr, 2019" }, { "code": null, "e": 216, "s": 28, "text": "There are no primitive types in Scala(unlike java). All data types in Scala are objects that have methods to operate on their data. All of Scala’s types exist as part of a type hierarchy." }, { "code": null, "e": 302, "s": 216, "text": "Every class that we define in Scala will also belong to this hierarchy automatically." }, { "code": null, "e": 475, "s": 302, "text": "Any is the superclass of all classes, also called the top class. It defines certain universal methods such as equals, hashCode, and toString. Any has two direct subclasses:" }, { "code": null, "e": 482, "s": 475, "text": "AnyVal" }, { "code": null, "e": 489, "s": 482, "text": "AnyRef" }, { "code": null, "e": 499, "s": 489, "text": ".Example:" }, { "code": "// Scala program of Scala Type hierarchy // Creating objectobject Geeks { // Main method def main(args: Array[String]) { val list: List[Any] = List( false, 66677, 732, 'a', \"abs\" ) list.foreach(element => println(element)) }}", "e": 854, "s": 499, "text": null }, { "code": null, "e": 877, "s": 854, "text": "false\n66677\n732\na\nabs\n" }, { "code": null, "e": 1361, "s": 877, "text": " AnyVal represents value classes. All value classes are predefined; they correspond to the primitive types of Java-like languages. There are nine predefined value types and they are non-null able: Double, Float, Long, Int, Short, Byte, Char, Unit, and Boolean. Scala has both numeric (e.g., Int and Double) and non-numeric types (e.g., String) that can be used to define values and variables. Boolean variables can only be true or false. Char literals are written with single-quotes." }, { "code": null, "e": 1370, "s": 1361, "text": "Example:" }, { "code": "// Scala program of Scala Type hierarchy// Using AnyVal. // Creating Objectobject Geeks { // Main method def main(args: Array[String]) { val list: List[AnyVal] = List( 333, true, false ) list.foreach(element => println(element)) }}", "e": 1657, "s": 1370, "text": null }, { "code": null, "e": 1673, "s": 1657, "text": "333\ntrue\nfalse\n" }, { "code": null, "e": 1938, "s": 1673, "text": " AnyRef represents reference classes. All non-value types are defined as reference types. User-defined classes define reference types by default; i.e. they always (indirectly) subclass scala.AnyRef. scala.AnyRef in java programming corresponds to java.lang.Object." }, { "code": null, "e": 1947, "s": 1938, "text": "Example:" }, { "code": "// Scala program of Scala Type hierarchy // Using AnyRef // Creating objectobject Geeks{ // Main method def main(args: Array[String]) { val list: List[AnyRef] = List( \"GFG\", \"GEEKSFORGEEKS\" ) list.foreach(element => println(element)) }}", "e": 2233, "s": 1947, "text": null }, { "code": null, "e": 2252, "s": 2233, "text": "GFG\nGEEKSFORGEEKS\n" }, { "code": null, "e": 2491, "s": 2252, "text": " Nothing and Null:Nothing is a subclassify of all value types, it is also called the bottom type. Type Nothing That has no value. we can use Nothing to signal non-termination such as a thrown exception, program exit, or an infinite loop ." }, { "code": null, "e": 2662, "s": 2491, "text": "Null is a subclassify of all reference types. the keyword literal null can identify a single value. Null is provided mostly for interoperability with other JVM languages." }, { "code": null, "e": 2669, "s": 2662, "text": "Picked" }, { "code": null, "e": 2675, "s": 2669, "text": "Scala" }, { "code": null, "e": 2700, "s": 2675, "text": "scala-parameterized-type" }, { "code": null, "e": 2706, "s": 2700, "text": "Scala" } ]
Flutter - Dialogs - GeeksforGeeks
15 Feb, 2021 The dialog is a type of widget which comes on the window or the screen which contains any critical information or can ask for any decision. When a dialog box is popped up the all the other functions get disabled until you close the dialog box or provide an answer. We use a dialog box for a different type of condition such as alert notification, simple notification in which different options are shown, or we can also make a dialog box which can be used as a tab for showing the dialog box. AlertDialog SimpleDialog showDialog Alert dialog tells the user about any condition that requires any recognition. The alert dialog contains an optional title and an optional list of actions. We have different no of actions as our requirements. Sometimes the content is too large as compared to the screen size so for resolving this problem we may have to use the expanded class. Title: It is always recommended to make our dialog title as short as possible. It will be easily understandable to the user. Action: It is used to show the content for what action has to perform. Content: The body of the alertDialog widget is defined by the content. Shape: It is used to define the shape of our dialog box whether it is circular, curve, and many more. AlertDialog( { Key key, Widget title, EdgeInsetsGeometry titlePadding, TextStyle titleTextStyle, Widget content, EdgeInsetsGeometry contentPadding: const EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 24.0), TextStyle contentTextStyle, List<Widget> actions, EdgeInsetsGeometry actionsPadding: EdgeInsets.zero, VerticalDirection actionsOverflowDirection, double actionsOverflowButtonSpacing, EdgeInsetsGeometry buttonPadding, Color backgroundColor, double elevation, String semanticLabel, EdgeInsets insetPadding: _defaultInsetPadding, Clip clipBehavior: Clip.none, ShapeBorder shape, bool scrollable: false } ) Here is the snippet code for creating a dialog box. Dart AlertDialog( title: Text('Welcome'), // To display the title it is optional content: Text('GeeksforGeeks'), // Message which will be pop up on the screen // Action widget which will provide the user to acknowledge the choice actions: [ FlatButton( // FlatButton widget is used to make a text to work like a button textColor: Colors.black, onPressed: () {}, // function used to perform after pressing the button child: Text('CANCEL'), ), FlatButton( textColor: Colors.black, onPressed: () {}, child: Text('ACCEPT'), ), ], ), Output: Alert dialog A simple dialog allows the user to choose from different choices. It contains the title which is optional and presents above the choices. We can show options by using the padding also. Padding is used to make a widget more flexible. Title: It is always recommended to make our dialog title as short as possible. It will be easily understandable to the user. Shape: It is used to define the shape of our dialog box whether it is circular, curve, and many more. backgroundcolor: It is used to set the background color of our dialog box. TextStyle: It is used to change the style of our text. const SimpleDialog( { Key key, Widget title, EdgeInsetsGeometry titlePadding: const EdgeInsets.fromLTRB(24.0, 24.0, 24.0, 0.0), TextStyle titleTextStyle, List<Widget> children, EdgeInsetsGeometry contentPadding: const EdgeInsets.fromLTRB(0.0, 12.0, 0.0, 16.0), Color backgroundColor, double elevation, String semanticLabel, ShapeBorder shape } ) Here is the snippet code for Simple dialog Dart SimpleDialog( title:const Text('GeeksforGeeks'), children: <Widget>[ SimpleDialogOption( onPressed: () { }, child:const Text('Option 1'), ), SimpleDialogOption( onPressed: () { }, child: const Text('Option 2'), ), ], ), Output: SimpleDialog It basically used to change the current screen of our app to show the dialog popup. You must call before the dialog popup. It exits the current animation and presents a new screen animation. We use this dialog box when we want to show a tab which will popup any type of dialog box, or we create a front tab to show the background process. Builder: It returns the child instead of creating a child argument. Barriercolor: It defines the modal barrier color which darkens everything in the dialog. useSafeArea: It makes sure that the dialog uses the safe area of the screen only nor overlapping the screen area. Future<T> showDialog <T>( { @required BuildContext context, WidgetBuilder builder, bool barrierDismissible: true, Color barrierColor, bool useSafeArea: true, bool useRootNavigator: true, RouteSettings routeSettings, @Deprecated(It returns the child from the closure provided to the builder class ) Widget child } ) Here is the snippet for the showDialog function. Dart showDialog( context: context, builder: (BuildContext context) { return Expanded( child: AlertDialog( title: Text('Welcome'), content: Text('GeeksforGeeks'), actions: [ FlatButton( textColor: Colors.black, onPressed: () {}, child: Text('CANCEL'), ), FlatButton( textColor: Colors.black, onPressed: () {}, child: Text('ACCEPT'), ), ], ), ); }, ); Used to show any type of alert notification. We can give the option to react for the alert popup like the accept button or reject button. Used to show simple option as a dialog box. There are different options to choose and perform functions according to it. The option can be simple like choosing between different emails. Used to create an option that will popup a dialog box. By using this we can popup different types of dialog boxes like alertDialog, SimpleDialog as a sub widget. android Flutter Flutter UI-components Flutter-widgets Picked Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Listview.builder in Flutter Flutter - Asset Image Flutter - Custom Bottom Navigation Bar Splash Screen in Flutter Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget Flutter - BoxShadow Widget Flutter - Flexible Widget
[ { "code": null, "e": 25914, "s": 25886, "text": "\n15 Feb, 2021" }, { "code": null, "e": 26407, "s": 25914, "text": "The dialog is a type of widget which comes on the window or the screen which contains any critical information or can ask for any decision. When a dialog box is popped up the all the other functions get disabled until you close the dialog box or provide an answer. We use a dialog box for a different type of condition such as alert notification, simple notification in which different options are shown, or we can also make a dialog box which can be used as a tab for showing the dialog box." }, { "code": null, "e": 26419, "s": 26407, "text": "AlertDialog" }, { "code": null, "e": 26432, "s": 26419, "text": "SimpleDialog" }, { "code": null, "e": 26443, "s": 26432, "text": "showDialog" }, { "code": null, "e": 26788, "s": 26443, "text": "Alert dialog tells the user about any condition that requires any recognition. The alert dialog contains an optional title and an optional list of actions. We have different no of actions as our requirements. Sometimes the content is too large as compared to the screen size so for resolving this problem we may have to use the expanded class." }, { "code": null, "e": 26913, "s": 26788, "text": "Title: It is always recommended to make our dialog title as short as possible. It will be easily understandable to the user." }, { "code": null, "e": 26984, "s": 26913, "text": "Action: It is used to show the content for what action has to perform." }, { "code": null, "e": 27055, "s": 26984, "text": "Content: The body of the alertDialog widget is defined by the content." }, { "code": null, "e": 27157, "s": 27055, "text": "Shape: It is used to define the shape of our dialog box whether it is circular, curve, and many more." }, { "code": null, "e": 28146, "s": 27157, "text": "AlertDialog(\n {\n Key key,\n Widget title,\n EdgeInsetsGeometry titlePadding,\n TextStyle titleTextStyle,\n Widget content,\n EdgeInsetsGeometry contentPadding: const EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 24.0),\n TextStyle contentTextStyle,\n List<Widget> actions,\n EdgeInsetsGeometry actionsPadding: EdgeInsets.zero,\n VerticalDirection actionsOverflowDirection,\n double actionsOverflowButtonSpacing,\n EdgeInsetsGeometry buttonPadding,\n Color backgroundColor,\n double elevation,\n String semanticLabel,\n EdgeInsets insetPadding: _defaultInsetPadding,\n Clip clipBehavior: Clip.none,\n ShapeBorder shape,\n bool scrollable: false\n }\n)\n\n" }, { "code": null, "e": 28198, "s": 28146, "text": "Here is the snippet code for creating a dialog box." }, { "code": null, "e": 28203, "s": 28198, "text": "Dart" }, { "code": "AlertDialog( title: Text('Welcome'), // To display the title it is optional content: Text('GeeksforGeeks'), // Message which will be pop up on the screen // Action widget which will provide the user to acknowledge the choice actions: [ FlatButton( // FlatButton widget is used to make a text to work like a button textColor: Colors.black, onPressed: () {}, // function used to perform after pressing the button child: Text('CANCEL'), ), FlatButton( textColor: Colors.black, onPressed: () {}, child: Text('ACCEPT'), ), ], ),", "e": 28987, "s": 28203, "text": null }, { "code": null, "e": 28995, "s": 28987, "text": "Output:" }, { "code": null, "e": 29009, "s": 28995, "text": "Alert dialog " }, { "code": null, "e": 29242, "s": 29009, "text": "A simple dialog allows the user to choose from different choices. It contains the title which is optional and presents above the choices. We can show options by using the padding also. Padding is used to make a widget more flexible." }, { "code": null, "e": 29367, "s": 29242, "text": "Title: It is always recommended to make our dialog title as short as possible. It will be easily understandable to the user." }, { "code": null, "e": 29469, "s": 29367, "text": "Shape: It is used to define the shape of our dialog box whether it is circular, curve, and many more." }, { "code": null, "e": 29544, "s": 29469, "text": "backgroundcolor: It is used to set the background color of our dialog box." }, { "code": null, "e": 29599, "s": 29544, "text": "TextStyle: It is used to change the style of our text." }, { "code": null, "e": 30106, "s": 29599, "text": "const SimpleDialog(\n {\n Key key,\n Widget title,\n EdgeInsetsGeometry titlePadding: const EdgeInsets.fromLTRB(24.0, 24.0, 24.0, 0.0),\n TextStyle titleTextStyle,\n List<Widget> children,\n EdgeInsetsGeometry contentPadding: const EdgeInsets.fromLTRB(0.0, 12.0, 0.0, 16.0),\n Color backgroundColor,\n double elevation,\n String semanticLabel,\n ShapeBorder shape\n }\n)\n" }, { "code": null, "e": 30149, "s": 30106, "text": "Here is the snippet code for Simple dialog" }, { "code": null, "e": 30154, "s": 30149, "text": "Dart" }, { "code": "SimpleDialog( title:const Text('GeeksforGeeks'), children: <Widget>[ SimpleDialogOption( onPressed: () { }, child:const Text('Option 1'), ), SimpleDialogOption( onPressed: () { }, child: const Text('Option 2'), ), ], ),", "e": 30674, "s": 30154, "text": null }, { "code": null, "e": 30682, "s": 30674, "text": "Output:" }, { "code": null, "e": 30695, "s": 30682, "text": "SimpleDialog" }, { "code": null, "e": 31034, "s": 30695, "text": "It basically used to change the current screen of our app to show the dialog popup. You must call before the dialog popup. It exits the current animation and presents a new screen animation. We use this dialog box when we want to show a tab which will popup any type of dialog box, or we create a front tab to show the background process." }, { "code": null, "e": 31102, "s": 31034, "text": "Builder: It returns the child instead of creating a child argument." }, { "code": null, "e": 31191, "s": 31102, "text": "Barriercolor: It defines the modal barrier color which darkens everything in the dialog." }, { "code": null, "e": 31305, "s": 31191, "text": "useSafeArea: It makes sure that the dialog uses the safe area of the screen only nor overlapping the screen area." }, { "code": null, "e": 31717, "s": 31305, "text": "Future<T> showDialog <T>(\n {\n @required BuildContext context,\n WidgetBuilder builder,\n bool barrierDismissible: true,\n Color barrierColor,\n bool useSafeArea: true,\n bool useRootNavigator: true,\n RouteSettings routeSettings,\n @Deprecated(It returns the child from the closure provided to the builder class ) Widget child\n }\n)\n" }, { "code": null, "e": 31766, "s": 31717, "text": "Here is the snippet for the showDialog function." }, { "code": null, "e": 31771, "s": 31766, "text": "Dart" }, { "code": "showDialog( context: context, builder: (BuildContext context) { return Expanded( child: AlertDialog( title: Text('Welcome'), content: Text('GeeksforGeeks'), actions: [ FlatButton( textColor: Colors.black, onPressed: () {}, child: Text('CANCEL'), ), FlatButton( textColor: Colors.black, onPressed: () {}, child: Text('ACCEPT'), ), ], ), ); }, );", "e": 32618, "s": 31771, "text": null }, { "code": null, "e": 32663, "s": 32618, "text": "Used to show any type of alert notification." }, { "code": null, "e": 32756, "s": 32663, "text": "We can give the option to react for the alert popup like the accept button or reject button." }, { "code": null, "e": 32800, "s": 32756, "text": "Used to show simple option as a dialog box." }, { "code": null, "e": 32942, "s": 32800, "text": "There are different options to choose and perform functions according to it. The option can be simple like choosing between different emails." }, { "code": null, "e": 32997, "s": 32942, "text": "Used to create an option that will popup a dialog box." }, { "code": null, "e": 33104, "s": 32997, "text": "By using this we can popup different types of dialog boxes like alertDialog, SimpleDialog as a sub widget." }, { "code": null, "e": 33112, "s": 33104, "text": "android" }, { "code": null, "e": 33120, "s": 33112, "text": "Flutter" }, { "code": null, "e": 33142, "s": 33120, "text": "Flutter UI-components" }, { "code": null, "e": 33158, "s": 33142, "text": "Flutter-widgets" }, { "code": null, "e": 33165, "s": 33158, "text": "Picked" }, { "code": null, "e": 33170, "s": 33165, "text": "Dart" }, { "code": null, "e": 33178, "s": 33170, "text": "Flutter" }, { "code": null, "e": 33276, "s": 33178, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33308, "s": 33276, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 33336, "s": 33308, "text": "Listview.builder in Flutter" }, { "code": null, "e": 33358, "s": 33336, "text": "Flutter - Asset Image" }, { "code": null, "e": 33397, "s": 33358, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 33422, "s": 33397, "text": "Splash Screen in Flutter" }, { "code": null, "e": 33454, "s": 33422, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 33493, "s": 33454, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 33519, "s": 33493, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 33546, "s": 33519, "text": "Flutter - BoxShadow Widget" } ]
How to draw a circle in R?
There is no direct function in R to draw a circle but we can make use of plotrix package for this purpose. The plotrix package has a function called draw.cirlce which is can be used to draw a circle but we first need to draw a plot in base R then pass the correct arguments in draw.circle. The first and second arguments of draw.circle takes x and y coordinates, and the third one is for radius, hence these should be properly chosen based on the chart in base R. Loading plotrix package: > library(plotrix) Creating different circles using draw.circle: Live Demo > plot(1:10,type="n") > draw.circle(2,4,1) Live Demo > plot(1:10,type="n") > draw.circle(5,6,1)
[ { "code": null, "e": 1526, "s": 1062, "text": "There is no direct function in R to draw a circle but we can make use of plotrix package for this purpose. The plotrix package has a function called draw.cirlce which is can be used to draw a circle but we first need to draw a plot in base R then pass the correct arguments in draw.circle. The first and second arguments of draw.circle takes x and y coordinates, and the third one is for radius, hence these should be properly chosen based on the chart in base R." }, { "code": null, "e": 1551, "s": 1526, "text": "Loading plotrix package:" }, { "code": null, "e": 1570, "s": 1551, "text": "> library(plotrix)" }, { "code": null, "e": 1616, "s": 1570, "text": "Creating different circles using draw.circle:" }, { "code": null, "e": 1626, "s": 1616, "text": "Live Demo" }, { "code": null, "e": 1669, "s": 1626, "text": "> plot(1:10,type=\"n\")\n> draw.circle(2,4,1)" }, { "code": null, "e": 1679, "s": 1669, "text": "Live Demo" }, { "code": null, "e": 1722, "s": 1679, "text": "> plot(1:10,type=\"n\")\n> draw.circle(5,6,1)" } ]
Installing OpenCV in PiZero W. Most of us have faced issue in... | by Atul Singh | Towards Data Science
Most of us have faced issue in installing openCV in Pi.In this blog I will tell you step by step installation of opencv in your pi-zero W. While the Pi Zero isn’t quite fast enough for advanced video processing, it’s still a great tool that you can use to learn the basics of computer vision and OpenCV. I recomend you following this blog during night time as the compilation of OpenCV alone will takes 12+ hours. Lets Start.... 1> pi Zero W Hardware 2> SD card (minimum 16 GB ) 3> Any Raspbian OS (I have used Raspbian Buster) installed on your pi zero Assuming you have the given requirements lets start with the setup. Expand filesystem is rarely needed anymore as both NOOBs and the standalone install of Raspbian will automatically expand the filesystem on first boot. But just to make sure that the system is expanded run the following command: pi@raspberrypi:~ $ raspi-config --expand-rootfs Swap space is a portion of a hard disk drive (HDD) that is used for virtual memory. Having a swap file allows your computer’s operating system to pretend that you have more RAM than you actually do. This will increase up the compiling process of openCV. Otherwise you end up with memory exhausted error. To increase the Swapsize open the swap file of your pi zero using the following command: pi@raspberrypi:~ $ sudo nano /etc/dphys-swapfile Go to Swap size and change it to 2048 from 100. as show below. ...# where we want the swapfile to be, this is the default#CONF_SWAPFILE=/var/swap# set size to absolute value, leaving empty (default) then uses computed value# you most likely don't want this, unless you have an special disk situation#CONF_SWAPSIZE=100CONF_SWAPSIZE=2048... Reboot your system. pi@raspberrypi:~ $ sudo reboot First lets update & upgrade existing packages: pi@raspberrypi:~ $ sudo apt-get updatepi@raspberrypi:~ $ sudo apt-get upgrade If you are using Raspbian Buster run the following command: pi@raspberrypi:~ $sudo apt updatepi@raspberrypi:~ $sudo apt upgrade Enter “Y” when ever it prompts. Install developer tools: pi@raspberrypi:~ $ sudo apt-get install build-essential cmake pkg-config Install the IO packages: pi@raspberrypi:~ $ sudo apt-get install libjpeg-dev libtiff5-dev libjasper-dev libpng12-dev Along with some video I/O packages (although it’s unlikely that you’ll be doing a lot of video processing with the Raspberry Pi Zero): pi@raspberrypi:~ $ sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-devpi@raspberrypi:~ $ sudo apt-get install libxvidcore-dev libx264-dev We’ll need to install the GTK development library for OpenCV’s GUI interface: pi@raspberrypi:~ $ sudo apt-get install libgtk2.0-dev And routine optimization packages leveraged by OpenCV: pi@raspberrypi:~ $sudo apt-get install libatlas-base-dev gfortran So Now we have all the dependencies. Lets pull the release of opencv from OpenCV github. Note that I have pulled release version 3.4.1. You can try it for other version as well. Just replace the release version number. pi@raspberrypi:~ $cd ~pi@raspberrypi:~ $ wget -O opencv.zip https://github.com/Itseez/opencv/archive/3.4.1.zippi@raspberrypi:~ $unzip opencv.zip Along with it lets grab the opencv Contrib because SIFT and SURF have been removed from the default install of OpenCV: pi@raspberrypi:~ $ wget -O opencv_contrib.zip https://github.com/Itseez/opencv_contrib/archive/3.4.1.zippi@raspberrypi:~ $ unzip opencv_contrib.zip Once both of the repository are downloaded and expanded in your system It is a better idea to remove them so as to free some space. pi@raspberrypi:~ $ rm opencv.zip opencv_contrib.zip If you already have python2.7 installed in your system you can skip this step else install the Python 2.7 headers so wen can compile our OpenCV + Python bindings: pi@raspberrypi:~ $ sudo apt-get install python2.7-dev After which install pip , a python package manager. pi@raspberrypi:~ $ wget https://bootstrap.pypa.io/get-pip.pypi@raspberrypi:~ $ sudo python get-pip.py The only requirement to build Python + OpenCV bindings is to have NumPy installed, so install NumPy using pip: pi@raspberrypi:~ $ pip install numpy Now We are ready to compile and install OpenCV. Build the files: pi@raspberrypi:~ $ cd ~/opencv-3.4.1/pi@raspberrypi:~ $ mkdir buildpi@raspberrypi:~ $ cd buildpi@raspberrypi:~ $ cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_C_EXAMPLES=ON \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-3.0.0/modules \ -D BUILD_EXAMPLES=ON .. Now Its time to compile. Remember Compiling it self may take more than 9+ hours and there may be points when you will think that the system has freezed. But dont loose patience and let the system work till the time you dont see any error. pi@raspberrypi:~$ make Assuming your file compiled successfully without any error will Now install opencv using the following command. pi@raspberrypi:~$ sudo make installpi@raspberrypi:~$ sudo ldconfig Check the path for cv2.so file : find / -name “cv2.so” pi@raspberrypi:~$ /usr/local/python/cv2/python-2.7/cv2.so All you have to do now is to sym-link the cv2.so file(binding file) into the site-packages of python lib. pi@raspberrypi:~$ cd /usr/local/lib/python2.7/site-packages Run the following commnad: ln -s [path to cv2.so file] cv2.so. In my case it is as follow: pi@raspberrypi:~$/usr/local/lib/python2.7/site-packages $ ln -s /usr/local/python/cv2/python-2.7/cv2.so cv2.so Now is the time to Verify our openCV installation. fire up a Python shell and import the OpenCV bindings: pi@raspberrypi:/usr/local/lib/python2.7/site-packages$ pythonimport cv2>>> cv2.__version__3.4.1’ Thats It Now you have a freshly install openCV installed on your system. Now export the path python can access it from anywhere. pi@raspberrypi:~$ export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH You can now remove both the opencv-3.4.1 and opencv_contrib-3.4.1 directories, freeing up a bunch of space on your filesystem: But be cautious before you run this command! Make sure OpenCV has been properly installed on your system before blowing away these directories, otherwise you will have to start the (long, 12+ hour) compile all over again! If you encounter any error let me know in the comment section. If you want OpenCV for python3 then you can simply use sym-link to point the binding file to your python3 site-package and export the path
[ { "code": null, "e": 310, "s": 171, "text": "Most of us have faced issue in installing openCV in Pi.In this blog I will tell you step by step installation of opencv in your pi-zero W." }, { "code": null, "e": 585, "s": 310, "text": "While the Pi Zero isn’t quite fast enough for advanced video processing, it’s still a great tool that you can use to learn the basics of computer vision and OpenCV. I recomend you following this blog during night time as the compilation of OpenCV alone will takes 12+ hours." }, { "code": null, "e": 600, "s": 585, "text": "Lets Start...." }, { "code": null, "e": 622, "s": 600, "text": "1> pi Zero W Hardware" }, { "code": null, "e": 650, "s": 622, "text": "2> SD card (minimum 16 GB )" }, { "code": null, "e": 725, "s": 650, "text": "3> Any Raspbian OS (I have used Raspbian Buster) installed on your pi zero" }, { "code": null, "e": 793, "s": 725, "text": "Assuming you have the given requirements lets start with the setup." }, { "code": null, "e": 1022, "s": 793, "text": "Expand filesystem is rarely needed anymore as both NOOBs and the standalone install of Raspbian will automatically expand the filesystem on first boot. But just to make sure that the system is expanded run the following command:" }, { "code": null, "e": 1070, "s": 1022, "text": "pi@raspberrypi:~ $ raspi-config --expand-rootfs" }, { "code": null, "e": 1374, "s": 1070, "text": "Swap space is a portion of a hard disk drive (HDD) that is used for virtual memory. Having a swap file allows your computer’s operating system to pretend that you have more RAM than you actually do. This will increase up the compiling process of openCV. Otherwise you end up with memory exhausted error." }, { "code": null, "e": 1463, "s": 1374, "text": "To increase the Swapsize open the swap file of your pi zero using the following command:" }, { "code": null, "e": 1512, "s": 1463, "text": "pi@raspberrypi:~ $ sudo nano /etc/dphys-swapfile" }, { "code": null, "e": 1575, "s": 1512, "text": "Go to Swap size and change it to 2048 from 100. as show below." }, { "code": null, "e": 1853, "s": 1575, "text": "...# where we want the swapfile to be, this is the default#CONF_SWAPFILE=/var/swap# set size to absolute value, leaving empty (default) then uses computed value# you most likely don't want this, unless you have an special disk situation#CONF_SWAPSIZE=100CONF_SWAPSIZE=2048..." }, { "code": null, "e": 1873, "s": 1853, "text": "Reboot your system." }, { "code": null, "e": 1904, "s": 1873, "text": "pi@raspberrypi:~ $ sudo reboot" }, { "code": null, "e": 1951, "s": 1904, "text": "First lets update & upgrade existing packages:" }, { "code": null, "e": 2029, "s": 1951, "text": "pi@raspberrypi:~ $ sudo apt-get updatepi@raspberrypi:~ $ sudo apt-get upgrade" }, { "code": null, "e": 2089, "s": 2029, "text": "If you are using Raspbian Buster run the following command:" }, { "code": null, "e": 2157, "s": 2089, "text": "pi@raspberrypi:~ $sudo apt updatepi@raspberrypi:~ $sudo apt upgrade" }, { "code": null, "e": 2189, "s": 2157, "text": "Enter “Y” when ever it prompts." }, { "code": null, "e": 2214, "s": 2189, "text": "Install developer tools:" }, { "code": null, "e": 2287, "s": 2214, "text": "pi@raspberrypi:~ $ sudo apt-get install build-essential cmake pkg-config" }, { "code": null, "e": 2312, "s": 2287, "text": "Install the IO packages:" }, { "code": null, "e": 2404, "s": 2312, "text": "pi@raspberrypi:~ $ sudo apt-get install libjpeg-dev libtiff5-dev libjasper-dev libpng12-dev" }, { "code": null, "e": 2539, "s": 2404, "text": "Along with some video I/O packages (although it’s unlikely that you’ll be doing a lot of video processing with the Raspberry Pi Zero):" }, { "code": null, "e": 2703, "s": 2539, "text": "pi@raspberrypi:~ $ sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-devpi@raspberrypi:~ $ sudo apt-get install libxvidcore-dev libx264-dev" }, { "code": null, "e": 2781, "s": 2703, "text": "We’ll need to install the GTK development library for OpenCV’s GUI interface:" }, { "code": null, "e": 2835, "s": 2781, "text": "pi@raspberrypi:~ $ sudo apt-get install libgtk2.0-dev" }, { "code": null, "e": 2890, "s": 2835, "text": "And routine optimization packages leveraged by OpenCV:" }, { "code": null, "e": 2956, "s": 2890, "text": "pi@raspberrypi:~ $sudo apt-get install libatlas-base-dev gfortran" }, { "code": null, "e": 3045, "s": 2956, "text": "So Now we have all the dependencies. Lets pull the release of opencv from OpenCV github." }, { "code": null, "e": 3175, "s": 3045, "text": "Note that I have pulled release version 3.4.1. You can try it for other version as well. Just replace the release version number." }, { "code": null, "e": 3320, "s": 3175, "text": "pi@raspberrypi:~ $cd ~pi@raspberrypi:~ $ wget -O opencv.zip https://github.com/Itseez/opencv/archive/3.4.1.zippi@raspberrypi:~ $unzip opencv.zip" }, { "code": null, "e": 3439, "s": 3320, "text": "Along with it lets grab the opencv Contrib because SIFT and SURF have been removed from the default install of OpenCV:" }, { "code": null, "e": 3587, "s": 3439, "text": "pi@raspberrypi:~ $ wget -O opencv_contrib.zip https://github.com/Itseez/opencv_contrib/archive/3.4.1.zippi@raspberrypi:~ $ unzip opencv_contrib.zip" }, { "code": null, "e": 3719, "s": 3587, "text": "Once both of the repository are downloaded and expanded in your system It is a better idea to remove them so as to free some space." }, { "code": null, "e": 3771, "s": 3719, "text": "pi@raspberrypi:~ $ rm opencv.zip opencv_contrib.zip" }, { "code": null, "e": 3934, "s": 3771, "text": "If you already have python2.7 installed in your system you can skip this step else install the Python 2.7 headers so wen can compile our OpenCV + Python bindings:" }, { "code": null, "e": 3988, "s": 3934, "text": "pi@raspberrypi:~ $ sudo apt-get install python2.7-dev" }, { "code": null, "e": 4040, "s": 3988, "text": "After which install pip , a python package manager." }, { "code": null, "e": 4142, "s": 4040, "text": "pi@raspberrypi:~ $ wget https://bootstrap.pypa.io/get-pip.pypi@raspberrypi:~ $ sudo python get-pip.py" }, { "code": null, "e": 4253, "s": 4142, "text": "The only requirement to build Python + OpenCV bindings is to have NumPy installed, so install NumPy using pip:" }, { "code": null, "e": 4290, "s": 4253, "text": "pi@raspberrypi:~ $ pip install numpy" }, { "code": null, "e": 4338, "s": 4290, "text": "Now We are ready to compile and install OpenCV." }, { "code": null, "e": 4355, "s": 4338, "text": "Build the files:" }, { "code": null, "e": 4701, "s": 4355, "text": "pi@raspberrypi:~ $ cd ~/opencv-3.4.1/pi@raspberrypi:~ $ mkdir buildpi@raspberrypi:~ $ cd buildpi@raspberrypi:~ $ cmake -D CMAKE_BUILD_TYPE=RELEASE \\ -D CMAKE_INSTALL_PREFIX=/usr/local \\ -D INSTALL_C_EXAMPLES=ON \\ -D INSTALL_PYTHON_EXAMPLES=ON \\ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-3.0.0/modules \\ -D BUILD_EXAMPLES=ON .." }, { "code": null, "e": 4940, "s": 4701, "text": "Now Its time to compile. Remember Compiling it self may take more than 9+ hours and there may be points when you will think that the system has freezed. But dont loose patience and let the system work till the time you dont see any error." }, { "code": null, "e": 4963, "s": 4940, "text": "pi@raspberrypi:~$ make" }, { "code": null, "e": 5075, "s": 4963, "text": "Assuming your file compiled successfully without any error will Now install opencv using the following command." }, { "code": null, "e": 5142, "s": 5075, "text": "pi@raspberrypi:~$ sudo make installpi@raspberrypi:~$ sudo ldconfig" }, { "code": null, "e": 5175, "s": 5142, "text": "Check the path for cv2.so file :" }, { "code": null, "e": 5197, "s": 5175, "text": "find / -name “cv2.so”" }, { "code": null, "e": 5255, "s": 5197, "text": "pi@raspberrypi:~$ /usr/local/python/cv2/python-2.7/cv2.so" }, { "code": null, "e": 5361, "s": 5255, "text": "All you have to do now is to sym-link the cv2.so file(binding file) into the site-packages of python lib." }, { "code": null, "e": 5421, "s": 5361, "text": "pi@raspberrypi:~$ cd /usr/local/lib/python2.7/site-packages" }, { "code": null, "e": 5512, "s": 5421, "text": "Run the following commnad: ln -s [path to cv2.so file] cv2.so. In my case it is as follow:" }, { "code": null, "e": 5623, "s": 5512, "text": "pi@raspberrypi:~$/usr/local/lib/python2.7/site-packages $ ln -s /usr/local/python/cv2/python-2.7/cv2.so cv2.so" }, { "code": null, "e": 5674, "s": 5623, "text": "Now is the time to Verify our openCV installation." }, { "code": null, "e": 5729, "s": 5674, "text": "fire up a Python shell and import the OpenCV bindings:" }, { "code": null, "e": 5826, "s": 5729, "text": "pi@raspberrypi:/usr/local/lib/python2.7/site-packages$ pythonimport cv2>>> cv2.__version__3.4.1’" }, { "code": null, "e": 5955, "s": 5826, "text": "Thats It Now you have a freshly install openCV installed on your system. Now export the path python can access it from anywhere." }, { "code": null, "e": 6042, "s": 5955, "text": "pi@raspberrypi:~$ export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH" }, { "code": null, "e": 6169, "s": 6042, "text": "You can now remove both the opencv-3.4.1 and opencv_contrib-3.4.1 directories, freeing up a bunch of space on your filesystem:" }, { "code": null, "e": 6391, "s": 6169, "text": "But be cautious before you run this command! Make sure OpenCV has been properly installed on your system before blowing away these directories, otherwise you will have to start the (long, 12+ hour) compile all over again!" }, { "code": null, "e": 6454, "s": 6391, "text": "If you encounter any error let me know in the comment section." } ]
Delannoy Number - GeeksforGeeks
06 May, 2021 In mathematics, a Delannoy number D describes the number of paths from the southwest corner (0, 0) of a rectangular grid to the northeast corner (m, n), using only single steps north, northeast, or east. For Example, D(3, 3) equals 63.Delannoy Number can be calculated by: Delannoy number can be used to find: Counts the number of global alignments of two sequences of lengths m and n. Number of points in an m-dimensional integer lattice that are at most n steps from the origin. In cellular automata, the number of cells in an m-dimensional von Neumann neighborhood of radius n. Number of cells on a surface of an m-dimensional von Neumann neighborhood of radius n. Examples : Input : n = 3, m = 3 Output : 63 Input : n = 4, m = 5 Output : 681 Below is the implementation of finding Delannoy Number: C++ Java Python3 C# PHP Javascript // CPP Program of finding nth Delannoy Number.#include <bits/stdc++.h>using namespace std; // Return the nth Delannoy Number.int dealnnoy(int n, int m){ // Base case if (m == 0 || n == 0) return 1; // Recursive step. return dealnnoy(m - 1, n) + dealnnoy(m - 1, n - 1) + dealnnoy(m, n - 1);} // Driven Programint main(){ int n = 3, m = 4; cout << dealnnoy(n, m) << endl; return 0;} // Java Program for finding nth Delannoy Number.import java.util.*;import java.lang.*; public class GfG{ // Return the nth Delannoy Number. public static int dealnnoy(int n, int m) { // Base case if (m == 0 || n == 0) return 1; // Recursive step. return dealnnoy(m - 1, n) + dealnnoy(m - 1, n - 1) + dealnnoy(m, n - 1); } // driver function public static void main(String args[]){ int n = 3, m = 4; System.out.println(dealnnoy(n, m)); }} /* This code is contributed by Sagar Shukla. */ # Python3 Program for finding# nth Delannoy Number. # Return the nth Delannoy Number.def dealnnoy(n, m): # Base case if (m == 0 or n == 0) : return 1 # Recursive step. return dealnnoy(m - 1, n) + dealnnoy(m - 1, n - 1) + dealnnoy(m, n - 1) # Driven coden = 3m = 4;print( dealnnoy(n, m) ) # This code is contributed by "rishabh_jain". // C# Program for finding nth Delannoy Number.using System; public class GfG { // Return the nth Delannoy Number. public static int dealnnoy(int n, int m) { // Base case if (m == 0 || n == 0) return 1; // Recursive step. return dealnnoy(m - 1, n) + dealnnoy(m - 1, n - 1) + dealnnoy(m, n - 1); } // driver function public static void Main() { int n = 3, m = 4; Console.WriteLine(dealnnoy(n, m)); }} /* This code is contributed by vt_m. */ <?php// PHP Program of finding nth// Delannoy Number. // Return the nth Delannoy Number.function dealnnoy( $n, $m){ // Base case if ($m == 0 or $n == 0) return 1; // Recursive step. return dealnnoy($m - 1, $n) + dealnnoy($m - 1, $n - 1) + dealnnoy($m, $n - 1);} // Driver Code $n = 3; $m = 4; echo dealnnoy($n, $m); // This code is contributed by anuj_67.?> <script>// javascript Program for finding nth Delannoy Number. // Return the nth Delannoy Number. function dealnnoy(n, m) { // Base case if (m == 0 || n == 0) return 1; // Recursive step. return dealnnoy(m - 1, n) + dealnnoy(m - 1, n - 1) + dealnnoy(m, n - 1); } // Driver code let n = 3, m = 4; document.write(dealnnoy(n, m)); // This code is contributed by susmitakundugoaldanga.</script> Output: 129 Below is the Dynamic Programming program to find nth Delannoy Number: C++ Java Python3 C# PHP Javascript // CPP Program of finding nth Delannoy Number.#include <bits/stdc++.h>using namespace std; // Return the nth Delannoy Number.int dealnnoy(int n, int m){ int dp[m + 1][n + 1]; // Base cases for (int i = 0; i <= m; i++) dp[i][0] = 1; for (int i = 0; i <= m; i++) dp[0][i] = 1; for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1] + dp[i][j - 1]; return dp[m][n];} // Driven Programint main(){ int n = 3, m = 4; cout << dealnnoy(n, m) << endl; return 0;} // Java Program of finding nth Delannoy Number. import java.io.*; class GFG { // Return the nth Delannoy Number. static int dealnnoy(int n, int m) { int dp[][]=new int[m + 1][n + 1]; // Base cases for (int i = 0; i <= m; i++) dp[i][0] = 1; for (int i = 0; i < m; i++) dp[0][i] = 1; for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1] + dp[i][j - 1]; return dp[m][n]; } // Driven Program public static void main(String args[]) { int n = 3, m = 4; System.out.println(dealnnoy(n, m)); }} // This code is contributed by Nikita Tiwari. # Python3 Program for finding nth# Delannoy Number. # Return the nth Delannoy Number.def dealnnoy (n, m): dp = [[0 for x in range(n+1)] for x in range(m+1)] # Base cases for i in range(m): dp[0][i] = 1 for i in range(1, m + 1): dp[i][0] = 1 for i in range(1, m + 1): for j in range(1, n + 1): dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1] + dp[i][j - 1]; return dp[m][n] # Driven coden = 3m = 4print(dealnnoy(n, m)) # This code is contributed by "rishabh_jain". // C# Program of finding nth Delannoy Number.using System; class GFG { // Return the nth Delannoy Number. static int dealnnoy(int n, int m) { int[, ] dp = new int[m + 1, n + 1]; // Base cases for (int i = 0; i <= m; i++) dp[i, 0] = 1; for (int i = 0; i < m; i++) dp[0, i] = 1; for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) dp[i, j] = dp[i - 1, j] + dp[i - 1, j - 1] + dp[i, j - 1]; return dp[m, n]; } // Driven Program public static void Main() { int n = 3, m = 4; Console.WriteLine(dealnnoy(n, m)); }} // This code is contributed by vt_m. <?php// PHP Program of finding// nth Delannoy Number. // Return the nth Delannoy Number.function dealnnoy($n, $m){ $dp[$m + 1][$n + 1] = 0; // Base cases for ($i = 0; $i <= $m; $i++) $dp[$i][0] = 1; for ( $i = 0; $i <= $m; $i++) $dp[0][$i] = 1; for ($i = 1; $i <= $m; $i++) for ($j = 1; $j <= $n; $j++) $dp[$i][$j] = $dp[$i - 1][$j] + $dp[$i - 1][$j - 1] + $dp[$i][$j - 1]; return $dp[$m][$n];} // Driven Code$n = 3; $m = 4;echo dealnnoy($n, $m) ; // This code is contributed by SanjuTomar?> <script> // Javascript Program of finding// nth Delannoy Number. // Return the nth Delannoy Number.function dealnnoy(n, m){ var dp = Array.from(Array(m+1), () => Array(n+1)); // Base cases for (var i = 0; i <= m; i++) dp[i][0] = 1; for (var i = 0; i <= m; i++) dp[0][i] = 1; for (var i = 1; i <= m; i++) for (var j = 1; j <= n; j++) dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1] + dp[i][j - 1]; return dp[m][n];} // Driven Programvar n = 3, m = 4;document.write( dealnnoy(n, m)); </script> Output : 129 SanjuTomar vt_m susmitakundugoaldanga noob2000 series Dynamic Programming Mathematical Dynamic Programming Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Subset Sum Problem | DP-25 Matrix Chain Multiplication | DP-8 Longest Palindromic Substring | Set 1 Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Merge two sorted arrays Program to find GCD or HCF of two numbers
[ { "code": null, "e": 24233, "s": 24205, "text": "\n06 May, 2021" }, { "code": null, "e": 24508, "s": 24233, "text": "In mathematics, a Delannoy number D describes the number of paths from the southwest corner (0, 0) of a rectangular grid to the northeast corner (m, n), using only single steps north, northeast, or east. For Example, D(3, 3) equals 63.Delannoy Number can be calculated by: " }, { "code": null, "e": 24547, "s": 24508, "text": "Delannoy number can be used to find: " }, { "code": null, "e": 24625, "s": 24547, "text": "Counts the number of global alignments of two sequences of lengths m and n. " }, { "code": null, "e": 24722, "s": 24625, "text": "Number of points in an m-dimensional integer lattice that are at most n steps from the origin. " }, { "code": null, "e": 24824, "s": 24722, "text": "In cellular automata, the number of cells in an m-dimensional von Neumann neighborhood of radius n. " }, { "code": null, "e": 24911, "s": 24824, "text": "Number of cells on a surface of an m-dimensional von Neumann neighborhood of radius n." }, { "code": null, "e": 24924, "s": 24911, "text": "Examples : " }, { "code": null, "e": 24992, "s": 24924, "text": "Input : n = 3, m = 3\nOutput : 63\n\nInput : n = 4, m = 5\nOutput : 681" }, { "code": null, "e": 25052, "s": 24994, "text": "Below is the implementation of finding Delannoy Number: " }, { "code": null, "e": 25056, "s": 25052, "text": "C++" }, { "code": null, "e": 25061, "s": 25056, "text": "Java" }, { "code": null, "e": 25069, "s": 25061, "text": "Python3" }, { "code": null, "e": 25072, "s": 25069, "text": "C#" }, { "code": null, "e": 25076, "s": 25072, "text": "PHP" }, { "code": null, "e": 25087, "s": 25076, "text": "Javascript" }, { "code": "// CPP Program of finding nth Delannoy Number.#include <bits/stdc++.h>using namespace std; // Return the nth Delannoy Number.int dealnnoy(int n, int m){ // Base case if (m == 0 || n == 0) return 1; // Recursive step. return dealnnoy(m - 1, n) + dealnnoy(m - 1, n - 1) + dealnnoy(m, n - 1);} // Driven Programint main(){ int n = 3, m = 4; cout << dealnnoy(n, m) << endl; return 0;}", "e": 25517, "s": 25087, "text": null }, { "code": "// Java Program for finding nth Delannoy Number.import java.util.*;import java.lang.*; public class GfG{ // Return the nth Delannoy Number. public static int dealnnoy(int n, int m) { // Base case if (m == 0 || n == 0) return 1; // Recursive step. return dealnnoy(m - 1, n) + dealnnoy(m - 1, n - 1) + dealnnoy(m, n - 1); } // driver function public static void main(String args[]){ int n = 3, m = 4; System.out.println(dealnnoy(n, m)); }} /* This code is contributed by Sagar Shukla. */", "e": 26110, "s": 25517, "text": null }, { "code": "# Python3 Program for finding# nth Delannoy Number. # Return the nth Delannoy Number.def dealnnoy(n, m): # Base case if (m == 0 or n == 0) : return 1 # Recursive step. return dealnnoy(m - 1, n) + dealnnoy(m - 1, n - 1) + dealnnoy(m, n - 1) # Driven coden = 3m = 4;print( dealnnoy(n, m) ) # This code is contributed by \"rishabh_jain\".", "e": 26469, "s": 26110, "text": null }, { "code": "// C# Program for finding nth Delannoy Number.using System; public class GfG { // Return the nth Delannoy Number. public static int dealnnoy(int n, int m) { // Base case if (m == 0 || n == 0) return 1; // Recursive step. return dealnnoy(m - 1, n) + dealnnoy(m - 1, n - 1) + dealnnoy(m, n - 1); } // driver function public static void Main() { int n = 3, m = 4; Console.WriteLine(dealnnoy(n, m)); }} /* This code is contributed by vt_m. */", "e": 27023, "s": 26469, "text": null }, { "code": "<?php// PHP Program of finding nth// Delannoy Number. // Return the nth Delannoy Number.function dealnnoy( $n, $m){ // Base case if ($m == 0 or $n == 0) return 1; // Recursive step. return dealnnoy($m - 1, $n) + dealnnoy($m - 1, $n - 1) + dealnnoy($m, $n - 1);} // Driver Code $n = 3; $m = 4; echo dealnnoy($n, $m); // This code is contributed by anuj_67.?>", "e": 27439, "s": 27023, "text": null }, { "code": "<script>// javascript Program for finding nth Delannoy Number. // Return the nth Delannoy Number. function dealnnoy(n, m) { // Base case if (m == 0 || n == 0) return 1; // Recursive step. return dealnnoy(m - 1, n) + dealnnoy(m - 1, n - 1) + dealnnoy(m, n - 1); } // Driver code let n = 3, m = 4; document.write(dealnnoy(n, m)); // This code is contributed by susmitakundugoaldanga.</script>", "e": 27933, "s": 27439, "text": null }, { "code": null, "e": 27943, "s": 27933, "text": "Output: " }, { "code": null, "e": 27947, "s": 27943, "text": "129" }, { "code": null, "e": 28019, "s": 27947, "text": "Below is the Dynamic Programming program to find nth Delannoy Number: " }, { "code": null, "e": 28023, "s": 28019, "text": "C++" }, { "code": null, "e": 28028, "s": 28023, "text": "Java" }, { "code": null, "e": 28036, "s": 28028, "text": "Python3" }, { "code": null, "e": 28039, "s": 28036, "text": "C#" }, { "code": null, "e": 28043, "s": 28039, "text": "PHP" }, { "code": null, "e": 28054, "s": 28043, "text": "Javascript" }, { "code": "// CPP Program of finding nth Delannoy Number.#include <bits/stdc++.h>using namespace std; // Return the nth Delannoy Number.int dealnnoy(int n, int m){ int dp[m + 1][n + 1]; // Base cases for (int i = 0; i <= m; i++) dp[i][0] = 1; for (int i = 0; i <= m; i++) dp[0][i] = 1; for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1] + dp[i][j - 1]; return dp[m][n];} // Driven Programint main(){ int n = 3, m = 4; cout << dealnnoy(n, m) << endl; return 0;}", "e": 28663, "s": 28054, "text": null }, { "code": "// Java Program of finding nth Delannoy Number. import java.io.*; class GFG { // Return the nth Delannoy Number. static int dealnnoy(int n, int m) { int dp[][]=new int[m + 1][n + 1]; // Base cases for (int i = 0; i <= m; i++) dp[i][0] = 1; for (int i = 0; i < m; i++) dp[0][i] = 1; for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1] + dp[i][j - 1]; return dp[m][n]; } // Driven Program public static void main(String args[]) { int n = 3, m = 4; System.out.println(dealnnoy(n, m)); }} // This code is contributed by Nikita Tiwari.", "e": 29464, "s": 28663, "text": null }, { "code": "# Python3 Program for finding nth# Delannoy Number. # Return the nth Delannoy Number.def dealnnoy (n, m): dp = [[0 for x in range(n+1)] for x in range(m+1)] # Base cases for i in range(m): dp[0][i] = 1 for i in range(1, m + 1): dp[i][0] = 1 for i in range(1, m + 1): for j in range(1, n + 1): dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1] + dp[i][j - 1]; return dp[m][n] # Driven coden = 3m = 4print(dealnnoy(n, m)) # This code is contributed by \"rishabh_jain\".", "e": 29981, "s": 29464, "text": null }, { "code": "// C# Program of finding nth Delannoy Number.using System; class GFG { // Return the nth Delannoy Number. static int dealnnoy(int n, int m) { int[, ] dp = new int[m + 1, n + 1]; // Base cases for (int i = 0; i <= m; i++) dp[i, 0] = 1; for (int i = 0; i < m; i++) dp[0, i] = 1; for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) dp[i, j] = dp[i - 1, j] + dp[i - 1, j - 1] + dp[i, j - 1]; return dp[m, n]; } // Driven Program public static void Main() { int n = 3, m = 4; Console.WriteLine(dealnnoy(n, m)); }} // This code is contributed by vt_m.", "e": 30728, "s": 29981, "text": null }, { "code": "<?php// PHP Program of finding// nth Delannoy Number. // Return the nth Delannoy Number.function dealnnoy($n, $m){ $dp[$m + 1][$n + 1] = 0; // Base cases for ($i = 0; $i <= $m; $i++) $dp[$i][0] = 1; for ( $i = 0; $i <= $m; $i++) $dp[0][$i] = 1; for ($i = 1; $i <= $m; $i++) for ($j = 1; $j <= $n; $j++) $dp[$i][$j] = $dp[$i - 1][$j] + $dp[$i - 1][$j - 1] + $dp[$i][$j - 1]; return $dp[$m][$n];} // Driven Code$n = 3; $m = 4;echo dealnnoy($n, $m) ; // This code is contributed by SanjuTomar?>", "e": 31320, "s": 30728, "text": null }, { "code": "<script> // Javascript Program of finding// nth Delannoy Number. // Return the nth Delannoy Number.function dealnnoy(n, m){ var dp = Array.from(Array(m+1), () => Array(n+1)); // Base cases for (var i = 0; i <= m; i++) dp[i][0] = 1; for (var i = 0; i <= m; i++) dp[0][i] = 1; for (var i = 1; i <= m; i++) for (var j = 1; j <= n; j++) dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1] + dp[i][j - 1]; return dp[m][n];} // Driven Programvar n = 3, m = 4;document.write( dealnnoy(n, m)); </script>", "e": 31915, "s": 31320, "text": null }, { "code": null, "e": 31926, "s": 31915, "text": "Output : " }, { "code": null, "e": 31930, "s": 31926, "text": "129" }, { "code": null, "e": 31943, "s": 31932, "text": "SanjuTomar" }, { "code": null, "e": 31948, "s": 31943, "text": "vt_m" }, { "code": null, "e": 31970, "s": 31948, "text": "susmitakundugoaldanga" }, { "code": null, "e": 31979, "s": 31970, "text": "noob2000" }, { "code": null, "e": 31986, "s": 31979, "text": "series" }, { "code": null, "e": 32006, "s": 31986, "text": "Dynamic Programming" }, { "code": null, "e": 32019, "s": 32006, "text": "Mathematical" }, { "code": null, "e": 32039, "s": 32019, "text": "Dynamic Programming" }, { "code": null, "e": 32052, "s": 32039, "text": "Mathematical" }, { "code": null, "e": 32059, "s": 32052, "text": "series" }, { "code": null, "e": 32157, "s": 32059, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32166, "s": 32157, "text": "Comments" }, { "code": null, "e": 32179, "s": 32166, "text": "Old Comments" }, { "code": null, "e": 32210, "s": 32179, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 32243, "s": 32210, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 32270, "s": 32243, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 32305, "s": 32270, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 32343, "s": 32305, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 32403, "s": 32343, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32418, "s": 32403, "text": "C++ Data Types" }, { "code": null, "e": 32461, "s": 32418, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 32485, "s": 32461, "text": "Merge two sorted arrays" } ]
Types of Gradients in CSS
Gradients display the combination of two or more colors. The following are the types of gradients: Linear Gradients(down/up/left/right/diagonally) Radial Gradients Let us see an example of radial gradients: Live Demo <html> <head> <style> #grad1 { height: 100px; width: 550px; background: -webkit-radial-gradient(red 5%, green 15%, pink 60%); background: -o-radial-gradient(red 5%, green 15%, pink 60%); background: -moz-radial-gradient(red 5%, green 15%, pink 60%); background: radial-gradient(red 5%, green 15%, pink 60%); } </style> </head> <body> <div id = "grad1"></div> </body> </html>
[ { "code": null, "e": 1119, "s": 1062, "text": "Gradients display the combination of two or more colors." }, { "code": null, "e": 1161, "s": 1119, "text": "The following are the types of gradients:" }, { "code": null, "e": 1209, "s": 1161, "text": "Linear Gradients(down/up/left/right/diagonally)" }, { "code": null, "e": 1226, "s": 1209, "text": "Radial Gradients" }, { "code": null, "e": 1269, "s": 1226, "text": "Let us see an example of radial gradients:" }, { "code": null, "e": 1279, "s": 1269, "text": "Live Demo" }, { "code": null, "e": 1774, "s": 1279, "text": "<html>\n <head>\n <style>\n #grad1 {\n height: 100px;\n width: 550px;\n background: -webkit-radial-gradient(red 5%, green 15%, pink 60%);\n background: -o-radial-gradient(red 5%, green 15%, pink 60%);\n background: -moz-radial-gradient(red 5%, green 15%, pink 60%);\n background: radial-gradient(red 5%, green 15%, pink 60%);\n }\n </style>\n </head>\n <body>\n <div id = \"grad1\"></div>\n </body>\n</html>" } ]
Difference between NumPy.dot() and '*' operation in Python - GeeksforGeeks
09 Jul, 2021 In Python if we have two numpy arrays which are often referred as a vector. The ‘*’ operator and numpy.dot() work differently on them. It’s important to know especially when you are dealing with data science or competitive programming problem. ‘*’ operation caries out element-wise multiplication on array elements. The element at a[i][j] is multiplied with b[i][j] .This happens for all elements of array.Example: Let the two 2D array are v1 and v2:- v1 = [[1, 2], [3, 4]] v2 = [[1, 2], [3, 4]] Output: [[1, 4] [9, 16]] From below picture it would be clear. It carries of normal matrix multiplication . Where the condition of number of columns of first array should be equal to number of rows of second array is checked than only numpy.dot() function take place else it shows an error. Example: Let the two 2D array are v1 and v2:- v1=[[1, 2], [3, 4]] v2=[[1, 2], [3, 4]] Than numpy.dot(v1, v2) gives output of :- [[ 7 10] [15 22]] Examples 1: Python3 import numpy as np # vector v1 of dimension (2, 2)v1 = np.array([[1, 2], [1, 2]]) # vector v2 of dimension (2, 2)v2 = np.array([[1, 2], [1, 2]]) print("vector multiplication")print(np.dot(v1, v2)) print("\nElementwise multiplication of two vector")print(v1 * v2) Output : vector multiplication [[3 6] [3 6]] Elementwise multiplication of two vector [[1 4] [1 4]] Examples 2: Python3 import numpy as np v1 = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) v2 = np.array([[[1, 2, 3], [1, 2, 3], [1, 2, 3]]]) print("vector multiplication")print(np.dot(v1, v2)) print("\nElementwise multiplication of two vector")print(v1 * v2) Output : vector multiplication [[ 6 12 18] [ 6 12 18] [ 6 12 18]] Elementwise multiplication of two vector [[1 4 9] [1 4 9] [1 4 9]] singghakshay sumitgumber28 Python-numpy Difference Between Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference between Process and Thread Stack vs Heap Memory Allocation Difference Between Method Overloading and Method Overriding in Java Difference between Clustered and Non-clustered index Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24594, "s": 24566, "text": "\n09 Jul, 2021" }, { "code": null, "e": 24839, "s": 24594, "text": "In Python if we have two numpy arrays which are often referred as a vector. The ‘*’ operator and numpy.dot() work differently on them. It’s important to know especially when you are dealing with data science or competitive programming problem. " }, { "code": null, "e": 25012, "s": 24839, "text": "‘*’ operation caries out element-wise multiplication on array elements. The element at a[i][j] is multiplied with b[i][j] .This happens for all elements of array.Example: " }, { "code": null, "e": 25157, "s": 25012, "text": "Let the two 2D array are v1 and v2:-\nv1 = [[1, 2], [3, 4]]\nv2 = [[1, 2], [3, 4]]\n\nOutput:\n[[1, 4]\n[9, 16]]\nFrom below picture it would be clear." }, { "code": null, "e": 25400, "s": 25161, "text": "It carries of normal matrix multiplication . Where the condition of number of columns of first array should be equal to number of rows of second array is checked than only numpy.dot() function take place else it shows an error. Example: " }, { "code": null, "e": 25539, "s": 25400, "text": "Let the two 2D array are v1 and v2:-\nv1=[[1, 2], [3, 4]]\nv2=[[1, 2], [3, 4]]\nThan numpy.dot(v1, v2) gives output of :-\n[[ 7 10]\n [15 22]]" }, { "code": null, "e": 25553, "s": 25539, "text": "Examples 1: " }, { "code": null, "e": 25561, "s": 25553, "text": "Python3" }, { "code": "import numpy as np # vector v1 of dimension (2, 2)v1 = np.array([[1, 2], [1, 2]]) # vector v2 of dimension (2, 2)v2 = np.array([[1, 2], [1, 2]]) print(\"vector multiplication\")print(np.dot(v1, v2)) print(\"\\nElementwise multiplication of two vector\")print(v1 * v2)", "e": 25825, "s": 25561, "text": null }, { "code": null, "e": 25928, "s": 25825, "text": "Output :\nvector multiplication\n[[3 6]\n [3 6]]\n\nElementwise multiplication of two vector\n[[1 4]\n [1 4]]" }, { "code": null, "e": 25942, "s": 25928, "text": "Examples 2: " }, { "code": null, "e": 25950, "s": 25942, "text": "Python3" }, { "code": "import numpy as np v1 = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) v2 = np.array([[[1, 2, 3], [1, 2, 3], [1, 2, 3]]]) print(\"vector multiplication\")print(np.dot(v1, v2)) print(\"\\nElementwise multiplication of two vector\")print(v1 * v2)", "e": 26188, "s": 25950, "text": null }, { "code": null, "e": 26326, "s": 26188, "text": "Output :\nvector multiplication\n[[ 6 12 18]\n [ 6 12 18]\n [ 6 12 18]]\n\nElementwise multiplication of two vector\n[[1 4 9]\n [1 4 9]\n [1 4 9]]" }, { "code": null, "e": 26339, "s": 26326, "text": "singghakshay" }, { "code": null, "e": 26353, "s": 26339, "text": "sumitgumber28" }, { "code": null, "e": 26366, "s": 26353, "text": "Python-numpy" }, { "code": null, "e": 26385, "s": 26366, "text": "Difference Between" }, { "code": null, "e": 26392, "s": 26385, "text": "Python" }, { "code": null, "e": 26490, "s": 26392, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26551, "s": 26490, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26589, "s": 26551, "text": "Difference between Process and Thread" }, { "code": null, "e": 26621, "s": 26589, "text": "Stack vs Heap Memory Allocation" }, { "code": null, "e": 26689, "s": 26621, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 26742, "s": 26689, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 26770, "s": 26742, "text": "Read JSON file using Python" }, { "code": null, "e": 26820, "s": 26770, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 26842, "s": 26820, "text": "Python map() function" } ]
VBScript - Regular Expressions
Regular Expressions is a sequence of characters that forms a pattern, which is mainly used for search and replace. The purpose of creating a pattern is to match specific strings, so that the developer can extract characters based on conditions and replace certain characters. RegExp object helps the developers to match the pattern of strings and the properties and methods help us to work with Regular Expressions easily. It is similar to RegExp in JavaScript Pattern − The Pattern method represents a string that is used to define the regular expression and it should be set before using the regular expression object. Pattern − The Pattern method represents a string that is used to define the regular expression and it should be set before using the regular expression object. IgnoreCase − A Boolean property that represents if the regular expression should be tested against all possible matches in a string if true or false. If not specified explicitly, IgnoreCase value is set to False. IgnoreCase − A Boolean property that represents if the regular expression should be tested against all possible matches in a string if true or false. If not specified explicitly, IgnoreCase value is set to False. Global − A Boolean property that represents if the regular expression should be tested against all possible matches in a string. If not specified explicitly, Global value is set to False. Global − A Boolean property that represents if the regular expression should be tested against all possible matches in a string. If not specified explicitly, Global value is set to False. Test(search-string) − The Test method takes a string as its argument and returns True if the regular expression can successfully be matched against the string, otherwise False is returned. Test(search-string) − The Test method takes a string as its argument and returns True if the regular expression can successfully be matched against the string, otherwise False is returned. Replace(search-string, replace-string) − The Replace method takes 2 parameters. If the search is successful then it replaces that match with the replace-string, and the new string is returned. If there are no matches then the original search-string is returned. Replace(search-string, replace-string) − The Replace method takes 2 parameters. If the search is successful then it replaces that match with the replace-string, and the new string is returned. If there are no matches then the original search-string is returned. Execute(search-string) − The Execute method works like Replace, except that it returns a Matches collection object, containing a Match object for each successful match. It doesn't modify the original string. Execute(search-string) − The Execute method works like Replace, except that it returns a Matches collection object, containing a Match object for each successful match. It doesn't modify the original string. The Matches collection object is returned as a result of the Execute method. This collection object can contain zero or more Match objects and the properties of this object are read-only. Count − The Count method represents the number of match objects in the collection. Count − The Count method represents the number of match objects in the collection. Item − The Item method enables the match objects to be accessed from matches collections object. Item − The Item method enables the match objects to be accessed from matches collections object. The Match object is contained within the matches collection object. These objects represent the successful match after the search for a string. FirstIndex − It represents the position within the original string where the match occurred. This index are zero-based which means that the first position in a string is 0. FirstIndex − It represents the position within the original string where the match occurred. This index are zero-based which means that the first position in a string is 0. Length − A value that represents the total length of the matched string. Length − A value that represents the total length of the matched string. Value − A value that represents the matched value or text. It is also the default value when accessing the Match object. Value − A value that represents the matched value or text. It is also the default value when accessing the Match object. The pattern building is similar to PERL. Pattern building is the most important thing while working with Regular Expressions. In this section, we will deal with how to create a pattern based on various factors. The significance of position matching is to ensure that we place the regular expressions at the correct places. Any form of characters such as alphabet, number or special character or even decimal, hexadecimal can be treated as a Literal. Since few of the characters have already got a special meaning within the context of Regular Expression, we need to escape them using escape sequences. The character classes are the Pattern formed by customized grouping and enclosed within [ ] braces. If we are expecting a character class that should not be in the list, then we should ignore that particular character class using the negative symbol, which is a cap ^. Repetition matching allows multiple searches within the regular expression. It also specifies the number of times an element is repeated in a Regular Expression. Alternation and grouping helps developers to create more complex Regular Expressions in particularly handling intricate clauses within a Regular Expression which gives a great flexibility and control. Given below are a few examples that clearly explain how to build a Regular Expression. The below example checks whether or not the user entered an email id whose format should match such that there is an email id followed by '@' and then followed by domain name. <!DOCTYPE html> <html> <body> <script language = "vbscript" type = "text/vbscript"> strid = "welcome.user@tutorialspoint.co.us" Set re = New RegExp With re .Pattern = "^[\w-\.]{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,3}$" .IgnoreCase = False .Global = False End With ' Test method returns TRUE if a match is found If re.Test( strid ) Then Document.write(strid & " is a valid e-mail address") Else Document.write(strid & " is NOT a valid e-mail address") End If Set re = Nothing </script> </body> </html> 63 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2356, "s": 2080, "text": "Regular Expressions is a sequence of characters that forms a pattern, which is mainly used for search and replace. The purpose of creating a pattern is to match specific strings, so that the developer can extract characters based on conditions and replace certain characters." }, { "code": null, "e": 2541, "s": 2356, "text": "RegExp object helps the developers to match the pattern of strings and the properties and methods help us to work with Regular Expressions easily. It is similar to RegExp in JavaScript" }, { "code": null, "e": 2701, "s": 2541, "text": "Pattern − The Pattern method represents a string that is used to define the regular expression and it should be set before using the regular expression object." }, { "code": null, "e": 2861, "s": 2701, "text": "Pattern − The Pattern method represents a string that is used to define the regular expression and it should be set before using the regular expression object." }, { "code": null, "e": 3074, "s": 2861, "text": "IgnoreCase − A Boolean property that represents if the regular expression should be tested against all possible matches in a string if true or false. If not specified explicitly, IgnoreCase value is set to False." }, { "code": null, "e": 3287, "s": 3074, "text": "IgnoreCase − A Boolean property that represents if the regular expression should be tested against all possible matches in a string if true or false. If not specified explicitly, IgnoreCase value is set to False." }, { "code": null, "e": 3475, "s": 3287, "text": "Global − A Boolean property that represents if the regular expression should be tested against all possible matches in a string. If not specified explicitly, Global value is set to False." }, { "code": null, "e": 3663, "s": 3475, "text": "Global − A Boolean property that represents if the regular expression should be tested against all possible matches in a string. If not specified explicitly, Global value is set to False." }, { "code": null, "e": 3852, "s": 3663, "text": "Test(search-string) − The Test method takes a string as its argument and returns True if the regular expression can successfully be matched against the string, otherwise False is returned." }, { "code": null, "e": 4041, "s": 3852, "text": "Test(search-string) − The Test method takes a string as its argument and returns True if the regular expression can successfully be matched against the string, otherwise False is returned." }, { "code": null, "e": 4303, "s": 4041, "text": "Replace(search-string, replace-string) − The Replace method takes 2 parameters. If the search is successful then it replaces that match with the replace-string, and the new string is returned. If there are no matches then the original search-string is returned." }, { "code": null, "e": 4565, "s": 4303, "text": "Replace(search-string, replace-string) − The Replace method takes 2 parameters. If the search is successful then it replaces that match with the replace-string, and the new string is returned. If there are no matches then the original search-string is returned." }, { "code": null, "e": 4773, "s": 4565, "text": "Execute(search-string) − The Execute method works like Replace, except that it returns a Matches collection object, containing a Match object for each successful match. It doesn't modify the original string." }, { "code": null, "e": 4981, "s": 4773, "text": "Execute(search-string) − The Execute method works like Replace, except that it returns a Matches collection object, containing a Match object for each successful match. It doesn't modify the original string." }, { "code": null, "e": 5169, "s": 4981, "text": "The Matches collection object is returned as a result of the Execute method. This collection object can contain zero or more Match objects and the properties of this object are read-only." }, { "code": null, "e": 5252, "s": 5169, "text": "Count − The Count method represents the number of match objects in the collection." }, { "code": null, "e": 5335, "s": 5252, "text": "Count − The Count method represents the number of match objects in the collection." }, { "code": null, "e": 5432, "s": 5335, "text": "Item − The Item method enables the match objects to be accessed from matches collections object." }, { "code": null, "e": 5529, "s": 5432, "text": "Item − The Item method enables the match objects to be accessed from matches collections object." }, { "code": null, "e": 5673, "s": 5529, "text": "The Match object is contained within the matches collection object. These objects represent the successful match after the search for a string." }, { "code": null, "e": 5846, "s": 5673, "text": "FirstIndex − It represents the position within the original string where the match occurred. This index are zero-based which means that the first position in a string is 0." }, { "code": null, "e": 6019, "s": 5846, "text": "FirstIndex − It represents the position within the original string where the match occurred. This index are zero-based which means that the first position in a string is 0." }, { "code": null, "e": 6092, "s": 6019, "text": "Length − A value that represents the total length of the matched string." }, { "code": null, "e": 6165, "s": 6092, "text": "Length − A value that represents the total length of the matched string." }, { "code": null, "e": 6286, "s": 6165, "text": "Value − A value that represents the matched value or text. It is also the default value when accessing the Match object." }, { "code": null, "e": 6407, "s": 6286, "text": "Value − A value that represents the matched value or text. It is also the default value when accessing the Match object." }, { "code": null, "e": 6618, "s": 6407, "text": "The pattern building is similar to PERL. Pattern building is the most important thing while working with Regular Expressions. In this section, we will deal with how to create a pattern based on various factors." }, { "code": null, "e": 6730, "s": 6618, "text": "The significance of position matching is to ensure that we place the regular expressions at the correct places." }, { "code": null, "e": 7009, "s": 6730, "text": "Any form of characters such as alphabet, number or special character or even decimal, hexadecimal can be treated as a Literal. Since few of the characters have already got a special meaning within the context of Regular Expression, we need to escape them using escape sequences." }, { "code": null, "e": 7278, "s": 7009, "text": "The character classes are the Pattern formed by customized grouping and enclosed within [ ] braces. If we are expecting a character class that should not be in the list, then we should ignore that particular character class using the negative symbol, which is a cap ^." }, { "code": null, "e": 7440, "s": 7278, "text": "Repetition matching allows multiple searches within the regular expression. It also specifies the number of times an element is repeated in a Regular Expression." }, { "code": null, "e": 7641, "s": 7440, "text": "Alternation and grouping helps developers to create more complex Regular Expressions in particularly handling intricate clauses within a Regular Expression which gives a great flexibility and control." }, { "code": null, "e": 7728, "s": 7641, "text": "Given below are a few examples that clearly explain how to build a Regular Expression." }, { "code": null, "e": 7904, "s": 7728, "text": "The below example checks whether or not the user entered an email id whose format should match such that there is an email id followed by '@' and then followed by domain name." }, { "code": null, "e": 8593, "s": 7904, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n strid = \"welcome.user@tutorialspoint.co.us\"\n Set re = New RegExp\n With re\n .Pattern = \"^[\\w-\\.]{1,}\\@([\\da-zA-Z-]{1,}\\.){1,}[\\da-zA-Z-]{2,3}$\"\n .IgnoreCase = False\n .Global = False\n End With\n \n ' Test method returns TRUE if a match is found\n If re.Test( strid ) Then\n Document.write(strid & \" is a valid e-mail address\")\n Else\n Document.write(strid & \" is NOT a valid e-mail address\")\n End If\n \n Set re = Nothing\n </script>\n </body>\n</html>" }, { "code": null, "e": 8626, "s": 8593, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 8643, "s": 8626, "text": " Frahaan Hussain" }, { "code": null, "e": 8650, "s": 8643, "text": " Print" }, { "code": null, "e": 8661, "s": 8650, "text": " Add Notes" } ]
How to use the Text Watcher class in Android?
This example demonstrates how do I use the Text watcher class in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Android Text Watcher" android:textSize="16sp" android:textStyle="bold" android:layout_marginTop="24sp" android:layout_centerHorizontal="true" android:layout_alignParentTop="true" /> <EditText android:id="@+id/etInput" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_below="@id/text" android:maxLength="15" android:hint="Input" /> <TextView android:id="@+id/textView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="24sp" android:layout_centerHorizontal="true" android:layout_marginTop="12dp" android:layout_below="@id/etInput"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { EditText input; TextView output; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); input = findViewById(R.id.etInput); output = findViewById(R.id.textView); input.addTextChangedListener(textWatcher); } TextWatcher textWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { output.setText(s); if (start == 12){ Toast.makeText(getApplicationContext(), "Maximum Limit Reached", Toast.LENGTH_SHORT).show(); } } @Override public void afterTextChanged(Editable s) { } }; } Step 4 - Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code.
[ { "code": null, "e": 1136, "s": 1062, "text": "This example demonstrates how do I use the Text watcher class in android." }, { "code": null, "e": 1265, "s": 1136, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1330, "s": 1265, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2542, "s": 1330, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/text\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Android Text Watcher\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\"\n android:layout_marginTop=\"24sp\"\n android:layout_centerHorizontal=\"true\"\n android:layout_alignParentTop=\"true\" />\n <EditText\n android:id=\"@+id/etInput\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_below=\"@id/text\"\n android:maxLength=\"15\"\n android:hint=\"Input\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:textSize=\"24sp\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"12dp\"\n android:layout_below=\"@id/etInput\"/>\n</RelativeLayout>" }, { "code": null, "e": 2599, "s": 2542, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3740, "s": 2599, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.text.Editable;\nimport android.text.TextWatcher;\nimport android.widget.EditText;\nimport android.widget.TextView;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n EditText input;\n TextView output;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n input = findViewById(R.id.etInput);\n output = findViewById(R.id.textView);\n input.addTextChangedListener(textWatcher);\n }\n TextWatcher textWatcher = new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) {\n }\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) {\n output.setText(s);\n if (start == 12){\n Toast.makeText(getApplicationContext(), \"Maximum Limit Reached\", Toast.LENGTH_SHORT).show();\n }\n }\n @Override\n public void afterTextChanged(Editable s) {\n }\n };\n}" }, { "code": null, "e": 3795, "s": 3740, "text": "Step 4 - Add the following code to androidManifest.xml" }, { "code": null, "e": 4465, "s": 3795, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4812, "s": 4465, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 4853, "s": 4812, "text": "Click here to download the project code." } ]
Kernel Regression in Python. How to do Kernel regression by hand in... | by Pawan Nandakishore | Towards Data Science
1 Kernal Regression by Statsmodels 1.1 Generating Fake Data 1.2 Output of Kernal Regression 2 Kernel regression by Hand in Python 2.0.1 Step 1: Calculate the Kernel for a single input x point 2.0.2 Visualizing the Kernels for all the input x points 2.0.3 Step 2: Calculate the weights for each input x value 2.0.4 Step 3: Calculate the y pred value for a single input point 2.0.5 Step 4: Calculate the y pred values for all the input points 2.0.6 Step 5: Visualize the difference between the two methods 3 Conclusion 4 References This notebook demonstrates how you can perform Kernel Regression manually in python. While Statsmodels provides a library for Kernel Regression, doing Kernel regression by hand can help us better understand how we get to the find result. First, I will show how Kernel Regression is done using Statsmodels. Next I will show how it is done by hand, then finally overlay both plots to show that the results are the same. To begin with, lets looks at Kernel regression by Statsmodels We generate y values by using a lambda function. You can change the lambda function around to see what happens. The x values i.e. the independent variable is controlled by new_x where we have displaced the x value to show that you can have import numpy as npimport plotly.express as pxfrom statsmodels.nonparametric.kernel_regressionimport KernelReg as kr import plotly.graph_objs as goimport pandas as pd np.random.seed(1)# xwidth controls the range of x values.xwidth = 20x = np.arange(0,xwidth,1)# we want to add some noise to the x values so that dont sit at regular intervalsx_residuals = np.random.normal(scale=0.2, size=[x.shape[0]])# new_x is the range of x values we will be using all the way throughnew_x = x + x_residuals# We generate residuals for y values since we want to show some variation in the datanum_points = x.shape[0]residuals = np.random.normal(scale=2.0, size=[num_points])# We will be using fun_y to generate y values all the way throughfun_y = lambda x: -(x*x) + residuals Let us plot the data. We are going to be using Plotly express through this article for all the plotting. # Plot the x and y values px.scatter(x=new_x,y=fun_y(new_x), title='Figure 1: Visualizing the generated data') Our goal is to fit a curve the above data point using regression. How can we go about it? Using statsmodels it is fairly simple. The output of kernel regression in Statsmodels non-parametric regression module are two arrays. 1) The predicted y values2) The Marginal Effects The marginal effects are essentially the first derivative of the predicted value to the independent variable for a univariate regression problem. More on marginal effects can be found here. fig = px.scatter(x=new_x,y=fun_y(new_x), title='Figure 2: Statsmodels fit to generated data')fig.add_trace(go.Scatter(x=new_x, y=pred_y, name='Statsmodels fit', mode='lines')) To do Kernel regression by hand, we need to understand a few things. First, here are some of the properties of the kernel. 1) The Kernel is symmetric i.e K(x) = K(-x) 2) Area under the Kernel function is equal to 1 meaning We are going to use a gaussian kernel to solve this problem. The Gaussian kernel has the form: Where b is the bandwidth, xi are the points from the dependent variable, and xx is the range of values over which we define the kernel function. In our case xi comes from new_x kernel_x = np.arange(-xwidth,xwidth, 0.1)bw_manual = 1def gauss_const(h): """ Returns the normalization constant for a gaussian """ return 1/(h*np.sqrt(np.pi*2))def gauss_exp(ker_x, xi, h): """ Returns the gaussian function exponent term """ num = - 0.5*np.square((xi- ker_x)) den = h*h return num/dendef kernel_function(h, ker_x, xi): """ Returns the gaussian function value. Combines the gauss_const and gauss_exp to get this result """ const = gauss_const(h) gauss_val = const*np.exp(gauss_exp(ker_x,xi,h)) return gauss_val# We are selecting a single point and calculating the Kernel valueinput_x = new_x[0]col1 = gauss_const(bw_manual)col2= gauss_exp(kernel_x, input_x, bw_manual)col3 = kernel_function(bw_manual, kernel_x, input_x) We want to display the dataframe for a single point xi. # Dataframe for a single observation point x_i. In the code x_i comes from new_xdata = {'Input_x': [input_x for x in range(col2.shape[0])], 'kernel_x': kernel_x, 'gaussian_const': [col1 for x in range(col2.shape[0])], 'gaussian_exp': col2, 'full_gaussian_value': col3, 'bw':[bw_manual for x in range(col2.shape[0])], }single_pt_KE = pd.DataFrame(data=data)single_pt_KE We also want to visualize a single kernel function. # Plotting a scatter plot of Kernel px.line(x=kernel_x, y=col3, title='Figure 3: Kernel function for a single input value') We want to visual the kernel K(x)K(x) for each xixi. Below we calculate the kernel function value and store them in a dictionary called kernel_fns which is converted to a dataframe kernels_df. We then use Plotly express to plot each kernel function. ## Plotting gaussian for all input x points kernel_fns = {'kernel_x': kernel_x}for input_x in new_x: input_string= 'x_value_{}'.format(np.round(input_x,2)) kernel_fns[input_string] = kernel_function(bw_manual, kernel_x, input_x)kernels_df = pd.DataFrame(data=kernel_fns)y_all = kernels_df.drop(columns='kernel_x')px.line(kernels_df, x='kernel_x', y=y_all.columns, title='Gaussian for all input points', range_x=[-5,20]) We will need to calculate the weight for a single input. The weight is calculated using the expression below: The above equation represents the weights for the ithith element of new_x where xx are all the elements of new_x. The denominator is summed over all the points in new_x. What is interesting to note here is that you are going to be using the kernels for all input points to calculate the weights. The equation above essentially scales weights between 0 and 1. The equation above has been implemented in the function weights Which gives us the weights for a single input point. . The function takes a single input point and gives us a row of weights. It does this by looping over all the input points while implementing the above equation. We get the predicted value for the ithith point from : This equation is implemented in the function single_y_pred . We take a dot product of the row of weights we get from the weights function and the y values from our fake data. The equation above represents that dot product. def weights(bw_manual, input_x, all_input_values ): w_row = [] for x_i in all_input_values: ki = kernel_function(bw_manual, x_i, input_x) ki_sum = np.sum(kernel_function(bw_manual, all_input_values, input_x)) w_row.append(ki/ki_sum) return w_rowdef single_y_pred(bw_manual, input_x, new_x): w = weights(bw_manual, input_x, new_x) y_single = np.sum(np.dot(fun_y(new_x),w)) return y_singleypred_single = single_y_pred(bw_manual, new_x[0], new_x) The code below loops over all the input points calculates the predicted values and appends them to Y_pred. Once we have the predicted values, all we need to do now is to visualize them. Y_pred = []for input_x in new_x: w = [] Y_single = single_y_pred(bw_manual, input_x, new_x) Y_pred.append(Y_single) Now that we have acquired the predicted value by calculating the predicted values manually, we can compare our regression curve to the one we get from statsmodels. We overlap the fits on top of each other and fit that they match perfectly. data= {'x': new_x, 'y': fun_y(new_x), 'y_manual': np.array(y_all)}fig = px.scatter(x=new_x,y=fun_y(x))fig.add_trace(go.Scatter(x=new_x, y=pred_y, name='Statsmodel KR', mode='lines'))fig.add_trace(go.Scatter(x=new_x, y=np.array(Y_pred), name='Manual KR', mode='lines')) This article shows how we can understand the kernel regression algorithm's inner workings with a simple example that uses generated data. If you learned something from this article do like and share this article. Thank you for reading!
[ { "code": null, "e": 207, "s": 172, "text": "1 Kernal Regression by Statsmodels" }, { "code": null, "e": 232, "s": 207, "text": "1.1 Generating Fake Data" }, { "code": null, "e": 264, "s": 232, "text": "1.2 Output of Kernal Regression" }, { "code": null, "e": 302, "s": 264, "text": "2 Kernel regression by Hand in Python" }, { "code": null, "e": 364, "s": 302, "text": "2.0.1 Step 1: Calculate the Kernel for a single input x point" }, { "code": null, "e": 421, "s": 364, "text": "2.0.2 Visualizing the Kernels for all the input x points" }, { "code": null, "e": 480, "s": 421, "text": "2.0.3 Step 2: Calculate the weights for each input x value" }, { "code": null, "e": 546, "s": 480, "text": "2.0.4 Step 3: Calculate the y pred value for a single input point" }, { "code": null, "e": 613, "s": 546, "text": "2.0.5 Step 4: Calculate the y pred values for all the input points" }, { "code": null, "e": 676, "s": 613, "text": "2.0.6 Step 5: Visualize the difference between the two methods" }, { "code": null, "e": 689, "s": 676, "text": "3 Conclusion" }, { "code": null, "e": 702, "s": 689, "text": "4 References" }, { "code": null, "e": 940, "s": 702, "text": "This notebook demonstrates how you can perform Kernel Regression manually in python. While Statsmodels provides a library for Kernel Regression, doing Kernel regression by hand can help us better understand how we get to the find result." }, { "code": null, "e": 1120, "s": 940, "text": "First, I will show how Kernel Regression is done using Statsmodels. Next I will show how it is done by hand, then finally overlay both plots to show that the results are the same." }, { "code": null, "e": 1182, "s": 1120, "text": "To begin with, lets looks at Kernel regression by Statsmodels" }, { "code": null, "e": 1422, "s": 1182, "text": "We generate y values by using a lambda function. You can change the lambda function around to see what happens. The x values i.e. the independent variable is controlled by new_x where we have displaced the x value to show that you can have" }, { "code": null, "e": 1589, "s": 1422, "text": "import numpy as npimport plotly.express as pxfrom statsmodels.nonparametric.kernel_regressionimport KernelReg as kr import plotly.graph_objs as goimport pandas as pd " }, { "code": null, "e": 2183, "s": 1589, "text": "np.random.seed(1)# xwidth controls the range of x values.xwidth = 20x = np.arange(0,xwidth,1)# we want to add some noise to the x values so that dont sit at regular intervalsx_residuals = np.random.normal(scale=0.2, size=[x.shape[0]])# new_x is the range of x values we will be using all the way throughnew_x = x + x_residuals# We generate residuals for y values since we want to show some variation in the datanum_points = x.shape[0]residuals = np.random.normal(scale=2.0, size=[num_points])# We will be using fun_y to generate y values all the way throughfun_y = lambda x: -(x*x) + residuals" }, { "code": null, "e": 2288, "s": 2183, "text": "Let us plot the data. We are going to be using Plotly express through this article for all the plotting." }, { "code": null, "e": 2400, "s": 2288, "text": "# Plot the x and y values px.scatter(x=new_x,y=fun_y(new_x), title='Figure 1: Visualizing the generated data')" }, { "code": null, "e": 2529, "s": 2400, "text": "Our goal is to fit a curve the above data point using regression. How can we go about it? Using statsmodels it is fairly simple." }, { "code": null, "e": 2625, "s": 2529, "text": "The output of kernel regression in Statsmodels non-parametric regression module are two arrays." }, { "code": null, "e": 2674, "s": 2625, "text": "1) The predicted y values2) The Marginal Effects" }, { "code": null, "e": 2864, "s": 2674, "text": "The marginal effects are essentially the first derivative of the predicted value to the independent variable for a univariate regression problem. More on marginal effects can be found here." }, { "code": null, "e": 3042, "s": 2864, "text": "fig = px.scatter(x=new_x,y=fun_y(new_x), title='Figure 2: Statsmodels fit to generated data')fig.add_trace(go.Scatter(x=new_x, y=pred_y, name='Statsmodels fit', mode='lines'))" }, { "code": null, "e": 3165, "s": 3042, "text": "To do Kernel regression by hand, we need to understand a few things. First, here are some of the properties of the kernel." }, { "code": null, "e": 3196, "s": 3165, "text": "1) The Kernel is symmetric i.e" }, { "code": null, "e": 3209, "s": 3196, "text": "K(x) = K(-x)" }, { "code": null, "e": 3265, "s": 3209, "text": "2) Area under the Kernel function is equal to 1 meaning" }, { "code": null, "e": 3360, "s": 3265, "text": "We are going to use a gaussian kernel to solve this problem. The Gaussian kernel has the form:" }, { "code": null, "e": 3537, "s": 3360, "text": "Where b is the bandwidth, xi are the points from the dependent variable, and xx is the range of values over which we define the kernel function. In our case xi comes from new_x" }, { "code": null, "e": 4328, "s": 3537, "text": "kernel_x = np.arange(-xwidth,xwidth, 0.1)bw_manual = 1def gauss_const(h): \"\"\" Returns the normalization constant for a gaussian \"\"\" return 1/(h*np.sqrt(np.pi*2))def gauss_exp(ker_x, xi, h): \"\"\" Returns the gaussian function exponent term \"\"\" num = - 0.5*np.square((xi- ker_x)) den = h*h return num/dendef kernel_function(h, ker_x, xi): \"\"\" Returns the gaussian function value. Combines the gauss_const and gauss_exp to get this result \"\"\" const = gauss_const(h) gauss_val = const*np.exp(gauss_exp(ker_x,xi,h)) return gauss_val# We are selecting a single point and calculating the Kernel valueinput_x = new_x[0]col1 = gauss_const(bw_manual)col2= gauss_exp(kernel_x, input_x, bw_manual)col3 = kernel_function(bw_manual, kernel_x, input_x)" }, { "code": null, "e": 4384, "s": 4328, "text": "We want to display the dataframe for a single point xi." }, { "code": null, "e": 4795, "s": 4384, "text": "# Dataframe for a single observation point x_i. In the code x_i comes from new_xdata = {'Input_x': [input_x for x in range(col2.shape[0])], 'kernel_x': kernel_x, 'gaussian_const': [col1 for x in range(col2.shape[0])], 'gaussian_exp': col2, 'full_gaussian_value': col3, 'bw':[bw_manual for x in range(col2.shape[0])], }single_pt_KE = pd.DataFrame(data=data)single_pt_KE" }, { "code": null, "e": 4847, "s": 4795, "text": "We also want to visualize a single kernel function." }, { "code": null, "e": 4971, "s": 4847, "text": "# Plotting a scatter plot of Kernel px.line(x=kernel_x, y=col3, title='Figure 3: Kernel function for a single input value')" }, { "code": null, "e": 5221, "s": 4971, "text": "We want to visual the kernel K(x)K(x) for each xixi. Below we calculate the kernel function value and store them in a dictionary called kernel_fns which is converted to a dataframe kernels_df. We then use Plotly express to plot each kernel function." }, { "code": null, "e": 5649, "s": 5221, "text": "## Plotting gaussian for all input x points kernel_fns = {'kernel_x': kernel_x}for input_x in new_x: input_string= 'x_value_{}'.format(np.round(input_x,2)) kernel_fns[input_string] = kernel_function(bw_manual, kernel_x, input_x)kernels_df = pd.DataFrame(data=kernel_fns)y_all = kernels_df.drop(columns='kernel_x')px.line(kernels_df, x='kernel_x', y=y_all.columns, title='Gaussian for all input points', range_x=[-5,20])" }, { "code": null, "e": 5759, "s": 5649, "text": "We will need to calculate the weight for a single input. The weight is calculated using the expression below:" }, { "code": null, "e": 6118, "s": 5759, "text": "The above equation represents the weights for the ithith element of new_x where xx are all the elements of new_x. The denominator is summed over all the points in new_x. What is interesting to note here is that you are going to be using the kernels for all input points to calculate the weights. The equation above essentially scales weights between 0 and 1." }, { "code": null, "e": 6397, "s": 6118, "text": "The equation above has been implemented in the function weights Which gives us the weights for a single input point. . The function takes a single input point and gives us a row of weights. It does this by looping over all the input points while implementing the above equation." }, { "code": null, "e": 6452, "s": 6397, "text": "We get the predicted value for the ithith point from :" }, { "code": null, "e": 6675, "s": 6452, "text": "This equation is implemented in the function single_y_pred . We take a dot product of the row of weights we get from the weights function and the y values from our fake data. The equation above represents that dot product." }, { "code": null, "e": 7161, "s": 6675, "text": "def weights(bw_manual, input_x, all_input_values ): w_row = [] for x_i in all_input_values: ki = kernel_function(bw_manual, x_i, input_x) ki_sum = np.sum(kernel_function(bw_manual, all_input_values, input_x)) w_row.append(ki/ki_sum) return w_rowdef single_y_pred(bw_manual, input_x, new_x): w = weights(bw_manual, input_x, new_x) y_single = np.sum(np.dot(fun_y(new_x),w)) return y_singleypred_single = single_y_pred(bw_manual, new_x[0], new_x)" }, { "code": null, "e": 7347, "s": 7161, "text": "The code below loops over all the input points calculates the predicted values and appends them to Y_pred. Once we have the predicted values, all we need to do now is to visualize them." }, { "code": null, "e": 7473, "s": 7347, "text": "Y_pred = []for input_x in new_x: w = [] Y_single = single_y_pred(bw_manual, input_x, new_x) Y_pred.append(Y_single)" }, { "code": null, "e": 7713, "s": 7473, "text": "Now that we have acquired the predicted value by calculating the predicted values manually, we can compare our regression curve to the one we get from statsmodels. We overlap the fits on top of each other and fit that they match perfectly." }, { "code": null, "e": 7984, "s": 7713, "text": "data= {'x': new_x, 'y': fun_y(new_x), 'y_manual': np.array(y_all)}fig = px.scatter(x=new_x,y=fun_y(x))fig.add_trace(go.Scatter(x=new_x, y=pred_y, name='Statsmodel KR', mode='lines'))fig.add_trace(go.Scatter(x=new_x, y=np.array(Y_pred), name='Manual KR', mode='lines'))" }, { "code": null, "e": 8197, "s": 7984, "text": "This article shows how we can understand the kernel regression algorithm's inner workings with a simple example that uses generated data. If you learned something from this article do like and share this article." } ]
apt-get command in Linux with Examples - GeeksforGeeks
04 Apr, 2019 apt-get is a command-line tool which helps in handling packages in Linux. Its main task is to retrieve the information and packages from the authenticated sources for installation, upgrade and removal of packages along with their dependencies. Here APT stands for the Advanced Packaging Tool. Syntax: apt-get [options] command or apt-get [options] install|remove pkg1 [pkg2 ...] or apt-get [options] source pkg1 [pkg2 ...] Most Used Commands: You need to provide one of the commands below, if -h option is not used. update : This command is used to synchronize the package index files from their sources again. You need to perform an update before you upgrade or dist-upgrade.apt-get update apt-get update upgrade : This command is used to install the latest versions of the packages currently installed on the user’s system from the sources enumerated in /etc/apt/sources.list. The installed packages which have new packages available are retrieved and installed. You need to perform an update before the upgrade, so that apt-get knows that new versions of packages are available.apt-get upgrade apt-get upgrade dselect-upgrade : This is used alongwith the Debian packaging tool, dselect. It follows the changes made by dselect to the Status field of available packages, and performs any actions necessary to realize that state.apt-get dselect-upgrade apt-get dselect-upgrade dist-upgrade : This command performs the function of upgrade, and also handles changing dependencies with new versions of packages. If necessary, the apt-get command will try to upgrade important packages at the expense of less important ones. It may also remove some packages in this process.apt-get dist-upgrade apt-get dist-upgrade install : This command is used to install or upgrade packages. It is followed by one or more package names the user wishes to install. All the dependencies of the desired packages will also be retrieved and installed. The user can also select the desired version by following the package name with an ‘equals’ and the desired version number. Also, the user can select a specific distribution by following the package name with a forward slash and the version or the archive name (e.g. ‘stable’, ‘testing’ or ‘unstable’). Both of these version selection methods have the potential to downgrade the packages, so must be used with care.apt-get install [...PACKAGES] apt-get install [...PACKAGES] remove : This is similar to install, with the difference being that it removes the packages instead of installing. It does not remove any configuration files created by the package.apt-get remove [...PACKAGES] apt-get remove [...PACKAGES] purge : This command removes the packages, and also removes any configuration files related to the packages.apt-get purge [...PACKAGES] apt-get purge [...PACKAGES] check : This command is used to update the package cache and checks for broken dependencies.apt-get check apt-get check download : This command is used to download the given binary package in the current directory.apt-get download [...PACKAGES] apt-get download [...PACKAGES] clean : This command is used to clear out the local repository of retrieved package files. It removes everything but not the lock file from /var/cache/apt/archives/partial/ and /var/cache/apt/archives/.apt-get clean apt-get clean autoremove : Sometimes the packages which are automatically installed to satisfy the dependencies of other packages, are no longer needed then autoremove command is used to remove these kind of packages.apt-get autoremove apt-get autoremove Options: –no-install-recommends : By passing this option, the user lets apt-get know not to consider recommended packages as a dependency to install.apt-get --no-install-recommends [...COMMAND] apt-get --no-install-recommends [...COMMAND] –install-suggests : By passing this option, the user lets apt-get know that it should consider suggested packages as dependencies to install.apt-get --install-suggests [...COMMAND] apt-get --install-suggests [...COMMAND] -d or –download-only : By passing this option, the user specifies that apt-get should only retrieve the packages, and not unpack or install them.apt-get -d [...COMMAND] apt-get -d [...COMMAND] -f or –fix-broken : By passing this option, the user specifies that apt-get should attempt to correct the system with broken dependencies in place.apt-get -f [...COMMAND] apt-get -f [...COMMAND] -m or –ignore-missing or –fix-missing : By passing this option, the user specifies that apt-get should ignore the missing packages ( packages that cannot be retrieved or fail the integrity check ) and handle the result.apt-get -m [...COMMAND] apt-get -m [...COMMAND] –no-download : By passing this command, the user disables downloading for apt-get. It means that it should only use the .debs it has already downloaded.apt-get [...COMMAND] apt-get [...COMMAND] -q or –quiet : When this option is specified, apt-get produces output which is suitable for logging.apt-get [...COMMAND] apt-get [...COMMAND] -s or –simulate or –just-print or –dry-run or –recon or –no-act : This option specifies that no action should be taken, and perform a simulation of events that would occur based on the current system, but do not change the system.apt-get -s [...COMMAND] apt-get -s [...COMMAND] -y or –yes or –assume-yes : During the execution of apt-get command, it may sometimes prompt the user for a yes/no. With this option, it is specified that it should assume ‘yes’ for all prompts, and should run without any interaction.apt-get -y [...COMMAND] apt-get -y [...COMMAND] –assume-no : With this option, apt-get assumes ‘no’ for all prompts.apt-get --assume-no [...COMMAND] apt-get --assume-no [...COMMAND] –no-show-upgraded : With this option, apt-get will not show the list of all packages that are to be upgraded.apt-get --no-show-upgraded [...COMMAND] apt-get --no-show-upgraded [...COMMAND] -V or –verbose-versions : With this option, apt-get will show full versions for upgraded and installed packages.apt-get -V [...COMMAND] apt-get -V [...COMMAND] –show-progress : With this option, apt-get will show user-friendly progress in the terminal window when the packages are being installed, removed or upgraded.apt-get --show-progress [...COMMAND] apt-get --show-progress [...COMMAND] -b or –compile or –build : With this option, apt-get will compile/build the source packages it downloads.apt-get -b [...COMMAND] apt-get -b [...COMMAND] –no-upgrade : With this option, apt-get prevents the packages from being upgraded if they are already installed.apt-get --no-upgrade [...COMMAND] apt-get --no-upgrade [...COMMAND] –only-upgrade : With this option, apt-get will only upgrade the packages which are already installed, and not install new packages.apt-get --only-upgrade [...COMMAND] apt-get --only-upgrade [...COMMAND] –reinstall : With this option, apt-get reinstalls the packages that are already installed, at their latest versions.apt-get --reinstall [...COMMAND] apt-get --reinstall [...COMMAND] –auto-remove or –autoremove : When using apt-get with install or remove command, this option acts like running the autoremove command.apt-get install/remove --autoremove [...PACKAGES] apt-get install/remove --autoremove [...PACKAGES] -h or –help : With this option, apt-get displays a short usage summary.apt-get -hOutput: apt-get -h Output: -v or –version : With this option, apt-get displays it’s current version number.apt-get [...COMMAND]Output: apt-get [...COMMAND] Output: Note: apt-get command will return 0 for successful executions, and decimal 100 in case of errors. Linux-basic-commands linux-command Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C ZIP command in Linux with examples tar command in Linux with examples SORT command in Linux/Unix with examples curl command in Linux with Examples 'crontab' in Linux with Examples UDP Server-Client implementation in C diff command in Linux with examples Conditional Statements | Shell Script Cat command in Linux with examples
[ { "code": null, "e": 24566, "s": 24538, "text": "\n04 Apr, 2019" }, { "code": null, "e": 24859, "s": 24566, "text": "apt-get is a command-line tool which helps in handling packages in Linux. Its main task is to retrieve the information and packages from the authenticated sources for installation, upgrade and removal of packages along with their dependencies. Here APT stands for the Advanced Packaging Tool." }, { "code": null, "e": 24867, "s": 24859, "text": "Syntax:" }, { "code": null, "e": 24994, "s": 24867, "text": "apt-get [options] command\n\nor\n\napt-get [options] install|remove pkg1 [pkg2 ...]\n\nor\n\napt-get [options] source pkg1 [pkg2 ...]\n" }, { "code": null, "e": 25087, "s": 24994, "text": "Most Used Commands: You need to provide one of the commands below, if -h option is not used." }, { "code": null, "e": 25263, "s": 25087, "text": "update : This command is used to synchronize the package index files from their sources again. You need to perform an update before you upgrade or dist-upgrade.apt-get update " }, { "code": null, "e": 25279, "s": 25263, "text": "apt-get update " }, { "code": null, "e": 25671, "s": 25279, "text": "upgrade : This command is used to install the latest versions of the packages currently installed on the user’s system from the sources enumerated in /etc/apt/sources.list. The installed packages which have new packages available are retrieved and installed. You need to perform an update before the upgrade, so that apt-get knows that new versions of packages are available.apt-get upgrade " }, { "code": null, "e": 25688, "s": 25671, "text": "apt-get upgrade " }, { "code": null, "e": 25929, "s": 25688, "text": "dselect-upgrade : This is used alongwith the Debian packaging tool, dselect. It follows the changes made by dselect to the Status field of available packages, and performs any actions necessary to realize that state.apt-get dselect-upgrade " }, { "code": null, "e": 25954, "s": 25929, "text": "apt-get dselect-upgrade " }, { "code": null, "e": 26269, "s": 25954, "text": "dist-upgrade : This command performs the function of upgrade, and also handles changing dependencies with new versions of packages. If necessary, the apt-get command will try to upgrade important packages at the expense of less important ones. It may also remove some packages in this process.apt-get dist-upgrade " }, { "code": null, "e": 26291, "s": 26269, "text": "apt-get dist-upgrade " }, { "code": null, "e": 26955, "s": 26291, "text": "install : This command is used to install or upgrade packages. It is followed by one or more package names the user wishes to install. All the dependencies of the desired packages will also be retrieved and installed. The user can also select the desired version by following the package name with an ‘equals’ and the desired version number. Also, the user can select a specific distribution by following the package name with a forward slash and the version or the archive name (e.g. ‘stable’, ‘testing’ or ‘unstable’). Both of these version selection methods have the potential to downgrade the packages, so must be used with care.apt-get install [...PACKAGES] " }, { "code": null, "e": 26986, "s": 26955, "text": "apt-get install [...PACKAGES] " }, { "code": null, "e": 27196, "s": 26986, "text": "remove : This is similar to install, with the difference being that it removes the packages instead of installing. It does not remove any configuration files created by the package.apt-get remove [...PACKAGES]" }, { "code": null, "e": 27225, "s": 27196, "text": "apt-get remove [...PACKAGES]" }, { "code": null, "e": 27361, "s": 27225, "text": "purge : This command removes the packages, and also removes any configuration files related to the packages.apt-get purge [...PACKAGES]" }, { "code": null, "e": 27389, "s": 27361, "text": "apt-get purge [...PACKAGES]" }, { "code": null, "e": 27495, "s": 27389, "text": "check : This command is used to update the package cache and checks for broken dependencies.apt-get check" }, { "code": null, "e": 27509, "s": 27495, "text": "apt-get check" }, { "code": null, "e": 27634, "s": 27509, "text": "download : This command is used to download the given binary package in the current directory.apt-get download [...PACKAGES]" }, { "code": null, "e": 27665, "s": 27634, "text": "apt-get download [...PACKAGES]" }, { "code": null, "e": 27881, "s": 27665, "text": "clean : This command is used to clear out the local repository of retrieved package files. It removes everything but not the lock file from /var/cache/apt/archives/partial/ and /var/cache/apt/archives/.apt-get clean" }, { "code": null, "e": 27895, "s": 27881, "text": "apt-get clean" }, { "code": null, "e": 28117, "s": 27895, "text": "autoremove : Sometimes the packages which are automatically installed to satisfy the dependencies of other packages, are no longer needed then autoremove command is used to remove these kind of packages.apt-get autoremove" }, { "code": null, "e": 28136, "s": 28117, "text": "apt-get autoremove" }, { "code": null, "e": 28145, "s": 28136, "text": "Options:" }, { "code": null, "e": 28330, "s": 28145, "text": "–no-install-recommends : By passing this option, the user lets apt-get know not to consider recommended packages as a dependency to install.apt-get --no-install-recommends [...COMMAND]" }, { "code": null, "e": 28375, "s": 28330, "text": "apt-get --no-install-recommends [...COMMAND]" }, { "code": null, "e": 28557, "s": 28375, "text": "–install-suggests : By passing this option, the user lets apt-get know that it should consider suggested packages as dependencies to install.apt-get --install-suggests [...COMMAND]" }, { "code": null, "e": 28598, "s": 28557, "text": "apt-get --install-suggests [...COMMAND]" }, { "code": null, "e": 28767, "s": 28598, "text": "-d or –download-only : By passing this option, the user specifies that apt-get should only retrieve the packages, and not unpack or install them.apt-get -d [...COMMAND]" }, { "code": null, "e": 28791, "s": 28767, "text": "apt-get -d [...COMMAND]" }, { "code": null, "e": 28962, "s": 28791, "text": "-f or –fix-broken : By passing this option, the user specifies that apt-get should attempt to correct the system with broken dependencies in place.apt-get -f [...COMMAND]" }, { "code": null, "e": 28986, "s": 28962, "text": "apt-get -f [...COMMAND]" }, { "code": null, "e": 29229, "s": 28986, "text": "-m or –ignore-missing or –fix-missing : By passing this option, the user specifies that apt-get should ignore the missing packages ( packages that cannot be retrieved or fail the integrity check ) and handle the result.apt-get -m [...COMMAND]" }, { "code": null, "e": 29253, "s": 29229, "text": "apt-get -m [...COMMAND]" }, { "code": null, "e": 29427, "s": 29253, "text": "–no-download : By passing this command, the user disables downloading for apt-get. It means that it should only use the .debs it has already downloaded.apt-get [...COMMAND]" }, { "code": null, "e": 29449, "s": 29427, "text": "apt-get [...COMMAND]" }, { "code": null, "e": 29571, "s": 29449, "text": "-q or –quiet : When this option is specified, apt-get produces output which is suitable for logging.apt-get [...COMMAND]" }, { "code": null, "e": 29593, "s": 29571, "text": "apt-get [...COMMAND]" }, { "code": null, "e": 29847, "s": 29593, "text": "-s or –simulate or –just-print or –dry-run or –recon or –no-act : This option specifies that no action should be taken, and perform a simulation of events that would occur based on the current system, but do not change the system.apt-get -s [...COMMAND]" }, { "code": null, "e": 29871, "s": 29847, "text": "apt-get -s [...COMMAND]" }, { "code": null, "e": 30129, "s": 29871, "text": "-y or –yes or –assume-yes : During the execution of apt-get command, it may sometimes prompt the user for a yes/no. With this option, it is specified that it should assume ‘yes’ for all prompts, and should run without any interaction.apt-get -y [...COMMAND]" }, { "code": null, "e": 30153, "s": 30129, "text": "apt-get -y [...COMMAND]" }, { "code": null, "e": 30254, "s": 30153, "text": "–assume-no : With this option, apt-get assumes ‘no’ for all prompts.apt-get --assume-no [...COMMAND]" }, { "code": null, "e": 30287, "s": 30254, "text": "apt-get --assume-no [...COMMAND]" }, { "code": null, "e": 30436, "s": 30287, "text": "–no-show-upgraded : With this option, apt-get will not show the list of all packages that are to be upgraded.apt-get --no-show-upgraded [...COMMAND]" }, { "code": null, "e": 30476, "s": 30436, "text": "apt-get --no-show-upgraded [...COMMAND]" }, { "code": null, "e": 30612, "s": 30476, "text": "-V or –verbose-versions : With this option, apt-get will show full versions for upgraded and installed packages.apt-get -V [...COMMAND]" }, { "code": null, "e": 30636, "s": 30612, "text": "apt-get -V [...COMMAND]" }, { "code": null, "e": 30831, "s": 30636, "text": "–show-progress : With this option, apt-get will show user-friendly progress in the terminal window when the packages are being installed, removed or upgraded.apt-get --show-progress [...COMMAND]" }, { "code": null, "e": 30868, "s": 30831, "text": "apt-get --show-progress [...COMMAND]" }, { "code": null, "e": 30997, "s": 30868, "text": "-b or –compile or –build : With this option, apt-get will compile/build the source packages it downloads.apt-get -b [...COMMAND]" }, { "code": null, "e": 31021, "s": 30997, "text": "apt-get -b [...COMMAND]" }, { "code": null, "e": 31167, "s": 31021, "text": "–no-upgrade : With this option, apt-get prevents the packages from being upgraded if they are already installed.apt-get --no-upgrade [...COMMAND]" }, { "code": null, "e": 31201, "s": 31167, "text": "apt-get --no-upgrade [...COMMAND]" }, { "code": null, "e": 31368, "s": 31201, "text": "–only-upgrade : With this option, apt-get will only upgrade the packages which are already installed, and not install new packages.apt-get --only-upgrade [...COMMAND]" }, { "code": null, "e": 31404, "s": 31368, "text": "apt-get --only-upgrade [...COMMAND]" }, { "code": null, "e": 31553, "s": 31404, "text": "–reinstall : With this option, apt-get reinstalls the packages that are already installed, at their latest versions.apt-get --reinstall [...COMMAND]" }, { "code": null, "e": 31586, "s": 31553, "text": "apt-get --reinstall [...COMMAND]" }, { "code": null, "e": 31770, "s": 31586, "text": "–auto-remove or –autoremove : When using apt-get with install or remove command, this option acts like running the autoremove command.apt-get install/remove --autoremove [...PACKAGES]" }, { "code": null, "e": 31820, "s": 31770, "text": "apt-get install/remove --autoremove [...PACKAGES]" }, { "code": null, "e": 31909, "s": 31820, "text": "-h or –help : With this option, apt-get displays a short usage summary.apt-get -hOutput:" }, { "code": null, "e": 31920, "s": 31909, "text": "apt-get -h" }, { "code": null, "e": 31928, "s": 31920, "text": "Output:" }, { "code": null, "e": 32037, "s": 31928, "text": "-v or –version : With this option, apt-get displays it’s current version number.apt-get [...COMMAND]Output:" }, { "code": null, "e": 32059, "s": 32037, "text": "apt-get [...COMMAND]" }, { "code": null, "e": 32067, "s": 32059, "text": "Output:" }, { "code": null, "e": 32165, "s": 32067, "text": "Note: apt-get command will return 0 for successful executions, and decimal 100 in case of errors." }, { "code": null, "e": 32186, "s": 32165, "text": "Linux-basic-commands" }, { "code": null, "e": 32200, "s": 32186, "text": "linux-command" }, { "code": null, "e": 32207, "s": 32200, "text": "Picked" }, { "code": null, "e": 32218, "s": 32207, "text": "Linux-Unix" }, { "code": null, "e": 32316, "s": 32218, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32354, "s": 32316, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 32389, "s": 32354, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 32424, "s": 32389, "text": "tar command in Linux with examples" }, { "code": null, "e": 32465, "s": 32424, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 32501, "s": 32465, "text": "curl command in Linux with Examples" }, { "code": null, "e": 32534, "s": 32501, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 32572, "s": 32534, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 32608, "s": 32572, "text": "diff command in Linux with examples" }, { "code": null, "e": 32646, "s": 32608, "text": "Conditional Statements | Shell Script" } ]
A Complete Pandas Glossary for Data Science | by Terence Shin | Towards Data Science
Like most others, I tried to learn Pandas through boot camps — unfortunately, the problem with boot camps is that you forget everything pretty quickly if you don’t practice what you learn! At the same time, I found that there was a need for a central Pandas resource that I could refer to when working on personal data science projects. That’s how this came into fruition. Use this as a resource to learn Pandas and also to refer to! SetupCreating and Reading DataManipulating DataFramesSummary FunctionsMapping FunctionsGrouping and Sorting VariablesHandling Missing Data Setup Creating and Reading Data Manipulating DataFrames Summary Functions Mapping Functions Grouping and Sorting Variables Handling Missing Data import pandas as pd A DataFrame is simply a table made up of multiple arrays. In the example below, the code would create a table with two columns, ABC and DEF. pd.DataFrame({'ABC':[1,2,3],'DEF':[4,5,6]},index=[1,2,3]) A Series is a sequence of values, also known as a list. From a visual perspective, imagine it being one column of a table. pd.Series([1,2,3],index=[], name ='ABC') The most common way of getting our data. This converts a CSV file into a DataFrame. # exampledf = pd.read_csv("filename.csv", index_col=0) Vice versa, if you want to convert a DataFrame into a CSV, you can use the code below: # exampledf.to_csv("filename.csv", index_col=0) This tells you how large a DataFrame is and is in the format (rows, columns). df.shape() If you want to get a visual idea of what a DataFrame looks like, .head() returns the first 5 rows of the given DataFrame. df.head() # For one columndf.variable.dtype# For all columnsdf.dtypes This is useful if you want to convert integers to floats (or vice versa). df.variable.astype() # a) Method 1df.property_name# b) Method 2df['property_name'] # if you want to get the first value in a seriesdf['property_name'][0] Index-based selection retrieves data based on its numerical position in the DataFrame. It follows a rows-first, columns-second format. Iloc’s indexing scheme is such that the first number is inclusive and the last number is exclusive. df.iloc[] Label-based selection is another way to index a DataFrame, but it retrieves data based on the actual data values rather than the numerical position. Loc’s indexing scheme is such that the both the first and last values are inclusive. df.loc[] Because label-based selection relies on the index of the DataFrame, you can use .set_index() to assign a column to the index. df.set_index("variable") We can filter out a DataFrame using Label-based selection too. # a) Single Condition df.loc[df.property_name == 'ABC']# b) Multiple conditions using ANDdf.loc[df.property_name == 'ABC' & df.property_name == 'DEF']# c) Multiple conditions using ORdf.loc[df.property_name == 'ABC' | df.property_name == 'DEF'] We can use isin() to filter a DataFrame as well. If you know SQL, it’s similar to the WHERE ___ IN() statement. df.loc[df.property_name isin(['ABC','DEF']) The first line of code will filter a DataFrame to only show rows where the property name is null. Vice versa, the second line of code with the filter it so that the property name is not null. df.loc[df.property_name.isnull()]df.loc[df.property_name.notnull()] df['new_column'] = 'ABC' You’ll often want to rename a column to something easier to refer to. Using the code below, the column ABC would be renamed to DEF. df.rename(columns={'ABC': 'DEF'}) This gives a high-level summary of a DataFrame or a variable. It is type-sensitive, meaning that its output will be different for numerical variables compared to string variables. df.describe()df.variable.describe() This returns the average of a variable. df.variable.mean() This returns all of the unique values of a variable. df.variable.unique() This shows a list of unique values and also the frequency of occurrence in the DataFrame. df.variable.value_counts() Mapping is used to transform an initial set of values to another set of values through a function. For example, we could use mapping to convert the values of a column from meters to centimeters or we could normalize the values. .map() is used to transform a Series. df.numerical_variable.map() .apply() is similar to .map(), except that it transforms the entire DataFrame. df.numerical_variable.apply() Get the count for each value of a variable (same as value_counts) df.groupby('variable').variable.count() Get the min value for each value of a variable df.groupby('variable').variable.min() Get a summary (length, min, max) for each value of a variable df.groupby(['variable']).variable.agg([len, min, max]) Multi-indexing df.groupby(['variable_one', 'variable_two']) Sorting by one variable df.sort_values(by='variable', ascending=False) Sorting by multiple variables df.sort_values(by=['variable_one', 'variable_two']) Sorting by index df.sort_index() Handling missing data is one of the most important steps in EDA. Below are a number of ways to handle missing data. df.isna().sum() If you have a DataFrame with a large number of rows and you can afford to remove rows with null values completely, then .dropna() is a useful tool. df.dropna() This is similar to above except that it drops any columns with null values rather than the rows. df.dropna(axis=1) If you would rather fill missing values instead of removing the row or column completely, you can use the code below: df.variable.fillna("n/a") Let’s say there’s a DataFrame where someone already filled missing values with “n/a”, but you want the missing values to be filled with “unknown”. Then you can use the following code below: df.variable.replace("n/a", "unknown") This is useful when you want to combine two DataFrames that have the same columns. For example, if we wanted to combine January sales and February sales together to analyze longer-term trends, you could use the following code: Jan_sales = pd.read_csv("jan_sales.csv")Feb_sales = pd.read_csv("feb_sales.csv")pd.concat([Jan_sales, Feb_sales]) If you want to combine two columns that have a common index (e.g. customer_id), then you can use .join(). Use the parameter, on, to determine what column to join on. To determine if it’s a left, right, inner, or outer join, you use the parameter, how. # exampletable_1.join(table_2, on='customer_id', how='left') If you don’t know about SQL joins, read here. It’s essentially the same idea. I hope this is helpful! Please provide comments if you feel that I missed something or if something isn’t clear. Thanks! If you like my work and want to support me... The BEST way to support me is by following me on Medium here.Be one of the FIRST to follow me on Twitter here. I’ll be posting lots of updates and interesting stuff here!Also, be one of the FIRST to subscribe to my new YouTube channel here!Follow me on LinkedIn here.Sign up on my email list here.Check out my website, terenceshin.com. The BEST way to support me is by following me on Medium here. Be one of the FIRST to follow me on Twitter here. I’ll be posting lots of updates and interesting stuff here! Also, be one of the FIRST to subscribe to my new YouTube channel here! Follow me on LinkedIn here. Sign up on my email list here. Check out my website, terenceshin.com.
[ { "code": null, "e": 360, "s": 171, "text": "Like most others, I tried to learn Pandas through boot camps — unfortunately, the problem with boot camps is that you forget everything pretty quickly if you don’t practice what you learn!" }, { "code": null, "e": 605, "s": 360, "text": "At the same time, I found that there was a need for a central Pandas resource that I could refer to when working on personal data science projects. That’s how this came into fruition. Use this as a resource to learn Pandas and also to refer to!" }, { "code": null, "e": 744, "s": 605, "text": "SetupCreating and Reading DataManipulating DataFramesSummary FunctionsMapping FunctionsGrouping and Sorting VariablesHandling Missing Data" }, { "code": null, "e": 750, "s": 744, "text": "Setup" }, { "code": null, "e": 776, "s": 750, "text": "Creating and Reading Data" }, { "code": null, "e": 800, "s": 776, "text": "Manipulating DataFrames" }, { "code": null, "e": 818, "s": 800, "text": "Summary Functions" }, { "code": null, "e": 836, "s": 818, "text": "Mapping Functions" }, { "code": null, "e": 867, "s": 836, "text": "Grouping and Sorting Variables" }, { "code": null, "e": 889, "s": 867, "text": "Handling Missing Data" }, { "code": null, "e": 909, "s": 889, "text": "import pandas as pd" }, { "code": null, "e": 1050, "s": 909, "text": "A DataFrame is simply a table made up of multiple arrays. In the example below, the code would create a table with two columns, ABC and DEF." }, { "code": null, "e": 1108, "s": 1050, "text": "pd.DataFrame({'ABC':[1,2,3],'DEF':[4,5,6]},index=[1,2,3])" }, { "code": null, "e": 1231, "s": 1108, "text": "A Series is a sequence of values, also known as a list. From a visual perspective, imagine it being one column of a table." }, { "code": null, "e": 1272, "s": 1231, "text": "pd.Series([1,2,3],index=[], name ='ABC')" }, { "code": null, "e": 1356, "s": 1272, "text": "The most common way of getting our data. This converts a CSV file into a DataFrame." }, { "code": null, "e": 1411, "s": 1356, "text": "# exampledf = pd.read_csv(\"filename.csv\", index_col=0)" }, { "code": null, "e": 1498, "s": 1411, "text": "Vice versa, if you want to convert a DataFrame into a CSV, you can use the code below:" }, { "code": null, "e": 1546, "s": 1498, "text": "# exampledf.to_csv(\"filename.csv\", index_col=0)" }, { "code": null, "e": 1624, "s": 1546, "text": "This tells you how large a DataFrame is and is in the format (rows, columns)." }, { "code": null, "e": 1635, "s": 1624, "text": "df.shape()" }, { "code": null, "e": 1757, "s": 1635, "text": "If you want to get a visual idea of what a DataFrame looks like, .head() returns the first 5 rows of the given DataFrame." }, { "code": null, "e": 1767, "s": 1757, "text": "df.head()" }, { "code": null, "e": 1827, "s": 1767, "text": "# For one columndf.variable.dtype# For all columnsdf.dtypes" }, { "code": null, "e": 1901, "s": 1827, "text": "This is useful if you want to convert integers to floats (or vice versa)." }, { "code": null, "e": 1922, "s": 1901, "text": "df.variable.astype()" }, { "code": null, "e": 1984, "s": 1922, "text": "# a) Method 1df.property_name# b) Method 2df['property_name']" }, { "code": null, "e": 2055, "s": 1984, "text": "# if you want to get the first value in a seriesdf['property_name'][0]" }, { "code": null, "e": 2290, "s": 2055, "text": "Index-based selection retrieves data based on its numerical position in the DataFrame. It follows a rows-first, columns-second format. Iloc’s indexing scheme is such that the first number is inclusive and the last number is exclusive." }, { "code": null, "e": 2300, "s": 2290, "text": "df.iloc[]" }, { "code": null, "e": 2534, "s": 2300, "text": "Label-based selection is another way to index a DataFrame, but it retrieves data based on the actual data values rather than the numerical position. Loc’s indexing scheme is such that the both the first and last values are inclusive." }, { "code": null, "e": 2543, "s": 2534, "text": "df.loc[]" }, { "code": null, "e": 2669, "s": 2543, "text": "Because label-based selection relies on the index of the DataFrame, you can use .set_index() to assign a column to the index." }, { "code": null, "e": 2694, "s": 2669, "text": "df.set_index(\"variable\")" }, { "code": null, "e": 2757, "s": 2694, "text": "We can filter out a DataFrame using Label-based selection too." }, { "code": null, "e": 3002, "s": 2757, "text": "# a) Single Condition df.loc[df.property_name == 'ABC']# b) Multiple conditions using ANDdf.loc[df.property_name == 'ABC' & df.property_name == 'DEF']# c) Multiple conditions using ORdf.loc[df.property_name == 'ABC' | df.property_name == 'DEF']" }, { "code": null, "e": 3114, "s": 3002, "text": "We can use isin() to filter a DataFrame as well. If you know SQL, it’s similar to the WHERE ___ IN() statement." }, { "code": null, "e": 3158, "s": 3114, "text": "df.loc[df.property_name isin(['ABC','DEF'])" }, { "code": null, "e": 3350, "s": 3158, "text": "The first line of code will filter a DataFrame to only show rows where the property name is null. Vice versa, the second line of code with the filter it so that the property name is not null." }, { "code": null, "e": 3418, "s": 3350, "text": "df.loc[df.property_name.isnull()]df.loc[df.property_name.notnull()]" }, { "code": null, "e": 3443, "s": 3418, "text": "df['new_column'] = 'ABC'" }, { "code": null, "e": 3575, "s": 3443, "text": "You’ll often want to rename a column to something easier to refer to. Using the code below, the column ABC would be renamed to DEF." }, { "code": null, "e": 3609, "s": 3575, "text": "df.rename(columns={'ABC': 'DEF'})" }, { "code": null, "e": 3789, "s": 3609, "text": "This gives a high-level summary of a DataFrame or a variable. It is type-sensitive, meaning that its output will be different for numerical variables compared to string variables." }, { "code": null, "e": 3825, "s": 3789, "text": "df.describe()df.variable.describe()" }, { "code": null, "e": 3865, "s": 3825, "text": "This returns the average of a variable." }, { "code": null, "e": 3884, "s": 3865, "text": "df.variable.mean()" }, { "code": null, "e": 3937, "s": 3884, "text": "This returns all of the unique values of a variable." }, { "code": null, "e": 3958, "s": 3937, "text": "df.variable.unique()" }, { "code": null, "e": 4048, "s": 3958, "text": "This shows a list of unique values and also the frequency of occurrence in the DataFrame." }, { "code": null, "e": 4075, "s": 4048, "text": "df.variable.value_counts()" }, { "code": null, "e": 4303, "s": 4075, "text": "Mapping is used to transform an initial set of values to another set of values through a function. For example, we could use mapping to convert the values of a column from meters to centimeters or we could normalize the values." }, { "code": null, "e": 4341, "s": 4303, "text": ".map() is used to transform a Series." }, { "code": null, "e": 4369, "s": 4341, "text": "df.numerical_variable.map()" }, { "code": null, "e": 4448, "s": 4369, "text": ".apply() is similar to .map(), except that it transforms the entire DataFrame." }, { "code": null, "e": 4478, "s": 4448, "text": "df.numerical_variable.apply()" }, { "code": null, "e": 4544, "s": 4478, "text": "Get the count for each value of a variable (same as value_counts)" }, { "code": null, "e": 4584, "s": 4544, "text": "df.groupby('variable').variable.count()" }, { "code": null, "e": 4631, "s": 4584, "text": "Get the min value for each value of a variable" }, { "code": null, "e": 4669, "s": 4631, "text": "df.groupby('variable').variable.min()" }, { "code": null, "e": 4731, "s": 4669, "text": "Get a summary (length, min, max) for each value of a variable" }, { "code": null, "e": 4786, "s": 4731, "text": "df.groupby(['variable']).variable.agg([len, min, max])" }, { "code": null, "e": 4801, "s": 4786, "text": "Multi-indexing" }, { "code": null, "e": 4846, "s": 4801, "text": "df.groupby(['variable_one', 'variable_two'])" }, { "code": null, "e": 4870, "s": 4846, "text": "Sorting by one variable" }, { "code": null, "e": 4917, "s": 4870, "text": "df.sort_values(by='variable', ascending=False)" }, { "code": null, "e": 4947, "s": 4917, "text": "Sorting by multiple variables" }, { "code": null, "e": 4999, "s": 4947, "text": "df.sort_values(by=['variable_one', 'variable_two'])" }, { "code": null, "e": 5016, "s": 4999, "text": "Sorting by index" }, { "code": null, "e": 5032, "s": 5016, "text": "df.sort_index()" }, { "code": null, "e": 5148, "s": 5032, "text": "Handling missing data is one of the most important steps in EDA. Below are a number of ways to handle missing data." }, { "code": null, "e": 5164, "s": 5148, "text": "df.isna().sum()" }, { "code": null, "e": 5312, "s": 5164, "text": "If you have a DataFrame with a large number of rows and you can afford to remove rows with null values completely, then .dropna() is a useful tool." }, { "code": null, "e": 5324, "s": 5312, "text": "df.dropna()" }, { "code": null, "e": 5421, "s": 5324, "text": "This is similar to above except that it drops any columns with null values rather than the rows." }, { "code": null, "e": 5439, "s": 5421, "text": "df.dropna(axis=1)" }, { "code": null, "e": 5557, "s": 5439, "text": "If you would rather fill missing values instead of removing the row or column completely, you can use the code below:" }, { "code": null, "e": 5583, "s": 5557, "text": "df.variable.fillna(\"n/a\")" }, { "code": null, "e": 5773, "s": 5583, "text": "Let’s say there’s a DataFrame where someone already filled missing values with “n/a”, but you want the missing values to be filled with “unknown”. Then you can use the following code below:" }, { "code": null, "e": 5811, "s": 5773, "text": "df.variable.replace(\"n/a\", \"unknown\")" }, { "code": null, "e": 6038, "s": 5811, "text": "This is useful when you want to combine two DataFrames that have the same columns. For example, if we wanted to combine January sales and February sales together to analyze longer-term trends, you could use the following code:" }, { "code": null, "e": 6152, "s": 6038, "text": "Jan_sales = pd.read_csv(\"jan_sales.csv\")Feb_sales = pd.read_csv(\"feb_sales.csv\")pd.concat([Jan_sales, Feb_sales])" }, { "code": null, "e": 6258, "s": 6152, "text": "If you want to combine two columns that have a common index (e.g. customer_id), then you can use .join()." }, { "code": null, "e": 6318, "s": 6258, "text": "Use the parameter, on, to determine what column to join on." }, { "code": null, "e": 6404, "s": 6318, "text": "To determine if it’s a left, right, inner, or outer join, you use the parameter, how." }, { "code": null, "e": 6465, "s": 6404, "text": "# exampletable_1.join(table_2, on='customer_id', how='left')" }, { "code": null, "e": 6543, "s": 6465, "text": "If you don’t know about SQL joins, read here. It’s essentially the same idea." }, { "code": null, "e": 6664, "s": 6543, "text": "I hope this is helpful! Please provide comments if you feel that I missed something or if something isn’t clear. Thanks!" }, { "code": null, "e": 6710, "s": 6664, "text": "If you like my work and want to support me..." }, { "code": null, "e": 7046, "s": 6710, "text": "The BEST way to support me is by following me on Medium here.Be one of the FIRST to follow me on Twitter here. I’ll be posting lots of updates and interesting stuff here!Also, be one of the FIRST to subscribe to my new YouTube channel here!Follow me on LinkedIn here.Sign up on my email list here.Check out my website, terenceshin.com." }, { "code": null, "e": 7108, "s": 7046, "text": "The BEST way to support me is by following me on Medium here." }, { "code": null, "e": 7218, "s": 7108, "text": "Be one of the FIRST to follow me on Twitter here. I’ll be posting lots of updates and interesting stuff here!" }, { "code": null, "e": 7289, "s": 7218, "text": "Also, be one of the FIRST to subscribe to my new YouTube channel here!" }, { "code": null, "e": 7317, "s": 7289, "text": "Follow me on LinkedIn here." }, { "code": null, "e": 7348, "s": 7317, "text": "Sign up on my email list here." } ]
GATE | GATE-CS-2015 (Set 1) | Question 64 - GeeksforGeeks
17 Sep, 2021 The least number of temporary variables required to create a three-address code in static single assignment form for the expression q + r/3 + s – t * 5 + u * v/w is(A) 4(B) 8(C) 7(D) 9Answer: (B)Explanation: The correct answer is 8. This question was asked as a fill in the blank type question in the exam. Three address code is an intermediate code generated by compilers while optimizing the code. Each three address code instruction can have atmost three operands (constants and variables) combined with an assignment and a binary operator. The point to be noted in three address code is that the variables used on the left hand side (LHS) of the assignment cannot be repeated again in the LHS side. Static single assignment (SSA) is nothing but a refinement of the three address code. So, in this question, we have t1 = r / 3; t2 = t * 5; t3 = u * v; t4 = t3 / w; t5 = q + t1; t6 = t5 + s; t7 = t6 - t2; t8 = t7 + t4; Therefore, we require 8 temporary variables (t1 to t8) to create the three address code in static single assignment form. YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQ - Code Generation and Optimization | Joyojyoti Acharya | GeeksforGeeks GATE |Watch 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:0050:30 / 59:20•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=4ab8S2Qs7h8" 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-CS-2015 (Set 1) GATE-GATE-CS-2015 (Set 1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE-IT-2004 | Question 83 GATE | GATE CS 2018 | Question 37 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-CS-2016 (Set 1) | Question 63 GATE | GATE-CS-2007 | Question 17 GATE | GATE-IT-2004 | Question 12 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2007 | Question 64
[ { "code": null, "e": 24346, "s": 24318, "text": "\n17 Sep, 2021" }, { "code": null, "e": 24554, "s": 24346, "text": "The least number of temporary variables required to create a three-address code in static single assignment form for the expression q + r/3 + s – t * 5 + u * v/w is(A) 4(B) 8(C) 7(D) 9Answer: (B)Explanation:" }, { "code": null, "e": 24653, "s": 24554, "text": "The correct answer is 8. This question was asked as a fill in the blank type question in the exam." }, { "code": null, "e": 25137, "s": 24655, "text": "Three address code is an intermediate code generated by compilers while optimizing the code. Each three address code instruction can have atmost three operands (constants and variables) combined with an assignment and a binary operator. The point to be noted in three address code is that the variables used on the left hand side (LHS) of the assignment cannot be repeated again in the LHS side. Static single assignment (SSA) is nothing but a refinement of the three address code." }, { "code": null, "e": 25167, "s": 25137, "text": "So, in this question, we have" }, { "code": null, "e": 25278, "s": 25167, "text": "t1 = r / 3;\n\nt2 = t * 5;\n\nt3 = u * v;\n\nt4 = t3 / w;\n\nt5 = q + t1;\n\nt6 = t5 + s;\n\nt7 = t6 - t2; \n\nt8 = t7 + t4;" }, { "code": null, "e": 25400, "s": 25278, "text": "Therefore, we require 8 temporary variables (t1 to t8) to create the three address code in static single assignment form." }, { "code": null, "e": 26315, "s": 25400, "text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQ - Code Generation and Optimization | Joyojyoti Acharya | GeeksforGeeks GATE |Watch 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:0050:30 / 59:20•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=4ab8S2Qs7h8\" 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": 26336, "s": 26315, "text": "GATE-CS-2015 (Set 1)" }, { "code": null, "e": 26362, "s": 26336, "text": "GATE-GATE-CS-2015 (Set 1)" }, { "code": null, "e": 26367, "s": 26362, "text": "GATE" }, { "code": null, "e": 26465, "s": 26367, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26474, "s": 26465, "text": "Comments" }, { "code": null, "e": 26487, "s": 26474, "text": "Old Comments" }, { "code": null, "e": 26529, "s": 26487, "text": "GATE | GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 26563, "s": 26529, "text": "GATE | GATE-IT-2004 | Question 83" }, { "code": null, "e": 26597, "s": 26563, "text": "GATE | GATE CS 2018 | Question 37" }, { "code": null, "e": 26639, "s": 26597, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 26681, "s": 26639, "text": "GATE | GATE-CS-2016 (Set 1) | Question 65" }, { "code": null, "e": 26723, "s": 26681, "text": "GATE | GATE-CS-2016 (Set 1) | Question 63" }, { "code": null, "e": 26757, "s": 26723, "text": "GATE | GATE-CS-2007 | Question 17" }, { "code": null, "e": 26791, "s": 26757, "text": "GATE | GATE-IT-2004 | Question 12" }, { "code": null, "e": 26833, "s": 26791, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" } ]
9 Cool Julia Tricks In 4 Minutes. The Best features of the Julia REPL | by DJ Passey | Towards Data Science
Julia is a new scientific computing language that is as easy to learn as Python, but executes as fast as C. Julia is a compiled language but since it uses a just in time compiler, (like Java), your code can be executed immediately. This feature is put to use in the Julia REPL where you can run lines or blocks of code. REPL stands for read, execute, print, loop. Once Julia is installed, typing Julia at the command line opens the REPL. The REPL has many features that can help you test snippets and debug your code. Type ] at the beginning of the line to enter package mode. This is a shortcut to accessing Julia’s package manager, Pkg. In this mode you can install packages, update them, look at the versions of current packages and more. A few useful commands in package mode are add, remove, build, and update. Typing ; at the beginning of a line enters shell mode. This changes the Julia REPL to run bash commands instead of Julia. In shell mode, the REPL acts like a Bash shell and you can enter your standard bash commands like ls, cd, mkdir, and others. I’ve used this feature a lot. Type ? to enter help mode. In this mode, you can see function or type documentation as well as other tips and hints. When you enter text, Julia will search for documentation and function names that match the text you entered. julia> uppercase([PRESS TAB] uppercase(c::T) where T<:AbstractChar in Base.Unicode at strings/unicode.jl:247 uppercase(s::AbstractString) in Base.Unicode at strings/unicode.jl:518 Tab completion works the same way in the REPL as it works in the shell, or in iPython, but it has an additional useful feature. When typing a function name, press tab after the open parenthesis. If you do, Julia will display a list of methods associated with the function name, the types of their arguments and their location in the source code. julia> @doc max max(x, y, ...)Return the maximum of the arguments. See also the maximum function to take the maximum element from a collection. Calling @doc before a function or type will print the documentation of that object. (In Julia documentation appears in a string before the function definition.) This is useful for quickly finding a function that you need, or reminding yourself about a particular function’s usage. julia> @time sum(rand(1000)); 0.000030 seconds (6 allocations: 8.109 KiB) The @time macro is another extremely useful tool. As you might expect, it times the execution of the statement it precedes. julia> apropos("capital") Base.Unicode.titlecase Base.Unicode.uppercasefirst This function accepts a string and searches all documentation for relevant functions and types. This can help avoid digging through documentation to find the functions you need. julia> methods(uppercase) # 2 methods for generic function "uppercase": [1] uppercase(c::T) where T<:AbstractChar in Base.Unicode at strings/unicode.jl:247 [2] uppercase(s::AbstractString) in Base.Unicode at strings/unicode.jl:518 The methods function accepts a function and returns all dispatched definitions of the function, along with the types they accept and where they are found in the source code. This is useful when you are trying to find a function or when you can’t remember to order of arguments. julia> using Fluxjulia> methodswith(BatchNorm) [1] show(io::IO, l::BatchNorm) in Flux at /Users/djpassey/.julia/packages/Flux/NpkMm/src/layers/normalise.jl:211 [2] testmode!(m::BatchNorm) in Flux at /Users/djpassey/.julia/packages/Flux/NpkMm/src/layers/normalise.jl:207 [3] testmode!(m::BatchNorm, mode) in Flux at /Users/djpassey/.julia/packages/Flux/NpkMm/src/layers/normalise.jl:207 This is another useful function. This function accepts types and returns all functions that act on that type. In the example above I import a machine learning package, Flux, and call methodswith on the BatchNorm struct. It shows us that there are three functions that accept BatchNorm objects as arguments. This is useful when you are getting to know a new package and want to learn about the structs defined in the library. It is also helpful when you are looking for a function to act on a certain type. Overall the Julia REPL can be extremely useful in helping developers locate the right functions and test snippets of code. Hopefully, these tips will come in handy and speed up your Julia development.
[ { "code": null, "e": 536, "s": 172, "text": "Julia is a new scientific computing language that is as easy to learn as Python, but executes as fast as C. Julia is a compiled language but since it uses a just in time compiler, (like Java), your code can be executed immediately. This feature is put to use in the Julia REPL where you can run lines or blocks of code. REPL stands for read, execute, print, loop." }, { "code": null, "e": 690, "s": 536, "text": "Once Julia is installed, typing Julia at the command line opens the REPL. The REPL has many features that can help you test snippets and debug your code." }, { "code": null, "e": 988, "s": 690, "text": "Type ] at the beginning of the line to enter package mode. This is a shortcut to accessing Julia’s package manager, Pkg. In this mode you can install packages, update them, look at the versions of current packages and more. A few useful commands in package mode are add, remove, build, and update." }, { "code": null, "e": 1265, "s": 988, "text": "Typing ; at the beginning of a line enters shell mode. This changes the Julia REPL to run bash commands instead of Julia. In shell mode, the REPL acts like a Bash shell and you can enter your standard bash commands like ls, cd, mkdir, and others. I’ve used this feature a lot." }, { "code": null, "e": 1491, "s": 1265, "text": "Type ? to enter help mode. In this mode, you can see function or type documentation as well as other tips and hints. When you enter text, Julia will search for documentation and function names that match the text you entered." }, { "code": null, "e": 1677, "s": 1491, "text": "julia> uppercase([PRESS TAB] uppercase(c::T) where T<:AbstractChar in Base.Unicode at strings/unicode.jl:247 uppercase(s::AbstractString) in Base.Unicode at strings/unicode.jl:518" }, { "code": null, "e": 2023, "s": 1677, "text": "Tab completion works the same way in the REPL as it works in the shell, or in iPython, but it has an additional useful feature. When typing a function name, press tab after the open parenthesis. If you do, Julia will display a list of methods associated with the function name, the types of their arguments and their location in the source code." }, { "code": null, "e": 2168, "s": 2023, "text": "julia> @doc max max(x, y, ...)Return the maximum of the arguments. See also the maximum function to take the maximum element from a collection." }, { "code": null, "e": 2449, "s": 2168, "text": "Calling @doc before a function or type will print the documentation of that object. (In Julia documentation appears in a string before the function definition.) This is useful for quickly finding a function that you need, or reminding yourself about a particular function’s usage." }, { "code": null, "e": 2523, "s": 2449, "text": "julia> @time sum(rand(1000)); 0.000030 seconds (6 allocations: 8.109 KiB)" }, { "code": null, "e": 2647, "s": 2523, "text": "The @time macro is another extremely useful tool. As you might expect, it times the execution of the statement it precedes." }, { "code": null, "e": 2725, "s": 2647, "text": "julia> apropos(\"capital\") Base.Unicode.titlecase Base.Unicode.uppercasefirst" }, { "code": null, "e": 2903, "s": 2725, "text": "This function accepts a string and searches all documentation for relevant functions and types. This can help avoid digging through documentation to find the functions you need." }, { "code": null, "e": 3134, "s": 2903, "text": "julia> methods(uppercase) # 2 methods for generic function \"uppercase\": [1] uppercase(c::T) where T<:AbstractChar in Base.Unicode at strings/unicode.jl:247 [2] uppercase(s::AbstractString) in Base.Unicode at strings/unicode.jl:518" }, { "code": null, "e": 3412, "s": 3134, "text": "The methods function accepts a function and returns all dispatched definitions of the function, along with the types they accept and where they are found in the source code. This is useful when you are trying to find a function or when you can’t remember to order of arguments." }, { "code": null, "e": 3798, "s": 3412, "text": "julia> using Fluxjulia> methodswith(BatchNorm) [1] show(io::IO, l::BatchNorm) in Flux at /Users/djpassey/.julia/packages/Flux/NpkMm/src/layers/normalise.jl:211 [2] testmode!(m::BatchNorm) in Flux at /Users/djpassey/.julia/packages/Flux/NpkMm/src/layers/normalise.jl:207 [3] testmode!(m::BatchNorm, mode) in Flux at /Users/djpassey/.julia/packages/Flux/NpkMm/src/layers/normalise.jl:207" }, { "code": null, "e": 4105, "s": 3798, "text": "This is another useful function. This function accepts types and returns all functions that act on that type. In the example above I import a machine learning package, Flux, and call methodswith on the BatchNorm struct. It shows us that there are three functions that accept BatchNorm objects as arguments." }, { "code": null, "e": 4304, "s": 4105, "text": "This is useful when you are getting to know a new package and want to learn about the structs defined in the library. It is also helpful when you are looking for a function to act on a certain type." } ]
Get the list of all declared fields in Java
The list of all declared fields can be obtained using the java.lang.Class.getDeclaredFields() method as it returns an array of field objects. These field objects include the objects with the public, private, protected and default access but not the inherited fields. Also, the getDeclaredFields() method returns a zero length array if the class or interface has no declared fields or if a primitive type, array class or void is represented in the Class object. A program that demonstrates this is given as follows − Live Demo import java.lang.reflect.*; public class Demo { public static void main(String[] argv) throws Exception { Class c = java.lang.String.class; Field[] fields = c.getDeclaredFields(); for(int i = 0; i < fields.length; i++) { System.out.println("The Field is: " + fields[i].toString()); } } } The Field is: private final char[] java.lang.String.value The Field is: private int java.lang.String.hash The Field is: private static final long java.lang.String.serialVersionUID The Field is: private static final java.io.ObjectStreamField[] java.lang.String.serialPersistentFields The Field is: public static final java.util.Comparator java.lang.String.CASE_INSENSITIVE_ORDER Now let us understand the above program. The class c holds the java.lang.String.class.. Then the array fields[] stores the field objects of this class that are obtained using the method getDeclaredFields(). Then the fields are displayed using the for loop. A code snippet which demonstrates this is as follows − Class c = java.lang.String.class; Field[] fields = c.getDeclaredFields(); for(int i = 0; i < fields.length; i++) { System.out.println("The Field is: " + fields[i].toString()); }
[ { "code": null, "e": 1329, "s": 1062, "text": "The list of all declared fields can be obtained using the java.lang.Class.getDeclaredFields() method as it returns an array of field objects. These field objects include the objects with the public, private, protected and default access but not the inherited fields." }, { "code": null, "e": 1523, "s": 1329, "text": "Also, the getDeclaredFields() method returns a zero length array if the class or interface has no declared fields or if a primitive type, array class or void is represented in the Class object." }, { "code": null, "e": 1578, "s": 1523, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1589, "s": 1578, "text": " Live Demo" }, { "code": null, "e": 1916, "s": 1589, "text": "import java.lang.reflect.*;\npublic class Demo {\n public static void main(String[] argv) throws Exception {\n Class c = java.lang.String.class;\n Field[] fields = c.getDeclaredFields();\n for(int i = 0; i < fields.length; i++) {\n System.out.println(\"The Field is: \" + fields[i].toString());\n }\n }\n}" }, { "code": null, "e": 2294, "s": 1916, "text": "The Field is: private final char[] java.lang.String.value The Field is: private int java.lang.String.hash The Field is: private static final long java.lang.String.serialVersionUID The Field is: private static final java.io.ObjectStreamField[] java.lang.String.serialPersistentFields The Field is: public static final java.util.Comparator java.lang.String.CASE_INSENSITIVE_ORDER" }, { "code": null, "e": 2335, "s": 2294, "text": "Now let us understand the above program." }, { "code": null, "e": 2606, "s": 2335, "text": "The class c holds the java.lang.String.class.. Then the array fields[] stores the field objects of this class that are obtained using the method getDeclaredFields(). Then the fields are displayed using the for loop. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2787, "s": 2606, "text": "Class c = java.lang.String.class;\nField[] fields = c.getDeclaredFields();\nfor(int i = 0; i < fields.length; i++) {\n System.out.println(\"The Field is: \" + fields[i].toString());\n}" } ]
7 Ways to Handle Missing Values in Machine Learning | by Satyam Kumar | Towards Data Science
The real-world data often has a lot of missing values. The cause of missing values can be data corruption or failure to record data. The handling of missing data is very important during the preprocessing of the dataset as many machine learning algorithms do not support missing values. This article covers 7 ways to handle missing values in the dataset: Deleting Rows with missing valuesImpute missing values for continuous variableImpute missing values for categorical variableOther Imputation MethodsUsing Algorithms that support missing valuesPrediction of missing valuesImputation using Deep Learning Library — Datawig Deleting Rows with missing values Impute missing values for continuous variable Impute missing values for categorical variable Other Imputation Methods Using Algorithms that support missing values Prediction of missing values Imputation using Deep Learning Library — Datawig Data used is Titanic Dataset from Kaggle data = pd.read_csv("train.csv")msno.matrix(data) Missing values can be handled by deleting the rows or columns having null values. If columns have more than half of the rows as null then the entire column can be dropped. The rows which are having one or more columns values as null can also be dropped. Pros: A model trained with the removal of all missing values creates a robust model. Cons: Loss of a lot of information. Works poorly if the percentage of missing values is excessive in comparison to the complete dataset. Columns in the dataset which are having numeric continuous values can be replaced with the mean, median, or mode of remaining values in the column. This method can prevent the loss of data compared to the earlier method. Replacing the above two approximations (mean, median) is a statistical approach to handle the missing values. The missing values are replaced by the mean value in the above example, in the same way, it can be replaced by the median value. Pros: Prevent data loss which results in deletion of rows or columns Works well with a small dataset and is easy to implement. Cons: Works only with numerical continuous variables. Can cause data leakage Do not factor the covariance between features. When missing values is from categorical columns (string or numerical) then the missing values can be replaced with the most frequent category. If the number of missing values is very large then it can be replaced with a new category. Pros: Prevent data loss which results in deletion of rows or columns Works well with a small dataset and is easy to implement. Negates the loss of data by adding a unique category Cons: Works only with categorical variables. Addition of new features to the model while encoding, which may result in poor performance Depending on the nature of the data or data type, some other imputation methods may be more appropriate to impute missing values. For example, for the data variable having longitudinal behavior, it might make sense to use the last valid observation to fill the missing value. This is known as the Last observation carried forward (LOCF) method. For the time-series dataset variable, it makes sense to use the interpolation of the variable before and after a timestamp for a missing value. All the machine learning algorithms don’t support missing values but some ML algorithms are robust to missing values in the dataset. The k-NN algorithm can ignore a column from a distance measure when a value is missing. Naive Bayes can also support missing values when making a prediction. These algorithms can be used when the dataset contains null or missing values. The sklearn implementations of naive Bayes and k-Nearest Neighbors in Python do not support the presence of the missing values. Another algorithm that can be used here is RandomForest that works well on non-linear and categorical data. It adapts to the data structure taking into consideration the high variance or the bias, producing better results on large datasets. Pros: No need to handle missing values in each column as ML algorithms will handle them efficiently. Cons: No implementation of these ML algorithms in the scikit-learn library. In the earlier methods to handle missing values, we do not use the correlation advantage of the variable containing the missing value and other variables. Using the other features which don’t have nulls can be used to predict missing values. The regression or classification model can be used for the prediction of missing values depending on the nature (categorical or continuous) of the feature having missing value. Here 'Age' column contains missing values so for prediction of null values the spliting of data will be,y_train: rows from data["Age"] with non null valuesy_test: rows from data["Age"] with null valuesX_train: Dataset except data["Age"] features with non null valuesX_test: Dataset except data["Age"] features with null values towardsdatascience.com Pros: Gives a better result than earlier methods Takes into account the covariance between the missing value column and other columns. Cons: Considered only as a proxy for the true values This method works very well with categorical, continuous, and non-numerical features. Datawig is a library that learns ML models using Deep Neural Networks to impute missing values in the datagram. Install datawig library,pip3 install datawig Datawig can take a data frame and fit an imputation model for each column with missing values, with all other columns as inputs. Below is the code to impute missing values in the Age column Pros: Quite accurate compared to other methods. It supports CPUs and GPUs. Cons: Can be quite slow with large datasets. Every dataset has missing values that need to be handled intelligently to create a robust model. In this article, I have discussed 7 ways to handle missing values that can handle missing values in every type of column. There is no thump rule to handle missing values in a particular manner, the method which gets a robust model with the best performance. One can use various methods on different features depending on how and what the data is about. Having domain knowledge about the dataset is important, which can give an insight into how to preprocess the data and handle missing values. References: [1] Datawig: https://github.com/awslabs/datawig Loved the article? Become a Medium member to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, with no extra cost to you. satyam-kumar.medium.com Thank You for Reading
[ { "code": null, "e": 459, "s": 172, "text": "The real-world data often has a lot of missing values. The cause of missing values can be data corruption or failure to record data. The handling of missing data is very important during the preprocessing of the dataset as many machine learning algorithms do not support missing values." }, { "code": null, "e": 527, "s": 459, "text": "This article covers 7 ways to handle missing values in the dataset:" }, { "code": null, "e": 796, "s": 527, "text": "Deleting Rows with missing valuesImpute missing values for continuous variableImpute missing values for categorical variableOther Imputation MethodsUsing Algorithms that support missing valuesPrediction of missing valuesImputation using Deep Learning Library — Datawig" }, { "code": null, "e": 830, "s": 796, "text": "Deleting Rows with missing values" }, { "code": null, "e": 876, "s": 830, "text": "Impute missing values for continuous variable" }, { "code": null, "e": 923, "s": 876, "text": "Impute missing values for categorical variable" }, { "code": null, "e": 948, "s": 923, "text": "Other Imputation Methods" }, { "code": null, "e": 993, "s": 948, "text": "Using Algorithms that support missing values" }, { "code": null, "e": 1022, "s": 993, "text": "Prediction of missing values" }, { "code": null, "e": 1071, "s": 1022, "text": "Imputation using Deep Learning Library — Datawig" }, { "code": null, "e": 1112, "s": 1071, "text": "Data used is Titanic Dataset from Kaggle" }, { "code": null, "e": 1161, "s": 1112, "text": "data = pd.read_csv(\"train.csv\")msno.matrix(data)" }, { "code": null, "e": 1415, "s": 1161, "text": "Missing values can be handled by deleting the rows or columns having null values. If columns have more than half of the rows as null then the entire column can be dropped. The rows which are having one or more columns values as null can also be dropped." }, { "code": null, "e": 1421, "s": 1415, "text": "Pros:" }, { "code": null, "e": 1500, "s": 1421, "text": "A model trained with the removal of all missing values creates a robust model." }, { "code": null, "e": 1506, "s": 1500, "text": "Cons:" }, { "code": null, "e": 1536, "s": 1506, "text": "Loss of a lot of information." }, { "code": null, "e": 1637, "s": 1536, "text": "Works poorly if the percentage of missing values is excessive in comparison to the complete dataset." }, { "code": null, "e": 1968, "s": 1637, "text": "Columns in the dataset which are having numeric continuous values can be replaced with the mean, median, or mode of remaining values in the column. This method can prevent the loss of data compared to the earlier method. Replacing the above two approximations (mean, median) is a statistical approach to handle the missing values." }, { "code": null, "e": 2097, "s": 1968, "text": "The missing values are replaced by the mean value in the above example, in the same way, it can be replaced by the median value." }, { "code": null, "e": 2103, "s": 2097, "text": "Pros:" }, { "code": null, "e": 2166, "s": 2103, "text": "Prevent data loss which results in deletion of rows or columns" }, { "code": null, "e": 2224, "s": 2166, "text": "Works well with a small dataset and is easy to implement." }, { "code": null, "e": 2230, "s": 2224, "text": "Cons:" }, { "code": null, "e": 2278, "s": 2230, "text": "Works only with numerical continuous variables." }, { "code": null, "e": 2301, "s": 2278, "text": "Can cause data leakage" }, { "code": null, "e": 2348, "s": 2301, "text": "Do not factor the covariance between features." }, { "code": null, "e": 2582, "s": 2348, "text": "When missing values is from categorical columns (string or numerical) then the missing values can be replaced with the most frequent category. If the number of missing values is very large then it can be replaced with a new category." }, { "code": null, "e": 2588, "s": 2582, "text": "Pros:" }, { "code": null, "e": 2651, "s": 2588, "text": "Prevent data loss which results in deletion of rows or columns" }, { "code": null, "e": 2709, "s": 2651, "text": "Works well with a small dataset and is easy to implement." }, { "code": null, "e": 2762, "s": 2709, "text": "Negates the loss of data by adding a unique category" }, { "code": null, "e": 2768, "s": 2762, "text": "Cons:" }, { "code": null, "e": 2807, "s": 2768, "text": "Works only with categorical variables." }, { "code": null, "e": 2898, "s": 2807, "text": "Addition of new features to the model while encoding, which may result in poor performance" }, { "code": null, "e": 3028, "s": 2898, "text": "Depending on the nature of the data or data type, some other imputation methods may be more appropriate to impute missing values." }, { "code": null, "e": 3243, "s": 3028, "text": "For example, for the data variable having longitudinal behavior, it might make sense to use the last valid observation to fill the missing value. This is known as the Last observation carried forward (LOCF) method." }, { "code": null, "e": 3387, "s": 3243, "text": "For the time-series dataset variable, it makes sense to use the interpolation of the variable before and after a timestamp for a missing value." }, { "code": null, "e": 3757, "s": 3387, "text": "All the machine learning algorithms don’t support missing values but some ML algorithms are robust to missing values in the dataset. The k-NN algorithm can ignore a column from a distance measure when a value is missing. Naive Bayes can also support missing values when making a prediction. These algorithms can be used when the dataset contains null or missing values." }, { "code": null, "e": 3885, "s": 3757, "text": "The sklearn implementations of naive Bayes and k-Nearest Neighbors in Python do not support the presence of the missing values." }, { "code": null, "e": 4126, "s": 3885, "text": "Another algorithm that can be used here is RandomForest that works well on non-linear and categorical data. It adapts to the data structure taking into consideration the high variance or the bias, producing better results on large datasets." }, { "code": null, "e": 4132, "s": 4126, "text": "Pros:" }, { "code": null, "e": 4227, "s": 4132, "text": "No need to handle missing values in each column as ML algorithms will handle them efficiently." }, { "code": null, "e": 4233, "s": 4227, "text": "Cons:" }, { "code": null, "e": 4303, "s": 4233, "text": "No implementation of these ML algorithms in the scikit-learn library." }, { "code": null, "e": 4545, "s": 4303, "text": "In the earlier methods to handle missing values, we do not use the correlation advantage of the variable containing the missing value and other variables. Using the other features which don’t have nulls can be used to predict missing values." }, { "code": null, "e": 4722, "s": 4545, "text": "The regression or classification model can be used for the prediction of missing values depending on the nature (categorical or continuous) of the feature having missing value." }, { "code": null, "e": 5049, "s": 4722, "text": "Here 'Age' column contains missing values so for prediction of null values the spliting of data will be,y_train: rows from data[\"Age\"] with non null valuesy_test: rows from data[\"Age\"] with null valuesX_train: Dataset except data[\"Age\"] features with non null valuesX_test: Dataset except data[\"Age\"] features with null values" }, { "code": null, "e": 5072, "s": 5049, "text": "towardsdatascience.com" }, { "code": null, "e": 5078, "s": 5072, "text": "Pros:" }, { "code": null, "e": 5121, "s": 5078, "text": "Gives a better result than earlier methods" }, { "code": null, "e": 5207, "s": 5121, "text": "Takes into account the covariance between the missing value column and other columns." }, { "code": null, "e": 5213, "s": 5207, "text": "Cons:" }, { "code": null, "e": 5260, "s": 5213, "text": "Considered only as a proxy for the true values" }, { "code": null, "e": 5458, "s": 5260, "text": "This method works very well with categorical, continuous, and non-numerical features. Datawig is a library that learns ML models using Deep Neural Networks to impute missing values in the datagram." }, { "code": null, "e": 5503, "s": 5458, "text": "Install datawig library,pip3 install datawig" }, { "code": null, "e": 5632, "s": 5503, "text": "Datawig can take a data frame and fit an imputation model for each column with missing values, with all other columns as inputs." }, { "code": null, "e": 5693, "s": 5632, "text": "Below is the code to impute missing values in the Age column" }, { "code": null, "e": 5699, "s": 5693, "text": "Pros:" }, { "code": null, "e": 5741, "s": 5699, "text": "Quite accurate compared to other methods." }, { "code": null, "e": 5768, "s": 5741, "text": "It supports CPUs and GPUs." }, { "code": null, "e": 5774, "s": 5768, "text": "Cons:" }, { "code": null, "e": 5813, "s": 5774, "text": "Can be quite slow with large datasets." }, { "code": null, "e": 6404, "s": 5813, "text": "Every dataset has missing values that need to be handled intelligently to create a robust model. In this article, I have discussed 7 ways to handle missing values that can handle missing values in every type of column. There is no thump rule to handle missing values in a particular manner, the method which gets a robust model with the best performance. One can use various methods on different features depending on how and what the data is about. Having domain knowledge about the dataset is important, which can give an insight into how to preprocess the data and handle missing values." }, { "code": null, "e": 6416, "s": 6404, "text": "References:" }, { "code": null, "e": 6464, "s": 6416, "text": "[1] Datawig: https://github.com/awslabs/datawig" }, { "code": null, "e": 6653, "s": 6464, "text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a small portion of your membership fee if you use the following link, with no extra cost to you." }, { "code": null, "e": 6677, "s": 6653, "text": "satyam-kumar.medium.com" } ]
12 Colab Notebooks that matter. StyleGAN, GPT-2, StyleTransfer... | by Merzmensch | Towards Data Science
It took at least two AI Winters to survive. The story is obvious: theoretically, Artificial Intelligence as a concept was already here. Neuronal Networks (as a concept: 1943 — McCulloch&Pitts /functional: 1965 — Ivakhnenko/Lapa), Machine learning (Samuel, 1959), Backpropagation (Werbos — 1975), just to name some of the key researches. Theoretically. But in practice, computational power was still like this: AI research had still to wait for practical realization. Finally, in the 2000s, every owner of a personal computer became able to do experiments with Machine and Deep Learning. I remember 2016, as Google Deep Dream emerged (thank Alexander Mordvintsev). It took a good amount of time for me to set it up and to get it running. But the results were astonishing: I was in love with AI. And I wanted to try out more. Then I discovered Colab Notebooks. And they changed my life. Google Colab Notebooks enable the democratization of Data Science. They allow it everybody — AI researcher, artist, data scientist et al. — to enjoy the power of Machine and Deep Learning on every device (even on smartphones). Just run the cells, change the parameters, values, and sources, and enjoy the diversity of AI. I want to share with you some of my favorite Notebooks. Try them out! You can find many great essays here at Towards Data Science about backgrounds and working with Colab Notebooks. What’s this about? DeepDream visualizes pattern recognition, interpretation and iterative generation by Neural Networks. By increasing this creative interpretation you can produce dream-alike imagery. Neural Networks act like our brain in the case of Pareidolia: it looks for familiar patterns, which derive from datasets they were trained on. The example above (a screen from my presentation on the AI Meetup Frankfurt, November 2019) demonstrates how our brain recognizes a face in the rock formations of Cydonia region on Mars. A user Nixtown transformed Da Vinci’s Mona Lisa by continuous DeepDream iterations — and AI recognizes weird patterns. Often our brain recognizes patterns or objects which aren’t there. But if our human perception does it, why AI shouldn’t? Links: Original Blog post by Alexander Mordvintsev GitHub Colab Notebook Things to try out: Try to generate different patterns and to resize images (octaves). Use more iterations. And don’t be afraid of insanity — the results could be unsettling. Fun fact: Initially, DeepDream used to recognize in every pattern mostly dog faces. According to FastCompany, the Network was trained on... a smaller subset of the ImageNet database released in 2012 for use in a contest... a subset which contained “fine-grained classification of 120 dog sub-classes (FastCompany). Read more about my experiments with DeepDream. What’s this about? BigGAN was one of the first prominent Generative Adversarial Networks. Trained on ImageNet at a now-humble 128x128 resolution this Network became a standard by its manifold generative abilities. In this notebook, you can generate samples from a long list of categories. Links: BigGAN paper on arXiv (Andrew Brock, Jeff Donahue, and Karen Simonyan. Large Scale GAN Training for High Fidelity Natural Image Synthesis. arxiv:1809.11096, 2018) Colab Notebook Things to try out: The same notebook allows you to create interpolation between images. This approach was — and is — mindblowing and innovative since only Surrealists and Abstract Artists were previously so courageous to combine incompatible things. Now you can do it with photorealistic results, for example, generate an interpolation between a Yorkshire terrier and a Space shuttle. Read also: BigGAN as a creative engine BigGAN and Metamorphosis of Everything What’s this about: In this experiment, the Deep Learned systems examine two source images — and transfer their style: not only colors but also shapes and patterns. Links: Lucid (TensorFlow) Colab Notebook Read also: Style Transfer (and you can do it as well) AI&Creativity: Alien Elements with Style There are many approaches to train AI on Artworks. One of them was provided via Reddit: StyleGAN trained on Artwork Dataset with 24k images from Kaggle. You get interesting results, it could even be possible to trace the original artworks the model was trained on. (New art game, everybody? “Visual Etymology”): Another one is WikiART StyleGAN2 Conditional Model, provided by Peter Baylies (et al) and packed into a notebook by Doron Adler: This model was trained on WikiART images. It allows even to choose between artists, genres and styles. And the images are impressive: Things to try out: Every new combination produces interesting artworks. Try to select artists from different epochs with an untypical style. Like Picasso & Renaissance or Shishkin & Pop Art. The results are sometimes unexpected and not always comprehensible, but that’s art after all. Links: _C0D32_ Colab Notebook (trained on 24k Artworks) WikiART StyleGAN2 Colab Notebook Read also: How to Train Your Artist. The Non-Treachery of Dataset. What’s this about? This network, developed by NVidia, is at the moment (6th March 2020, 4:27 pm) the most advanced generative network for images. It was trained on High-Definition-Datasets (for example, Faces from Flickr-Faces-HQ). StyleGAN2 provides automatically learned, unsupervised separation of high-level attributes, stochastic variation and control of layers with visual features. There are various StyleGAN2-Notebooks (benefits of crowdsourced research), but my favorite is finetuned by Mikael Christensen. Links: Paper: https://arxiv.org/abs/1812.04948 Video: https://youtu.be/kSLJriaOumA Code: https://github.com/NVlabs/stylegan / https://github.com/NVlabs/stylegan2 Colab Notebook Things to try out: There are various default datasets by NVidia available within the notebook (mind the resolution): Try out new Datasets. Train your own models or use those, provided by various artists and researchers, like Michael Friesen (follow his twitter for new updates). Bacteria StyleGAN Art-StyleGAN: MC Escher-StyleGAN: Produce videos of interpolations: Try out StyleGAN2 projection. With the StyleGAN2 notebook you discover (or better: re-cover) images being hidden in the Latent Space of the Network. StyleGAN Projection is a method to trace back StyleGAN2-generated images — so you can detect a photo as an AI-generated product (#DeepFake debunk). It still has some downsides: you have to know the concrete dataset of the particular image; every change in the image will make the process of projection unfeasible. Here is a successful projection: And this one will probably deprive you of sleep next night: Read more: StyleGAN2 Projection. A Reliable Method for Image Forensics? If you want to try a bigger diversity of motives, try out ArtBreeder, a powerful image generator by Joel Simon: artbreeder.com What’s that about: DeOldify model by Jason Antic allows organic colorization of photos and videos. You can bring back to vivid life old historical footage. Meanwhile, it’s implemented into MyHeritage.org. The method is powerful. It recognizes patterns and objects and applies the colors of trained visual databases on it. For example, these flowers from the 1950ies: It also works for videos. Watch here #DeOldified and upscaled version of the famous “Arrival of a Train at La Ciotat (The Lumière Brothers, 1896)” Advice: Upload your b&w footage to your Google Drive. So you can preserve privacy (if you trust Google Cloud, of course). Links: GitHub DeOldify for images DeOldify for videos (supports various video platforms) Read more: DeOldify: GAN based Image Colorization Re-animated History What’s this about: 3D Ken Burns Effect (developed by Simon Niklaus et al) allows generating animated 3D video footage of a single photo. Things to try out: In the Colab Notebook you will find the component autozoom.py. Try to finetune it with following parameters: objectTo = process_autozoom({'dblShift': 10.0,'dblZoom': 10000000000000000000000000000000000000000000000000000000,'objectFrom': objectFrom})numpyResult = process_kenburns({'dblSteps': numpy.linspace(0.0, 8.0, 400).tolist(),'objectFrom': objectFrom,'objectTo': objectTo,'boolInpaint': True}) This will exaggerate the camera movement — and you will fly through the whole scenery. Like in this example: Do some experiments with parameters, and you will experience your photos from a fully new perspective. The Notebook provides many useful functions, like serial image=>video transfer. Links: 3D Ken Burns Effect from a Single Image on ArXiv Colab Notebook (provided by Andi Bayo and improved by Manuel Romero) Read more: Very spatial! AI-based parallax 3D videos from photos. Re-animated History Beyond the Boundaries Watch my series dreAIms towardsdatascience.com What’s this about: First Order Motion Model by Aliaksandr Siarohin et al transfers facial movements from video footage to an image. Things to try out: Choose your video footage and source image! So many possibilities. Be fair, don’t #DeepFake. Links: Project page GitHub / Paper Colab Notebook This language Model, released by OpenAI during the year 2019 is trained on 40 GB text from various sources. There are several GPT-2 Colab notebooks, which work in a similar way: you enter the beginning of the sentence, and GPT-2 continues (or you ask questions to provided texts). The transformer-driven model works with “self-attention”, paying attention to text parts in specified proximity, which allows generating coherent stories, instead of gibberish chaos. I prefer two GPT-2 notebooks: “Train a GPT-2 Text-generating Model” by Max Woolf GPT-2 with Javascript Interface by gpt2ent Max Woolf’s Notebook allows: to generate various texts by GPT-2 to train your own texts (up to 355m Model) I did it in three languages: English (on “Alice in Wonderland”)German (on “Faust I” by Goethe)Russian (on early poetry by Pushkin) English (on “Alice in Wonderland”) German (on “Faust I” by Goethe) Russian (on early poetry by Pushkin) As you see, it works to some degree for all languages. Of course, GPT-2 is trained on English sources. For foreign languages, we should apply finetuning and other assets, but this proof of concept was convincing for me. With some interesting observations: The more I trained German on Faust, the closer to original the texts became. The reason is probably in a small dataset (just one single text). If you want to train on your texts, provide wider data amounts. Russian Texts are not really comprehensible, but you can nevertheless recognize the style and even form by Pushkin's poetry. And the coinages and neologisms are perfect, every literary Avant-gardist would be proud of such inventions. “GPT-2 with Javascript Interface”-Notebook allows: Text generation, not more, not less. But you can control the text length (which is a very relevant factor): With Temperature and top_k you can modify the randomness, repeatedness, and “weirdness” of the text. With Generate how much you can generate longer texts (I am using the value of 1000). Links: First OpenAI post about GPT2 GPT-2: 1.5B Release Max Woolf’s Blog Colab Notebook by Max Woolf GPT-2 with Javascript Interface You also can use the web-implementation of GPT-2 by Adam King: TalkToTransformer.com I asked this application about the meaning of life. The answer was very wise and mature. Read also: Lakrobuchi! (my Trilogy about GPT-2) AI can write music as well. In case of TensorFlow based Magenta, it uses Transformers, like in GPT-2, with self-attention, to allow the harmonic coherence and consistent composition. Here is a sample, being generated with Magenta: Things to try out: The notebook provides a lot of possibilities, for example for continuation, modulation, it allows .wav and .midi export. Magenta is a project by GoogleAI. A huge thing, it even includes hardware. And if you just want to listen, here is Magenta-Radio: magenta.github.io Links: Magenta by Google.ai Colab Notebook Magenta-Radio This is the mission of Colab Notebooks — to provide the possibility of work with ML/DL for the broad audience. To make AI accessible. To raise digital awareness and competence. And this is just the beginning of AI Spring. After years of snowy landscapes. And after frozen systems. In these Libraries you can find more Notebooks: github.com github.com Let’s experiment, explore, create! What are your favorite Colab Notebooks? Share them in comments!
[ { "code": null, "e": 581, "s": 171, "text": "It took at least two AI Winters to survive. The story is obvious: theoretically, Artificial Intelligence as a concept was already here. Neuronal Networks (as a concept: 1943 — McCulloch&Pitts /functional: 1965 — Ivakhnenko/Lapa), Machine learning (Samuel, 1959), Backpropagation (Werbos — 1975), just to name some of the key researches. Theoretically. But in practice, computational power was still like this:" }, { "code": null, "e": 758, "s": 581, "text": "AI research had still to wait for practical realization. Finally, in the 2000s, every owner of a personal computer became able to do experiments with Machine and Deep Learning." }, { "code": null, "e": 942, "s": 758, "text": "I remember 2016, as Google Deep Dream emerged (thank Alexander Mordvintsev). It took a good amount of time for me to set it up and to get it running. But the results were astonishing:" }, { "code": null, "e": 1056, "s": 942, "text": "I was in love with AI. And I wanted to try out more. Then I discovered Colab Notebooks. And they changed my life." }, { "code": null, "e": 1378, "s": 1056, "text": "Google Colab Notebooks enable the democratization of Data Science. They allow it everybody — AI researcher, artist, data scientist et al. — to enjoy the power of Machine and Deep Learning on every device (even on smartphones). Just run the cells, change the parameters, values, and sources, and enjoy the diversity of AI." }, { "code": null, "e": 1560, "s": 1378, "text": "I want to share with you some of my favorite Notebooks. Try them out! You can find many great essays here at Towards Data Science about backgrounds and working with Colab Notebooks." }, { "code": null, "e": 1579, "s": 1560, "text": "What’s this about?" }, { "code": null, "e": 1761, "s": 1579, "text": "DeepDream visualizes pattern recognition, interpretation and iterative generation by Neural Networks. By increasing this creative interpretation you can produce dream-alike imagery." }, { "code": null, "e": 1904, "s": 1761, "text": "Neural Networks act like our brain in the case of Pareidolia: it looks for familiar patterns, which derive from datasets they were trained on." }, { "code": null, "e": 2210, "s": 1904, "text": "The example above (a screen from my presentation on the AI Meetup Frankfurt, November 2019) demonstrates how our brain recognizes a face in the rock formations of Cydonia region on Mars. A user Nixtown transformed Da Vinci’s Mona Lisa by continuous DeepDream iterations — and AI recognizes weird patterns." }, { "code": null, "e": 2332, "s": 2210, "text": "Often our brain recognizes patterns or objects which aren’t there. But if our human perception does it, why AI shouldn’t?" }, { "code": null, "e": 2339, "s": 2332, "text": "Links:" }, { "code": null, "e": 2383, "s": 2339, "text": "Original Blog post by Alexander Mordvintsev" }, { "code": null, "e": 2390, "s": 2383, "text": "GitHub" }, { "code": null, "e": 2405, "s": 2390, "text": "Colab Notebook" }, { "code": null, "e": 2424, "s": 2405, "text": "Things to try out:" }, { "code": null, "e": 2579, "s": 2424, "text": "Try to generate different patterns and to resize images (octaves). Use more iterations. And don’t be afraid of insanity — the results could be unsettling." }, { "code": null, "e": 2589, "s": 2579, "text": "Fun fact:" }, { "code": null, "e": 2719, "s": 2589, "text": "Initially, DeepDream used to recognize in every pattern mostly dog faces. According to FastCompany, the Network was trained on..." }, { "code": null, "e": 2894, "s": 2719, "text": "a smaller subset of the ImageNet database released in 2012 for use in a contest... a subset which contained “fine-grained classification of 120 dog sub-classes (FastCompany)." }, { "code": null, "e": 2941, "s": 2894, "text": "Read more about my experiments with DeepDream." }, { "code": null, "e": 2960, "s": 2941, "text": "What’s this about?" }, { "code": null, "e": 3155, "s": 2960, "text": "BigGAN was one of the first prominent Generative Adversarial Networks. Trained on ImageNet at a now-humble 128x128 resolution this Network became a standard by its manifold generative abilities." }, { "code": null, "e": 3230, "s": 3155, "text": "In this notebook, you can generate samples from a long list of categories." }, { "code": null, "e": 3237, "s": 3230, "text": "Links:" }, { "code": null, "e": 3400, "s": 3237, "text": "BigGAN paper on arXiv (Andrew Brock, Jeff Donahue, and Karen Simonyan. Large Scale GAN Training for High Fidelity Natural Image Synthesis. arxiv:1809.11096, 2018)" }, { "code": null, "e": 3415, "s": 3400, "text": "Colab Notebook" }, { "code": null, "e": 3434, "s": 3415, "text": "Things to try out:" }, { "code": null, "e": 3800, "s": 3434, "text": "The same notebook allows you to create interpolation between images. This approach was — and is — mindblowing and innovative since only Surrealists and Abstract Artists were previously so courageous to combine incompatible things. Now you can do it with photorealistic results, for example, generate an interpolation between a Yorkshire terrier and a Space shuttle." }, { "code": null, "e": 3811, "s": 3800, "text": "Read also:" }, { "code": null, "e": 3839, "s": 3811, "text": "BigGAN as a creative engine" }, { "code": null, "e": 3878, "s": 3839, "text": "BigGAN and Metamorphosis of Everything" }, { "code": null, "e": 3897, "s": 3878, "text": "What’s this about:" }, { "code": null, "e": 4042, "s": 3897, "text": "In this experiment, the Deep Learned systems examine two source images — and transfer their style: not only colors but also shapes and patterns." }, { "code": null, "e": 4049, "s": 4042, "text": "Links:" }, { "code": null, "e": 4068, "s": 4049, "text": "Lucid (TensorFlow)" }, { "code": null, "e": 4083, "s": 4068, "text": "Colab Notebook" }, { "code": null, "e": 4094, "s": 4083, "text": "Read also:" }, { "code": null, "e": 4137, "s": 4094, "text": "Style Transfer (and you can do it as well)" }, { "code": null, "e": 4178, "s": 4137, "text": "AI&Creativity: Alien Elements with Style" }, { "code": null, "e": 4229, "s": 4178, "text": "There are many approaches to train AI on Artworks." }, { "code": null, "e": 4331, "s": 4229, "text": "One of them was provided via Reddit: StyleGAN trained on Artwork Dataset with 24k images from Kaggle." }, { "code": null, "e": 4490, "s": 4331, "text": "You get interesting results, it could even be possible to trace the original artworks the model was trained on. (New art game, everybody? “Visual Etymology”):" }, { "code": null, "e": 4619, "s": 4490, "text": "Another one is WikiART StyleGAN2 Conditional Model, provided by Peter Baylies (et al) and packed into a notebook by Doron Adler:" }, { "code": null, "e": 4722, "s": 4619, "text": "This model was trained on WikiART images. It allows even to choose between artists, genres and styles." }, { "code": null, "e": 4753, "s": 4722, "text": "And the images are impressive:" }, { "code": null, "e": 4772, "s": 4753, "text": "Things to try out:" }, { "code": null, "e": 5038, "s": 4772, "text": "Every new combination produces interesting artworks. Try to select artists from different epochs with an untypical style. Like Picasso & Renaissance or Shishkin & Pop Art. The results are sometimes unexpected and not always comprehensible, but that’s art after all." }, { "code": null, "e": 5045, "s": 5038, "text": "Links:" }, { "code": null, "e": 5094, "s": 5045, "text": "_C0D32_ Colab Notebook (trained on 24k Artworks)" }, { "code": null, "e": 5127, "s": 5094, "text": "WikiART StyleGAN2 Colab Notebook" }, { "code": null, "e": 5138, "s": 5127, "text": "Read also:" }, { "code": null, "e": 5164, "s": 5138, "text": "How to Train Your Artist." }, { "code": null, "e": 5194, "s": 5164, "text": "The Non-Treachery of Dataset." }, { "code": null, "e": 5213, "s": 5194, "text": "What’s this about?" }, { "code": null, "e": 5583, "s": 5213, "text": "This network, developed by NVidia, is at the moment (6th March 2020, 4:27 pm) the most advanced generative network for images. It was trained on High-Definition-Datasets (for example, Faces from Flickr-Faces-HQ). StyleGAN2 provides automatically learned, unsupervised separation of high-level attributes, stochastic variation and control of layers with visual features." }, { "code": null, "e": 5710, "s": 5583, "text": "There are various StyleGAN2-Notebooks (benefits of crowdsourced research), but my favorite is finetuned by Mikael Christensen." }, { "code": null, "e": 5717, "s": 5710, "text": "Links:" }, { "code": null, "e": 5757, "s": 5717, "text": "Paper: https://arxiv.org/abs/1812.04948" }, { "code": null, "e": 5793, "s": 5757, "text": "Video: https://youtu.be/kSLJriaOumA" }, { "code": null, "e": 5872, "s": 5793, "text": "Code: https://github.com/NVlabs/stylegan / https://github.com/NVlabs/stylegan2" }, { "code": null, "e": 5887, "s": 5872, "text": "Colab Notebook" }, { "code": null, "e": 5906, "s": 5887, "text": "Things to try out:" }, { "code": null, "e": 6004, "s": 5906, "text": "There are various default datasets by NVidia available within the notebook (mind the resolution):" }, { "code": null, "e": 6166, "s": 6004, "text": "Try out new Datasets. Train your own models or use those, provided by various artists and researchers, like Michael Friesen (follow his twitter for new updates)." }, { "code": null, "e": 6184, "s": 6166, "text": "Bacteria StyleGAN" }, { "code": null, "e": 6198, "s": 6184, "text": "Art-StyleGAN:" }, { "code": null, "e": 6218, "s": 6198, "text": "MC Escher-StyleGAN:" }, { "code": null, "e": 6252, "s": 6218, "text": "Produce videos of interpolations:" }, { "code": null, "e": 6715, "s": 6252, "text": "Try out StyleGAN2 projection. With the StyleGAN2 notebook you discover (or better: re-cover) images being hidden in the Latent Space of the Network. StyleGAN Projection is a method to trace back StyleGAN2-generated images — so you can detect a photo as an AI-generated product (#DeepFake debunk). It still has some downsides: you have to know the concrete dataset of the particular image; every change in the image will make the process of projection unfeasible." }, { "code": null, "e": 6748, "s": 6715, "text": "Here is a successful projection:" }, { "code": null, "e": 6808, "s": 6748, "text": "And this one will probably deprive you of sleep next night:" }, { "code": null, "e": 6819, "s": 6808, "text": "Read more:" }, { "code": null, "e": 6880, "s": 6819, "text": "StyleGAN2 Projection. A Reliable Method for Image Forensics?" }, { "code": null, "e": 6992, "s": 6880, "text": "If you want to try a bigger diversity of motives, try out ArtBreeder, a powerful image generator by Joel Simon:" }, { "code": null, "e": 7007, "s": 6992, "text": "artbreeder.com" }, { "code": null, "e": 7026, "s": 7007, "text": "What’s that about:" }, { "code": null, "e": 7212, "s": 7026, "text": "DeOldify model by Jason Antic allows organic colorization of photos and videos. You can bring back to vivid life old historical footage. Meanwhile, it’s implemented into MyHeritage.org." }, { "code": null, "e": 7329, "s": 7212, "text": "The method is powerful. It recognizes patterns and objects and applies the colors of trained visual databases on it." }, { "code": null, "e": 7374, "s": 7329, "text": "For example, these flowers from the 1950ies:" }, { "code": null, "e": 7522, "s": 7374, "text": "It also works for videos. Watch here #DeOldified and upscaled version of the famous “Arrival of a Train at La Ciotat (The Lumière Brothers, 1896)”" }, { "code": null, "e": 7530, "s": 7522, "text": "Advice:" }, { "code": null, "e": 7644, "s": 7530, "text": "Upload your b&w footage to your Google Drive. So you can preserve privacy (if you trust Google Cloud, of course)." }, { "code": null, "e": 7651, "s": 7644, "text": "Links:" }, { "code": null, "e": 7658, "s": 7651, "text": "GitHub" }, { "code": null, "e": 7678, "s": 7658, "text": "DeOldify for images" }, { "code": null, "e": 7733, "s": 7678, "text": "DeOldify for videos (supports various video platforms)" }, { "code": null, "e": 7744, "s": 7733, "text": "Read more:" }, { "code": null, "e": 7783, "s": 7744, "text": "DeOldify: GAN based Image Colorization" }, { "code": null, "e": 7803, "s": 7783, "text": "Re-animated History" }, { "code": null, "e": 7822, "s": 7803, "text": "What’s this about:" }, { "code": null, "e": 7940, "s": 7822, "text": "3D Ken Burns Effect (developed by Simon Niklaus et al) allows generating animated 3D video footage of a single photo." }, { "code": null, "e": 7959, "s": 7940, "text": "Things to try out:" }, { "code": null, "e": 8068, "s": 7959, "text": "In the Colab Notebook you will find the component autozoom.py. Try to finetune it with following parameters:" }, { "code": null, "e": 8359, "s": 8068, "text": "objectTo = process_autozoom({'dblShift': 10.0,'dblZoom': 10000000000000000000000000000000000000000000000000000000,'objectFrom': objectFrom})numpyResult = process_kenburns({'dblSteps': numpy.linspace(0.0, 8.0, 400).tolist(),'objectFrom': objectFrom,'objectTo': objectTo,'boolInpaint': True})" }, { "code": null, "e": 8468, "s": 8359, "text": "This will exaggerate the camera movement — and you will fly through the whole scenery. Like in this example:" }, { "code": null, "e": 8651, "s": 8468, "text": "Do some experiments with parameters, and you will experience your photos from a fully new perspective. The Notebook provides many useful functions, like serial image=>video transfer." }, { "code": null, "e": 8658, "s": 8651, "text": "Links:" }, { "code": null, "e": 8707, "s": 8658, "text": "3D Ken Burns Effect from a Single Image on ArXiv" }, { "code": null, "e": 8776, "s": 8707, "text": "Colab Notebook (provided by Andi Bayo and improved by Manuel Romero)" }, { "code": null, "e": 8787, "s": 8776, "text": "Read more:" }, { "code": null, "e": 8842, "s": 8787, "text": "Very spatial! AI-based parallax 3D videos from photos." }, { "code": null, "e": 8862, "s": 8842, "text": "Re-animated History" }, { "code": null, "e": 8884, "s": 8862, "text": "Beyond the Boundaries" }, { "code": null, "e": 8908, "s": 8884, "text": "Watch my series dreAIms" }, { "code": null, "e": 8931, "s": 8908, "text": "towardsdatascience.com" }, { "code": null, "e": 8950, "s": 8931, "text": "What’s this about:" }, { "code": null, "e": 9063, "s": 8950, "text": "First Order Motion Model by Aliaksandr Siarohin et al transfers facial movements from video footage to an image." }, { "code": null, "e": 9082, "s": 9063, "text": "Things to try out:" }, { "code": null, "e": 9175, "s": 9082, "text": "Choose your video footage and source image! So many possibilities. Be fair, don’t #DeepFake." }, { "code": null, "e": 9182, "s": 9175, "text": "Links:" }, { "code": null, "e": 9195, "s": 9182, "text": "Project page" }, { "code": null, "e": 9210, "s": 9195, "text": "GitHub / Paper" }, { "code": null, "e": 9225, "s": 9210, "text": "Colab Notebook" }, { "code": null, "e": 9689, "s": 9225, "text": "This language Model, released by OpenAI during the year 2019 is trained on 40 GB text from various sources. There are several GPT-2 Colab notebooks, which work in a similar way: you enter the beginning of the sentence, and GPT-2 continues (or you ask questions to provided texts). The transformer-driven model works with “self-attention”, paying attention to text parts in specified proximity, which allows generating coherent stories, instead of gibberish chaos." }, { "code": null, "e": 9719, "s": 9689, "text": "I prefer two GPT-2 notebooks:" }, { "code": null, "e": 9770, "s": 9719, "text": "“Train a GPT-2 Text-generating Model” by Max Woolf" }, { "code": null, "e": 9813, "s": 9770, "text": "GPT-2 with Javascript Interface by gpt2ent" }, { "code": null, "e": 9842, "s": 9813, "text": "Max Woolf’s Notebook allows:" }, { "code": null, "e": 9877, "s": 9842, "text": "to generate various texts by GPT-2" }, { "code": null, "e": 9920, "s": 9877, "text": "to train your own texts (up to 355m Model)" }, { "code": null, "e": 9949, "s": 9920, "text": "I did it in three languages:" }, { "code": null, "e": 10051, "s": 9949, "text": "English (on “Alice in Wonderland”)German (on “Faust I” by Goethe)Russian (on early poetry by Pushkin)" }, { "code": null, "e": 10086, "s": 10051, "text": "English (on “Alice in Wonderland”)" }, { "code": null, "e": 10118, "s": 10086, "text": "German (on “Faust I” by Goethe)" }, { "code": null, "e": 10155, "s": 10118, "text": "Russian (on early poetry by Pushkin)" }, { "code": null, "e": 10411, "s": 10155, "text": "As you see, it works to some degree for all languages. Of course, GPT-2 is trained on English sources. For foreign languages, we should apply finetuning and other assets, but this proof of concept was convincing for me. With some interesting observations:" }, { "code": null, "e": 10618, "s": 10411, "text": "The more I trained German on Faust, the closer to original the texts became. The reason is probably in a small dataset (just one single text). If you want to train on your texts, provide wider data amounts." }, { "code": null, "e": 10852, "s": 10618, "text": "Russian Texts are not really comprehensible, but you can nevertheless recognize the style and even form by Pushkin's poetry. And the coinages and neologisms are perfect, every literary Avant-gardist would be proud of such inventions." }, { "code": null, "e": 10903, "s": 10852, "text": "“GPT-2 with Javascript Interface”-Notebook allows:" }, { "code": null, "e": 11011, "s": 10903, "text": "Text generation, not more, not less. But you can control the text length (which is a very relevant factor):" }, { "code": null, "e": 11112, "s": 11011, "text": "With Temperature and top_k you can modify the randomness, repeatedness, and “weirdness” of the text." }, { "code": null, "e": 11197, "s": 11112, "text": "With Generate how much you can generate longer texts (I am using the value of 1000)." }, { "code": null, "e": 11204, "s": 11197, "text": "Links:" }, { "code": null, "e": 11233, "s": 11204, "text": "First OpenAI post about GPT2" }, { "code": null, "e": 11253, "s": 11233, "text": "GPT-2: 1.5B Release" }, { "code": null, "e": 11270, "s": 11253, "text": "Max Woolf’s Blog" }, { "code": null, "e": 11298, "s": 11270, "text": "Colab Notebook by Max Woolf" }, { "code": null, "e": 11330, "s": 11298, "text": "GPT-2 with Javascript Interface" }, { "code": null, "e": 11393, "s": 11330, "text": "You also can use the web-implementation of GPT-2 by Adam King:" }, { "code": null, "e": 11415, "s": 11393, "text": "TalkToTransformer.com" }, { "code": null, "e": 11504, "s": 11415, "text": "I asked this application about the meaning of life. The answer was very wise and mature." }, { "code": null, "e": 11515, "s": 11504, "text": "Read also:" }, { "code": null, "e": 11552, "s": 11515, "text": "Lakrobuchi! (my Trilogy about GPT-2)" }, { "code": null, "e": 11735, "s": 11552, "text": "AI can write music as well. In case of TensorFlow based Magenta, it uses Transformers, like in GPT-2, with self-attention, to allow the harmonic coherence and consistent composition." }, { "code": null, "e": 11783, "s": 11735, "text": "Here is a sample, being generated with Magenta:" }, { "code": null, "e": 11802, "s": 11783, "text": "Things to try out:" }, { "code": null, "e": 11998, "s": 11802, "text": "The notebook provides a lot of possibilities, for example for continuation, modulation, it allows .wav and .midi export. Magenta is a project by GoogleAI. A huge thing, it even includes hardware." }, { "code": null, "e": 12053, "s": 11998, "text": "And if you just want to listen, here is Magenta-Radio:" }, { "code": null, "e": 12071, "s": 12053, "text": "magenta.github.io" }, { "code": null, "e": 12078, "s": 12071, "text": "Links:" }, { "code": null, "e": 12099, "s": 12078, "text": "Magenta by Google.ai" }, { "code": null, "e": 12114, "s": 12099, "text": "Colab Notebook" }, { "code": null, "e": 12128, "s": 12114, "text": "Magenta-Radio" }, { "code": null, "e": 12305, "s": 12128, "text": "This is the mission of Colab Notebooks — to provide the possibility of work with ML/DL for the broad audience. To make AI accessible. To raise digital awareness and competence." }, { "code": null, "e": 12409, "s": 12305, "text": "And this is just the beginning of AI Spring. After years of snowy landscapes. And after frozen systems." }, { "code": null, "e": 12457, "s": 12409, "text": "In these Libraries you can find more Notebooks:" }, { "code": null, "e": 12468, "s": 12457, "text": "github.com" }, { "code": null, "e": 12479, "s": 12468, "text": "github.com" }, { "code": null, "e": 12514, "s": 12479, "text": "Let’s experiment, explore, create!" } ]
Making http request in React.js
In a typical web application, client makes a http request through browser and server sends html page in the response with data. But in a single page application (SPA), we have only one page and whenever client makes http request to server it generally responses with a json/xml formatted data. For making http request we have some of the below options − XmlHttpRequest Axios Windows fetch Axios is easy to work with react and handing requests. Lets install it first npm install –save axios Import it in the jsx file before using import Axios from ‘axios’; From the component lifecycle post, we observed that componentDidMount is the best place to make side effects like making http requests. Because componentDidMount executes only once in lifetime of a component. once http request gets completed we can update our state asynchronously and page will re-render with that updates. Axios uses promises to work it in asynchronous way. componentDidMount(){ Axios.get(‘url’).then((response)=>{console.log(response)}); } Then function simply contains a function having argument as response from promises. Inside the then we can use setState to update the data to state object of class. We can manipulate the data before updating the actual state in componentDidMount. Additionally we can send query parameters in axios. Based on some changes in state if we want o make another http request then we should use componentDidUpdate . But we have to make sure it does not result into infinite loop by adding conditional logic. Example using an id as an parameter , we can check if it not equal to previous id then we can make new http request here. Similar to get request we can do post request on button click. postdata=()=>{ const postObject={ //values } Axios.post(‘url’, postObject).then(response=>{ //process the response}); } Similar to get, we get the promise on complete of post request.there are other http methods which can be executed in same way. deleteData=()=>{ Axios.delete(‘url’).then(response=>{}); } We have catch method after the then method . Axios.get(‘url’).then(response=>{}).catch(error=>{ //we can update state to an error to show meaningful message on screen }); Sometimes we need to have a common process like adding authentication data or logging while making http request handling. In index.js file we can add interceptors which will be available for all the axios configs. Index.js Import axios from ‘axios’; Axios.interceptors.request.use(request=>{ //add logic here on the coming request return request; }); Make sure to return the request also in the interceptors. We can add erro logic as well as shown below Axios.interceptors.request.use(request=>{ //add logic here on the coming request return request; }, error=>{ //add error specific logic return Promise.reject(error); }); Similarly we can add interceptor for response Axios.interceptors. response.use(response=>{ //add logic here on the coming response return response; }, error=>{ //add error specific logic return Promise.reject(error); }); We can make other global configurations for axios like setting a bse url for all requests. In index.js file add below line Axios.defaults.baseURL=’your base url’;
[ { "code": null, "e": 1190, "s": 1062, "text": "In a typical web application, client makes a http request through browser and server sends html page in the response with data." }, { "code": null, "e": 1356, "s": 1190, "text": "But in a single page application (SPA), we have only one page and whenever client makes http request to server it generally responses with a json/xml formatted data." }, { "code": null, "e": 1416, "s": 1356, "text": "For making http request we have some of the below options −" }, { "code": null, "e": 1431, "s": 1416, "text": "XmlHttpRequest" }, { "code": null, "e": 1437, "s": 1431, "text": "Axios" }, { "code": null, "e": 1451, "s": 1437, "text": "Windows fetch" }, { "code": null, "e": 1506, "s": 1451, "text": "Axios is easy to work with react and handing requests." }, { "code": null, "e": 1528, "s": 1506, "text": "Lets install it first" }, { "code": null, "e": 1552, "s": 1528, "text": "npm install –save axios" }, { "code": null, "e": 1591, "s": 1552, "text": "Import it in the jsx file before using" }, { "code": null, "e": 1618, "s": 1591, "text": "import Axios from ‘axios’;" }, { "code": null, "e": 1942, "s": 1618, "text": "From the component lifecycle post, we observed that componentDidMount is the best place to make side effects like making http requests. Because componentDidMount executes only once in lifetime of a component. once http request gets completed we can update our state asynchronously and page will re-render with that updates." }, { "code": null, "e": 1994, "s": 1942, "text": "Axios uses promises to work it in asynchronous way." }, { "code": null, "e": 2080, "s": 1994, "text": "componentDidMount(){\n Axios.get(‘url’).then((response)=>{console.log(response)});\n}" }, { "code": null, "e": 2245, "s": 2080, "text": "Then function simply contains a function having argument as response from promises. Inside the then we can use setState to update the data to state object of class." }, { "code": null, "e": 2379, "s": 2245, "text": "We can manipulate the data before updating the actual state in componentDidMount. Additionally we can send query parameters in axios." }, { "code": null, "e": 2703, "s": 2379, "text": "Based on some changes in state if we want o make another http request then we should use componentDidUpdate . But we have to make sure it does not result into infinite loop by adding conditional logic. Example using an id as an parameter , we can check if it not equal to previous id then we can make new http request here." }, { "code": null, "e": 2766, "s": 2703, "text": "Similar to get request we can do post request on button click." }, { "code": null, "e": 2901, "s": 2766, "text": "postdata=()=>{\n const postObject={\n //values\n }\n Axios.post(‘url’, postObject).then(response=>{ //process the response});\n}" }, { "code": null, "e": 3028, "s": 2901, "text": "Similar to get, we get the promise on complete of post request.there are other http methods which can be executed in same way." }, { "code": null, "e": 3090, "s": 3028, "text": "deleteData=()=>{\n Axios.delete(‘url’).then(response=>{});\n}" }, { "code": null, "e": 3135, "s": 3090, "text": "We have catch method after the then method ." }, { "code": null, "e": 3264, "s": 3135, "text": "Axios.get(‘url’).then(response=>{}).catch(error=>{\n //we can update state to an error to show meaningful message on screen\n});" }, { "code": null, "e": 3386, "s": 3264, "text": "Sometimes we need to have a common process like adding authentication data or logging while making http request handling." }, { "code": null, "e": 3478, "s": 3386, "text": "In index.js file we can add interceptors which will be available for all the axios configs." }, { "code": null, "e": 3621, "s": 3478, "text": "Index.js\nImport axios from ‘axios’;\nAxios.interceptors.request.use(request=>{\n //add logic here on the coming request\n return request;\n});" }, { "code": null, "e": 3724, "s": 3621, "text": "Make sure to return the request also in the interceptors. We can add erro logic as well as shown below" }, { "code": null, "e": 3906, "s": 3724, "text": "Axios.interceptors.request.use(request=>{\n //add logic here on the coming request\n return request;\n}, error=>{\n //add error specific logic\n return Promise.reject(error);\n});" }, { "code": null, "e": 3952, "s": 3906, "text": "Similarly we can add interceptor for response" }, { "code": null, "e": 4139, "s": 3952, "text": "Axios.interceptors. response.use(response=>{\n //add logic here on the coming response\n return response;\n}, error=>{\n //add error specific logic\n return Promise.reject(error);\n});" }, { "code": null, "e": 4230, "s": 4139, "text": "We can make other global configurations for axios like setting a bse url for all requests." }, { "code": null, "e": 4262, "s": 4230, "text": "In index.js file add below line" }, { "code": null, "e": 4302, "s": 4262, "text": "Axios.defaults.baseURL=’your base url’;" } ]
Print all k-sum paths in a binary tree
07 Jul, 2022 A binary tree and a number k are given. Print every path in the tree with sum of the nodes in the path as k. A path can start from any node and end at any node and must be downward only, i.e. they need not be root node and leaf node; and negative numbers can also be there in the tree. Examples: Input : k = 5 Root of below binary tree: 1 / \ 3 -1 / \ / \ 2 1 4 5 / / \ \ 1 1 2 6 Output : 3 2 3 1 1 1 3 1 4 1 1 -1 4 1 -1 4 2 5 1 -1 5 Source : Amazon Interview Experience Set-323 Kindly note that this problem is significantly different from finding k-sum path from root to leaves. Here each node can be treated as root, hence the path can start and end at any node.The basic idea to solve the problem is to do a preorder traversal of the given tree. We also need a container (vector) to keep track of the path that led to that node. At each node we check if there are any path that sums to k, if any we print the path and proceed recursively to print each path. Below is the implementation of the same. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. C++ Java Python3 C# Javascript // C++ program to print all paths with sum k.#include <bits/stdc++.h>using namespace std; // utility function to print contents of// a vector from index i to it's endvoid printVector(const vector<int>& v, int i){ for (int j = i; j < v.size(); j++) cout << v[j] << " "; cout << endl;} // binary tree nodestruct Node { int data; Node *left, *right; Node(int x) { data = x; left = right = NULL; }}; // This function prints all paths that have sum kvoid printKPathUtil(Node* root, vector<int>& path, int k){ // empty node if (!root) return; // add current node to the path path.push_back(root->data); // check if there's any k sum path // in the left sub-tree. printKPathUtil(root->left, path, k); // check if there's any k sum path // in the right sub-tree. printKPathUtil(root->right, path, k); // check if there's any k sum path that // terminates at this node // Traverse the entire path as // there can be negative elements too int f = 0; for (int j = path.size() - 1; j >= 0; j--) { f += path[j]; // If path sum is k, print the path if (f == k) printVector(path, j); } // Remove the current element from the path path.pop_back();} // A wrapper over printKPathUtil()void printKPath(Node* root, int k){ vector<int> path; printKPathUtil(root, path, k);} // Driver codeint main(){ Node* root = new Node(1); root->left = new Node(3); root->left->left = new Node(2); root->left->right = new Node(1); root->left->right->left = new Node(1); root->right = new Node(-1); root->right->left = new Node(4); root->right->left->left = new Node(1); root->right->left->right = new Node(2); root->right->right = new Node(5); root->right->right->right = new Node(2); int k = 5; printKPath(root, k); return 0;} // Java program to print all paths with sum k.import java.util.*; class GFG { // utility function to print contents of // a vector from index i to it's end static void printVector(Vector<Integer> v, int i) { for (int j = i; j < v.size(); j++) System.out.print(v.get(j) + " "); System.out.println(); } // binary tree node static class Node { int data; Node left, right; Node(int x) { data = x; left = right = null; } }; static Vector<Integer> path = new Vector<Integer>(); // This function prints all paths that have sum k static void printKPathUtil(Node root, int k) { // empty node if (root == null) return; // add current node to the path path.add(root.data); // check if there's any k sum path // in the left sub-tree. printKPathUtil(root.left, k); // check if there's any k sum path // in the right sub-tree. printKPathUtil(root.right, k); // check if there's any k sum path that // terminates at this node // Traverse the entire path as // there can be negative elements too int f = 0; for (int j = path.size() - 1; j >= 0; j--) { f += path.get(j); // If path sum is k, print the path if (f == k) printVector(path, j); } // Remove the current element from the path path.remove(path.size() - 1); } // A wrapper over printKPathUtil() static void printKPath(Node root, int k) { path = new Vector<Integer>(); printKPathUtil(root, k); } // Driver code public static void main(String args[]) { Node root = new Node(1); root.left = new Node(3); root.left.left = new Node(2); root.left.right = new Node(1); root.left.right.left = new Node(1); root.right = new Node(-1); root.right.left = new Node(4); root.right.left.left = new Node(1); root.right.left.right = new Node(2); root.right.right = new Node(5); root.right.right.right = new Node(2); int k = 5; printKPath(root, k); }} // This code is contributed by Arnab Kundu # Python3 program to print all paths# with sum k # utility function to print contents of# a vector from index i to it's end def printVector(v, i): for j in range(i, len(v)): print(v[j], end=" ") print() # Binary Tree Node""" utility that allocates a newNode with the given key """ class newNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None # This function prints all paths# that have sum k def printKPathUtil(root, path, k): # empty node if (not root): return # add current node to the path path.append(root.data) # check if there's any k sum path # in the left sub-tree. printKPathUtil(root.left, path, k) # check if there's any k sum path # in the right sub-tree. printKPathUtil(root.right, path, k) # check if there's any k sum path that # terminates at this node # Traverse the entire path as # there can be negative elements too f = 0 for j in range(len(path) - 1, -1, -1): f += path[j] # If path sum is k, print the path if (f == k): printVector(path, j) # Remove the current element # from the path path.pop(-1) # A wrapper over printKPathUtil() def printKPath(root, k): path = [] printKPathUtil(root, path, k) # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(3) root.left.left = newNode(2) root.left.right = newNode(1) root.left.right.left = newNode(1) root.right = newNode(-1) root.right.left = newNode(4) root.right.left.left = newNode(1) root.right.left.right = newNode(2) root.right.right = newNode(5) root.right.right.right = newNode(2) k = 5 printKPath(root, k) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) // C# program to print all paths with sum k.using System;using System.Collections.Generic; class GFG { // utility function to print contents of // a vector from index i to it's end static void printList(List<int> v, int i) { for (int j = i; j < v.Count; j++) Console.Write(v[j] + " "); Console.WriteLine(); } // binary tree node public class Node { public int data; public Node left, right; public Node(int x) { data = x; left = right = null; } }; static List<int> path = new List<int>(); // This function prints all paths that have sum k static void printKPathUtil(Node root, int k) { // empty node if (root == null) return; // add current node to the path path.Add(root.data); // check if there's any k sum path // in the left sub-tree. printKPathUtil(root.left, k); // check if there's any k sum path // in the right sub-tree. printKPathUtil(root.right, k); // check if there's any k sum path that // terminates at this node // Traverse the entire path as // there can be negative elements too int f = 0; for (int j = path.Count - 1; j >= 0; j--) { f += path[j]; // If path sum is k, print the path if (f == k) printList(path, j); } // Remove the current element from the path path.RemoveAt(path.Count - 1); } // A wrapper over printKPathUtil() static void printKPath(Node root, int k) { path = new List<int>(); printKPathUtil(root, k); } // Driver code public static void Main(String[] args) { Node root = new Node(1); root.left = new Node(3); root.left.left = new Node(2); root.left.right = new Node(1); root.left.right.left = new Node(1); root.right = new Node(-1); root.right.left = new Node(4); root.right.left.left = new Node(1); root.right.left.right = new Node(2); root.right.right = new Node(5); root.right.right.right = new Node(2); int k = 5; printKPath(root, k); }} // This code is contributed by PrinciRaj1992 // Tree node class for Binary Tree// representationclass Node { constructor(data) { this.data = data; this.left = this.right = null; }} function printPathUtil(node, k, path_arr, all_path_arr) { if (node == null) { return; } let p1 = node.data.toString(); let p2 = ''; if (path_arr.length > 0) { p2 = path_arr + ',' + p1; } else { p2 = p1; } if (node.data == k) { all_path_arr.add(p1); } let sum = 0; let p2_arr = p2.split(','); for (let i = 0; i < p2_arr.length; i++) { sum = sum + Number(p2_arr[i]); } if (sum == k) { all_path_arr.add(p2); } printPathUtil(node.left, k, p1, all_path_arr) printPathUtil(node.left, k, p2, all_path_arr) printPathUtil(node.right, k, p1, all_path_arr) printPathUtil(node.right, k, p2, all_path_arr) } function printKPath(root, k) { let all_path_arr = new Set(); printPathUtil(root, k, '', all_path_arr); return all_path_arr;} function printPaths(paths) { for (let data of paths) { document.write(data.replaceAll(',', ' ')); document.write('<br>'); }} // Driver codelet root = new Node(1);root.left = new Node(3);root.left.left = new Node(2);root.left.right = new Node(1);root.left.right.left = new Node(1);root.right = new Node(-1);root.right.left = new Node(4);root.right.left.left = new Node(1);root.right.left.right = new Node(2);root.right.right = new Node(5);root.right.right.right = new Node(2); let k = 5; printPaths(printKPath(root, k)); // This code is contributed by gaurav2146 3 2 3 1 1 1 3 1 4 1 1 -1 4 1 -1 4 2 5 1 -1 5 Time Complexity: O(n*h*h) , as maximum size of path vector can be h Space Complexity: O(h) This article is contributed by Ashutosh Kumar If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. SHUBHAMSINGH10 andrew1234 nidhi_biet princiraj1992 nayanmanojgupta gaurav2146 hardikkoriintern Amazon Tree Amazon Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. AVL Tree | Set 1 (Insertion) Introduction to Data Structures What is Data Structure: Types, Classifications and Applications A program to check if a binary tree is BST or not Decision Tree Top 50 Tree Coding Problems for Interviews Segment Tree | Set 1 (Sum of given range) Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Sorted Array to Balanced BST
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 338, "s": 52, "text": "A binary tree and a number k are given. Print every path in the tree with sum of the nodes in the path as k. A path can start from any node and end at any node and must be downward only, i.e. they need not be root node and leaf node; and negative numbers can also be there in the tree." }, { "code": null, "e": 349, "s": 338, "text": "Examples: " }, { "code": null, "e": 667, "s": 349, "text": "Input : k = 5 \n Root of below binary tree:\n 1\n / \\\n 3 -1\n / \\ / \\\n 2 1 4 5 \n / / \\ \\ \n 1 1 2 6 \n \nOutput :\n3 2 \n3 1 1 \n1 3 1 \n4 1 \n1 -1 4 1 \n-1 4 2 \n5 \n1 -1 5 " }, { "code": null, "e": 712, "s": 667, "text": "Source : Amazon Interview Experience Set-323" }, { "code": null, "e": 1195, "s": 712, "text": "Kindly note that this problem is significantly different from finding k-sum path from root to leaves. Here each node can be treated as root, hence the path can start and end at any node.The basic idea to solve the problem is to do a preorder traversal of the given tree. We also need a container (vector) to keep track of the path that led to that node. At each node we check if there are any path that sums to k, if any we print the path and proceed recursively to print each path." }, { "code": null, "e": 1237, "s": 1195, "text": "Below is the implementation of the same. " }, { "code": null, "e": 1246, "s": 1237, "text": "Chapters" }, { "code": null, "e": 1273, "s": 1246, "text": "descriptions off, selected" }, { "code": null, "e": 1323, "s": 1273, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1346, "s": 1323, "text": "captions off, selected" }, { "code": null, "e": 1354, "s": 1346, "text": "English" }, { "code": null, "e": 1378, "s": 1354, "text": "This is a modal window." }, { "code": null, "e": 1447, "s": 1378, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1469, "s": 1447, "text": "End of dialog window." }, { "code": null, "e": 1473, "s": 1469, "text": "C++" }, { "code": null, "e": 1478, "s": 1473, "text": "Java" }, { "code": null, "e": 1486, "s": 1478, "text": "Python3" }, { "code": null, "e": 1489, "s": 1486, "text": "C#" }, { "code": null, "e": 1500, "s": 1489, "text": "Javascript" }, { "code": "// C++ program to print all paths with sum k.#include <bits/stdc++.h>using namespace std; // utility function to print contents of// a vector from index i to it's endvoid printVector(const vector<int>& v, int i){ for (int j = i; j < v.size(); j++) cout << v[j] << \" \"; cout << endl;} // binary tree nodestruct Node { int data; Node *left, *right; Node(int x) { data = x; left = right = NULL; }}; // This function prints all paths that have sum kvoid printKPathUtil(Node* root, vector<int>& path, int k){ // empty node if (!root) return; // add current node to the path path.push_back(root->data); // check if there's any k sum path // in the left sub-tree. printKPathUtil(root->left, path, k); // check if there's any k sum path // in the right sub-tree. printKPathUtil(root->right, path, k); // check if there's any k sum path that // terminates at this node // Traverse the entire path as // there can be negative elements too int f = 0; for (int j = path.size() - 1; j >= 0; j--) { f += path[j]; // If path sum is k, print the path if (f == k) printVector(path, j); } // Remove the current element from the path path.pop_back();} // A wrapper over printKPathUtil()void printKPath(Node* root, int k){ vector<int> path; printKPathUtil(root, path, k);} // Driver codeint main(){ Node* root = new Node(1); root->left = new Node(3); root->left->left = new Node(2); root->left->right = new Node(1); root->left->right->left = new Node(1); root->right = new Node(-1); root->right->left = new Node(4); root->right->left->left = new Node(1); root->right->left->right = new Node(2); root->right->right = new Node(5); root->right->right->right = new Node(2); int k = 5; printKPath(root, k); return 0;}", "e": 3400, "s": 1500, "text": null }, { "code": "// Java program to print all paths with sum k.import java.util.*; class GFG { // utility function to print contents of // a vector from index i to it's end static void printVector(Vector<Integer> v, int i) { for (int j = i; j < v.size(); j++) System.out.print(v.get(j) + \" \"); System.out.println(); } // binary tree node static class Node { int data; Node left, right; Node(int x) { data = x; left = right = null; } }; static Vector<Integer> path = new Vector<Integer>(); // This function prints all paths that have sum k static void printKPathUtil(Node root, int k) { // empty node if (root == null) return; // add current node to the path path.add(root.data); // check if there's any k sum path // in the left sub-tree. printKPathUtil(root.left, k); // check if there's any k sum path // in the right sub-tree. printKPathUtil(root.right, k); // check if there's any k sum path that // terminates at this node // Traverse the entire path as // there can be negative elements too int f = 0; for (int j = path.size() - 1; j >= 0; j--) { f += path.get(j); // If path sum is k, print the path if (f == k) printVector(path, j); } // Remove the current element from the path path.remove(path.size() - 1); } // A wrapper over printKPathUtil() static void printKPath(Node root, int k) { path = new Vector<Integer>(); printKPathUtil(root, k); } // Driver code public static void main(String args[]) { Node root = new Node(1); root.left = new Node(3); root.left.left = new Node(2); root.left.right = new Node(1); root.left.right.left = new Node(1); root.right = new Node(-1); root.right.left = new Node(4); root.right.left.left = new Node(1); root.right.left.right = new Node(2); root.right.right = new Node(5); root.right.right.right = new Node(2); int k = 5; printKPath(root, k); }} // This code is contributed by Arnab Kundu", "e": 5687, "s": 3400, "text": null }, { "code": "# Python3 program to print all paths# with sum k # utility function to print contents of# a vector from index i to it's end def printVector(v, i): for j in range(i, len(v)): print(v[j], end=\" \") print() # Binary Tree Node\"\"\" utility that allocates a newNode with the given key \"\"\" class newNode: # Construct to create a newNode def __init__(self, key): self.data = key self.left = None self.right = None # This function prints all paths# that have sum k def printKPathUtil(root, path, k): # empty node if (not root): return # add current node to the path path.append(root.data) # check if there's any k sum path # in the left sub-tree. printKPathUtil(root.left, path, k) # check if there's any k sum path # in the right sub-tree. printKPathUtil(root.right, path, k) # check if there's any k sum path that # terminates at this node # Traverse the entire path as # there can be negative elements too f = 0 for j in range(len(path) - 1, -1, -1): f += path[j] # If path sum is k, print the path if (f == k): printVector(path, j) # Remove the current element # from the path path.pop(-1) # A wrapper over printKPathUtil() def printKPath(root, k): path = [] printKPathUtil(root, path, k) # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(3) root.left.left = newNode(2) root.left.right = newNode(1) root.left.right.left = newNode(1) root.right = newNode(-1) root.right.left = newNode(4) root.right.left.left = newNode(1) root.right.left.right = newNode(2) root.right.right = newNode(5) root.right.right.right = newNode(2) k = 5 printKPath(root, k) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 7542, "s": 5687, "text": null }, { "code": "// C# program to print all paths with sum k.using System;using System.Collections.Generic; class GFG { // utility function to print contents of // a vector from index i to it's end static void printList(List<int> v, int i) { for (int j = i; j < v.Count; j++) Console.Write(v[j] + \" \"); Console.WriteLine(); } // binary tree node public class Node { public int data; public Node left, right; public Node(int x) { data = x; left = right = null; } }; static List<int> path = new List<int>(); // This function prints all paths that have sum k static void printKPathUtil(Node root, int k) { // empty node if (root == null) return; // add current node to the path path.Add(root.data); // check if there's any k sum path // in the left sub-tree. printKPathUtil(root.left, k); // check if there's any k sum path // in the right sub-tree. printKPathUtil(root.right, k); // check if there's any k sum path that // terminates at this node // Traverse the entire path as // there can be negative elements too int f = 0; for (int j = path.Count - 1; j >= 0; j--) { f += path[j]; // If path sum is k, print the path if (f == k) printList(path, j); } // Remove the current element from the path path.RemoveAt(path.Count - 1); } // A wrapper over printKPathUtil() static void printKPath(Node root, int k) { path = new List<int>(); printKPathUtil(root, k); } // Driver code public static void Main(String[] args) { Node root = new Node(1); root.left = new Node(3); root.left.left = new Node(2); root.left.right = new Node(1); root.left.right.left = new Node(1); root.right = new Node(-1); root.right.left = new Node(4); root.right.left.left = new Node(1); root.right.left.right = new Node(2); root.right.right = new Node(5); root.right.right.right = new Node(2); int k = 5; printKPath(root, k); }} // This code is contributed by PrinciRaj1992", "e": 9836, "s": 7542, "text": null }, { "code": "// Tree node class for Binary Tree// representationclass Node { constructor(data) { this.data = data; this.left = this.right = null; }} function printPathUtil(node, k, path_arr, all_path_arr) { if (node == null) { return; } let p1 = node.data.toString(); let p2 = ''; if (path_arr.length > 0) { p2 = path_arr + ',' + p1; } else { p2 = p1; } if (node.data == k) { all_path_arr.add(p1); } let sum = 0; let p2_arr = p2.split(','); for (let i = 0; i < p2_arr.length; i++) { sum = sum + Number(p2_arr[i]); } if (sum == k) { all_path_arr.add(p2); } printPathUtil(node.left, k, p1, all_path_arr) printPathUtil(node.left, k, p2, all_path_arr) printPathUtil(node.right, k, p1, all_path_arr) printPathUtil(node.right, k, p2, all_path_arr) } function printKPath(root, k) { let all_path_arr = new Set(); printPathUtil(root, k, '', all_path_arr); return all_path_arr;} function printPaths(paths) { for (let data of paths) { document.write(data.replaceAll(',', ' ')); document.write('<br>'); }} // Driver codelet root = new Node(1);root.left = new Node(3);root.left.left = new Node(2);root.left.right = new Node(1);root.left.right.left = new Node(1);root.right = new Node(-1);root.right.left = new Node(4);root.right.left.left = new Node(1);root.right.left.right = new Node(2);root.right.right = new Node(5);root.right.right.right = new Node(2); let k = 5; printPaths(printKPath(root, k)); // This code is contributed by gaurav2146", "e": 11433, "s": 9836, "text": null }, { "code": null, "e": 11486, "s": 11433, "text": "3 2 \n3 1 1 \n1 3 1 \n4 1 \n1 -1 4 1 \n-1 4 2 \n5 \n1 -1 5 " }, { "code": null, "e": 11578, "s": 11486, "text": "Time Complexity: O(n*h*h) , as maximum size of path vector can be h Space Complexity: O(h)" }, { "code": null, "e": 11876, "s": 11578, "text": "This article is contributed by Ashutosh Kumar If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 11891, "s": 11876, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 11902, "s": 11891, "text": "andrew1234" }, { "code": null, "e": 11913, "s": 11902, "text": "nidhi_biet" }, { "code": null, "e": 11927, "s": 11913, "text": "princiraj1992" }, { "code": null, "e": 11943, "s": 11927, "text": "nayanmanojgupta" }, { "code": null, "e": 11954, "s": 11943, "text": "gaurav2146" }, { "code": null, "e": 11971, "s": 11954, "text": "hardikkoriintern" }, { "code": null, "e": 11978, "s": 11971, "text": "Amazon" }, { "code": null, "e": 11983, "s": 11978, "text": "Tree" }, { "code": null, "e": 11990, "s": 11983, "text": "Amazon" }, { "code": null, "e": 11995, "s": 11990, "text": "Tree" }, { "code": null, "e": 12093, "s": 11995, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12122, "s": 12093, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 12154, "s": 12122, "text": "Introduction to Data Structures" }, { "code": null, "e": 12218, "s": 12154, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 12268, "s": 12218, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 12282, "s": 12268, "text": "Decision Tree" }, { "code": null, "e": 12325, "s": 12282, "text": "Top 50 Tree Coding Problems for Interviews" }, { "code": null, "e": 12367, "s": 12325, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 12437, "s": 12367, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 12520, "s": 12437, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" } ]
MySQL | Regular expressions (Regexp)
11 Oct, 2019 MySQL supports another type of pattern matching operation based on the regular expressions and the REGEXP operator. It provide a powerful and flexible pattern match that can help us implement power search utilities for our database systems.REGEXP is the operator used when performing regular expression pattern matches. RLIKE is the synonym.It also supports a number of metacharacters which allow more flexibility and control when performing pattern matching.The backslash is used as an escape character. It’s only considered in the pattern match if double backslashes have used.Not case sensitive. It provide a powerful and flexible pattern match that can help us implement power search utilities for our database systems. REGEXP is the operator used when performing regular expression pattern matches. RLIKE is the synonym. It also supports a number of metacharacters which allow more flexibility and control when performing pattern matching. The backslash is used as an escape character. It’s only considered in the pattern match if double backslashes have used. Not case sensitive. Examples with explanation : Match beginning of string(^):Gives all the names starting with ‘sa’.Example- sam,samarth.SELECT name FROM student_tbl WHERE name REGEXP '^sa'; SELECT name FROM student_tbl WHERE name REGEXP '^sa'; Match the end of a string($):Gives all the names ending with ‘on’.Example – norton,merton.SELECT name FROM student_tbl WHERE name REGEXP 'on$'; SELECT name FROM student_tbl WHERE name REGEXP 'on$'; Match zero or one instance of the strings preceding it(?):Gives all the titles containing ‘com’.Example – comedy , romantic comedy.SELECT title FROM movies_tbl WHERE title REGEXP 'com?'; SELECT title FROM movies_tbl WHERE title REGEXP 'com?'; matches any of the patterns p1, p2, or p3(p1|p2|p3):Gives all the names containing ‘be’ or ‘ae’.Example – Abel, Baer.SELECT name FROM student_tbl WHERE name REGEXP 'be|ae' ; SELECT name FROM student_tbl WHERE name REGEXP 'be|ae' ; Matches any character listed between the square brackets([abc]):Gives all the names containing ‘j’ or ‘z’.Example – Lorentz, Rajs.SELECT name FROM student_tbl WHERE name REGEXP '[jz]' ; SELECT name FROM student_tbl WHERE name REGEXP '[jz]' ; Matches any lower case letter between ‘a’ to ‘z’- ([a-z]) ([a-z] and (.)):Retrieve all names that contain a letter in the range of ‘b’ and ‘g’, followed by any character, followed by the letter ‘a’.Example – Tobias, sewall.Matches any single character(.)SELECT name FROM student_tbl WHERE name REGEXP '[b-g].[a]' ; Matches any single character(.) SELECT name FROM student_tbl WHERE name REGEXP '[b-g].[a]' ; Matches any character not listed between the square brackets.([^abc]):Gives all the names not containing ‘j’ or ‘z’. Example – nerton, sewall.SELECT name FROM student_tbl WHERE name REGEXP '[^jz]' ; SELECT name FROM student_tbl WHERE name REGEXP '[^jz]' ; Matches the end of words[[:>:]]:Gives all the titles ending with character “ack”. Example – Black.SELECT title FROM movies_tbl WHERE REGEXP 'ack[[:>:]]'; SELECT title FROM movies_tbl WHERE REGEXP 'ack[[:>:]]'; Matches the beginning of words[[:<:]]:Gives all the titles starting with character “for”. Example – Forgetting Sarah Marshal.SELECT title FROM movies_tbl WHERE title REGEXP '[[:<:]]for'; SELECT title FROM movies_tbl WHERE title REGEXP '[[:<:]]for'; Matches a character class[:class:]:i.e [:lower:]- lowercase character ,[:digit:] – digit characters etc.Gives all the titles containing alphabetic character only. Example – stranger things, Avengers.SELECT title FROM movies_tbl WHERE REGEXP '[:alpha:]' ; SELECT title FROM movies_tbl WHERE REGEXP '[:alpha:]' ; ShubhamMaurya3 TomClancy mysql DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Oct, 2019" }, { "code": null, "e": 170, "s": 54, "text": "MySQL supports another type of pattern matching operation based on the regular expressions and the REGEXP operator." }, { "code": null, "e": 653, "s": 170, "text": "It provide a powerful and flexible pattern match that can help us implement power search utilities for our database systems.REGEXP is the operator used when performing regular expression pattern matches. RLIKE is the synonym.It also supports a number of metacharacters which allow more flexibility and control when performing pattern matching.The backslash is used as an escape character. It’s only considered in the pattern match if double backslashes have used.Not case sensitive." }, { "code": null, "e": 778, "s": 653, "text": "It provide a powerful and flexible pattern match that can help us implement power search utilities for our database systems." }, { "code": null, "e": 880, "s": 778, "text": "REGEXP is the operator used when performing regular expression pattern matches. RLIKE is the synonym." }, { "code": null, "e": 999, "s": 880, "text": "It also supports a number of metacharacters which allow more flexibility and control when performing pattern matching." }, { "code": null, "e": 1120, "s": 999, "text": "The backslash is used as an escape character. It’s only considered in the pattern match if double backslashes have used." }, { "code": null, "e": 1140, "s": 1120, "text": "Not case sensitive." }, { "code": null, "e": 1168, "s": 1140, "text": "Examples with explanation :" }, { "code": null, "e": 1312, "s": 1168, "text": "Match beginning of string(^):Gives all the names starting with ‘sa’.Example- sam,samarth.SELECT name FROM student_tbl WHERE name REGEXP '^sa';\n" }, { "code": null, "e": 1367, "s": 1312, "text": "SELECT name FROM student_tbl WHERE name REGEXP '^sa';\n" }, { "code": null, "e": 1512, "s": 1367, "text": "Match the end of a string($):Gives all the names ending with ‘on’.Example – norton,merton.SELECT name FROM student_tbl WHERE name REGEXP 'on$';\n" }, { "code": null, "e": 1567, "s": 1512, "text": "SELECT name FROM student_tbl WHERE name REGEXP 'on$';\n" }, { "code": null, "e": 1756, "s": 1567, "text": "Match zero or one instance of the strings preceding it(?):Gives all the titles containing ‘com’.Example – comedy , romantic comedy.SELECT title FROM movies_tbl WHERE title REGEXP 'com?'; \n" }, { "code": null, "e": 1814, "s": 1756, "text": "SELECT title FROM movies_tbl WHERE title REGEXP 'com?'; \n" }, { "code": null, "e": 1989, "s": 1814, "text": "matches any of the patterns p1, p2, or p3(p1|p2|p3):Gives all the names containing ‘be’ or ‘ae’.Example – Abel, Baer.SELECT name FROM student_tbl WHERE name REGEXP 'be|ae' ;\n" }, { "code": null, "e": 2047, "s": 1989, "text": "SELECT name FROM student_tbl WHERE name REGEXP 'be|ae' ;\n" }, { "code": null, "e": 2234, "s": 2047, "text": "Matches any character listed between the square brackets([abc]):Gives all the names containing ‘j’ or ‘z’.Example – Lorentz, Rajs.SELECT name FROM student_tbl WHERE name REGEXP '[jz]' ;\n" }, { "code": null, "e": 2291, "s": 2234, "text": "SELECT name FROM student_tbl WHERE name REGEXP '[jz]' ;\n" }, { "code": null, "e": 2607, "s": 2291, "text": "Matches any lower case letter between ‘a’ to ‘z’- ([a-z]) ([a-z] and (.)):Retrieve all names that contain a letter in the range of ‘b’ and ‘g’, followed by any character, followed by the letter ‘a’.Example – Tobias, sewall.Matches any single character(.)SELECT name FROM student_tbl WHERE name REGEXP '[b-g].[a]' ;\n" }, { "code": null, "e": 2639, "s": 2607, "text": "Matches any single character(.)" }, { "code": null, "e": 2701, "s": 2639, "text": "SELECT name FROM student_tbl WHERE name REGEXP '[b-g].[a]' ;\n" }, { "code": null, "e": 2901, "s": 2701, "text": "Matches any character not listed between the square brackets.([^abc]):Gives all the names not containing ‘j’ or ‘z’. Example – nerton, sewall.SELECT name FROM student_tbl WHERE name REGEXP '[^jz]' ;\n" }, { "code": null, "e": 2959, "s": 2901, "text": "SELECT name FROM student_tbl WHERE name REGEXP '[^jz]' ;\n" }, { "code": null, "e": 3115, "s": 2959, "text": "Matches the end of words[[:>:]]:Gives all the titles ending with character “ack”. Example – Black.SELECT title FROM movies_tbl WHERE REGEXP 'ack[[:>:]]'; \n" }, { "code": null, "e": 3173, "s": 3115, "text": "SELECT title FROM movies_tbl WHERE REGEXP 'ack[[:>:]]'; \n" }, { "code": null, "e": 3362, "s": 3173, "text": "Matches the beginning of words[[:<:]]:Gives all the titles starting with character “for”. Example – Forgetting Sarah Marshal.SELECT title FROM movies_tbl WHERE title REGEXP '[[:<:]]for'; \n" }, { "code": null, "e": 3426, "s": 3362, "text": "SELECT title FROM movies_tbl WHERE title REGEXP '[[:<:]]for'; \n" }, { "code": null, "e": 3682, "s": 3426, "text": "Matches a character class[:class:]:i.e [:lower:]- lowercase character ,[:digit:] – digit characters etc.Gives all the titles containing alphabetic character only. Example – stranger things, Avengers.SELECT title FROM movies_tbl WHERE REGEXP '[:alpha:]' ;\n" }, { "code": null, "e": 3739, "s": 3682, "text": "SELECT title FROM movies_tbl WHERE REGEXP '[:alpha:]' ;\n" }, { "code": null, "e": 3754, "s": 3739, "text": "ShubhamMaurya3" }, { "code": null, "e": 3764, "s": 3754, "text": "TomClancy" }, { "code": null, "e": 3770, "s": 3764, "text": "mysql" }, { "code": null, "e": 3775, "s": 3770, "text": "DBMS" }, { "code": null, "e": 3779, "s": 3775, "text": "SQL" }, { "code": null, "e": 3784, "s": 3779, "text": "DBMS" }, { "code": null, "e": 3788, "s": 3784, "text": "SQL" } ]
ReactJS Fragments
04 Feb, 2021 We know that we make use of the render method inside a component whenever we want to render something to the screen. We may render a single element or multiple elements, though rendering multiple elements will require a ‘div’ tag around the content as the render method will only render a single root node inside it at a time. Example: Create a React app and edit the App.js file from the src folder as: Filename- App.js: javascript import React from "react"; // Simple rendering with divclass App extends React.Component { render() { return ( // Extraneous div element <div> <h2>Hello</h2> <p>How you doin'?</p> </div> ); }} export default App; Output: Reason to use Fragments: As we saw in the above code when we are trying to render more than one root element we have to put the entire content inside the ‘div’ tag which is not loved by many developers. So in React 16.2 version, Fragments were introduced, and we use them instead of the extraneous ‘div’ tag. Syntax: <React.Fragment> <h2>Child-1</h2> <p> Child-2</p> </React.Fragment> Example: Open App.js and replace the code with the below code. javascript import React from "react"; // Simple rendering with fragment syntaxclass App extends React.Component { render() { return ( <React.Fragment> <h2>Hello</h2> <p>How you doin'?</p> </React.Fragment> ); }} export default App; Output: Shorthand Fragment: The output of the first code and the code above is the same but the main reason for using is that it is a tiny bit faster when compared to the one with the ‘div’ tag inside it, as we didn’t create any DOM node. Also, it takes less memory. Another shorthand also exists for the above method in which we make use of ‘<>’ and ‘</>’ instead of the ‘React.Fragment’. Note: The shorthand syntax does not accept key attributes in that case you have to use the <React.Fragments> tag.Syntax: <> <h2>Child-1</h2> <p> Child-2</p> </> Example: Open App.js and replace the code with the below code. javascript import React from "react"; // Simple rendering with short syntaxclass App extends React.Component { render() { return ( <> <h2>Hello</h2> <p>How you doin'?</p> </> ); }} export default App; Output: shubhamyadav4 ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? Axios in React: A Guide for Beginners ReactJS setState() How to pass data from one component to other component in ReactJS ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Feb, 2021" }, { "code": null, "e": 381, "s": 52, "text": "We know that we make use of the render method inside a component whenever we want to render something to the screen. We may render a single element or multiple elements, though rendering multiple elements will require a ‘div’ tag around the content as the render method will only render a single root node inside it at a time. " }, { "code": null, "e": 458, "s": 381, "text": "Example: Create a React app and edit the App.js file from the src folder as:" }, { "code": null, "e": 476, "s": 458, "text": "Filename- App.js:" }, { "code": null, "e": 487, "s": 476, "text": "javascript" }, { "code": "import React from \"react\"; // Simple rendering with divclass App extends React.Component { render() { return ( // Extraneous div element <div> <h2>Hello</h2> <p>How you doin'?</p> </div> ); }} export default App;", "e": 741, "s": 487, "text": null }, { "code": null, "e": 749, "s": 741, "text": "Output:" }, { "code": null, "e": 1059, "s": 749, "text": "Reason to use Fragments: As we saw in the above code when we are trying to render more than one root element we have to put the entire content inside the ‘div’ tag which is not loved by many developers. So in React 16.2 version, Fragments were introduced, and we use them instead of the extraneous ‘div’ tag. " }, { "code": null, "e": 1067, "s": 1059, "text": "Syntax:" }, { "code": null, "e": 1157, "s": 1067, "text": "<React.Fragment> \n <h2>Child-1</h2> \n <p> Child-2</p> \n</React.Fragment> " }, { "code": null, "e": 1220, "s": 1157, "text": "Example: Open App.js and replace the code with the below code." }, { "code": null, "e": 1231, "s": 1220, "text": "javascript" }, { "code": "import React from \"react\"; // Simple rendering with fragment syntaxclass App extends React.Component { render() { return ( <React.Fragment> <h2>Hello</h2> <p>How you doin'?</p> </React.Fragment> ); }} export default App;", "e": 1488, "s": 1231, "text": null }, { "code": null, "e": 1496, "s": 1488, "text": "Output:" }, { "code": null, "e": 1879, "s": 1496, "text": "Shorthand Fragment: The output of the first code and the code above is the same but the main reason for using is that it is a tiny bit faster when compared to the one with the ‘div’ tag inside it, as we didn’t create any DOM node. Also, it takes less memory. Another shorthand also exists for the above method in which we make use of ‘<>’ and ‘</>’ instead of the ‘React.Fragment’. " }, { "code": null, "e": 2000, "s": 1879, "text": "Note: The shorthand syntax does not accept key attributes in that case you have to use the <React.Fragments> tag.Syntax:" }, { "code": null, "e": 2061, "s": 2000, "text": "<> \n <h2>Child-1</h2> \n <p> Child-2</p> \n</> " }, { "code": null, "e": 2124, "s": 2061, "text": "Example: Open App.js and replace the code with the below code." }, { "code": null, "e": 2135, "s": 2124, "text": "javascript" }, { "code": "import React from \"react\"; // Simple rendering with short syntaxclass App extends React.Component { render() { return ( <> <h2>Hello</h2> <p>How you doin'?</p> </> ); }} export default App;", "e": 2361, "s": 2135, "text": null }, { "code": null, "e": 2369, "s": 2361, "text": "Output:" }, { "code": null, "e": 2383, "s": 2369, "text": "shubhamyadav4" }, { "code": null, "e": 2391, "s": 2383, "text": "ReactJS" }, { "code": null, "e": 2408, "s": 2391, "text": "Web Technologies" }, { "code": null, "e": 2506, "s": 2408, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2549, "s": 2506, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2594, "s": 2549, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 2632, "s": 2594, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 2651, "s": 2632, "text": "ReactJS setState()" }, { "code": null, "e": 2719, "s": 2651, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 2752, "s": 2719, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2814, "s": 2752, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2875, "s": 2814, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2925, "s": 2875, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
p5.js | createButton() Function
11 Jul, 2019 The createButton() function is used to create a button element in the DOM (Document Object Model). The .size() function is used to set the size of button element. The .mousePressed() function is used to specify the behavior of mouse button when pressing it.Note: This function requires the p5.dom library. So add the following line in the head section of the index.html file. <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.dom.min.js"></script> Syntax: createButton( label, value ) Parameters: This function accepts two parameters as mentioned above and described below: label: This parameter holds the label displayed on the button. value: This parameter holds the value of the button. Return Value: It returns a pointer element holding the created node object. Note: This button element can be linked with various JavaScript events like mouse pressed, mouse clicked, mouse released, etc. Example: This example uses createButton() function to change the background color using the p5.js button element. // Create a variable for button objectvar color_button; // Create a function to change the background-colorfunction change_background() { // Pick a random number for r value r = random(255); // Pick a random number for g value g = random(255); // Pick a random number for b value b = random(255); // Set a random background-color background(r, g, b);} function setup() { // Create a canvas createCanvas(400, 400); // Set an initial background-color background(50); // Create the button color_button = createButton("Change Color"); // Position the button color_button.position(150, 200); // When the button is clicked change_background() // function is called color_button.mouseClicked(change_background);} Output: After clicking the button: After clicking the button again: Reference: https://p5js.org/reference/#/p5/createButton JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Roadmap to Learn JavaScript For Beginners Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jul, 2019" }, { "code": null, "e": 404, "s": 28, "text": "The createButton() function is used to create a button element in the DOM (Document Object Model). The .size() function is used to set the size of button element. The .mousePressed() function is used to specify the behavior of mouse button when pressing it.Note: This function requires the p5.dom library. So add the following line in the head section of the index.html file." }, { "code": "<script src=\"https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.dom.min.js\"></script>", "e": 501, "s": 404, "text": null }, { "code": null, "e": 509, "s": 501, "text": "Syntax:" }, { "code": null, "e": 538, "s": 509, "text": "createButton( label, value )" }, { "code": null, "e": 627, "s": 538, "text": "Parameters: This function accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 690, "s": 627, "text": "label: This parameter holds the label displayed on the button." }, { "code": null, "e": 743, "s": 690, "text": "value: This parameter holds the value of the button." }, { "code": null, "e": 819, "s": 743, "text": "Return Value: It returns a pointer element holding the created node object." }, { "code": null, "e": 946, "s": 819, "text": "Note: This button element can be linked with various JavaScript events like mouse pressed, mouse clicked, mouse released, etc." }, { "code": null, "e": 1060, "s": 946, "text": "Example: This example uses createButton() function to change the background color using the p5.js button element." }, { "code": "// Create a variable for button objectvar color_button; // Create a function to change the background-colorfunction change_background() { // Pick a random number for r value r = random(255); // Pick a random number for g value g = random(255); // Pick a random number for b value b = random(255); // Set a random background-color background(r, g, b);} function setup() { // Create a canvas createCanvas(400, 400); // Set an initial background-color background(50); // Create the button color_button = createButton(\"Change Color\"); // Position the button color_button.position(150, 200); // When the button is clicked change_background() // function is called color_button.mouseClicked(change_background);}", "e": 1881, "s": 1060, "text": null }, { "code": null, "e": 1889, "s": 1881, "text": "Output:" }, { "code": null, "e": 1916, "s": 1889, "text": "After clicking the button:" }, { "code": null, "e": 1949, "s": 1916, "text": "After clicking the button again:" }, { "code": null, "e": 2005, "s": 1949, "text": "Reference: https://p5js.org/reference/#/p5/createButton" }, { "code": null, "e": 2022, "s": 2005, "text": "JavaScript-p5.js" }, { "code": null, "e": 2033, "s": 2022, "text": "JavaScript" }, { "code": null, "e": 2050, "s": 2033, "text": "Web Technologies" }, { "code": null, "e": 2148, "s": 2050, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2209, "s": 2148, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2281, "s": 2209, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2321, "s": 2281, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2374, "s": 2321, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2416, "s": 2374, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2449, "s": 2416, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2511, "s": 2449, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2572, "s": 2511, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2622, "s": 2572, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Java Program to Get Today’s Date
06 Jun, 2021 Java is the most powerful programming language, by which we can perform many tasks and Java is an industry preferable language. So it is filled with a huge amount of features. Here we are going to discuss one of the best features of Java, which is how to get today’s or current date using Java. Methods: There are two ways to get today’s date as listed below: Using now() method of LocalDate classUsing java.sql.Date() function Using now() method of LocalDate class Using java.sql.Date() function Let us go through them one by one to get a fair understanding of them. Method 1: Using now() method of LocalDate class now() method of a LocalDate class used to obtain the current date from the system clock in the default time-zone. This method will return LocalDate based on the system clock with the default time-zone to obtain the current date. Example Java // Java Program to Get Today's Date// Using now() method of LocalDate class // Importing required classesimport java.text.SimpleDateFormat;import java.util.Date; // Main class// Day of Todaypublic class GFG { // Main Driver Method public static void main(String[] args) { // Printing Today's date by calling // java.time.LocalDate.now() function System.out.println(java.time.LocalDate.now()); }} 2021-05-31 Method 2: Using java.sql.Date() function Java // Java Program to Get Today's Date// Using java.sql.Date() function // Importing required classesimport java.text.SimpleDateFormat;import java.util.Date; // Main classpublic class GFG { // Main Driver Method public static void main(String[] args) { // Printing Today's date by calling // java.sql.Date() function long millis = System.currentTimeMillis(); java.sql.Date date = new java.sql.Date(millis); System.out.println(date); }} 2021-05-31 Java-Date-Time Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jun, 2021" }, { "code": null, "e": 323, "s": 28, "text": "Java is the most powerful programming language, by which we can perform many tasks and Java is an industry preferable language. So it is filled with a huge amount of features. Here we are going to discuss one of the best features of Java, which is how to get today’s or current date using Java." }, { "code": null, "e": 332, "s": 323, "text": "Methods:" }, { "code": null, "e": 388, "s": 332, "text": "There are two ways to get today’s date as listed below:" }, { "code": null, "e": 456, "s": 388, "text": "Using now() method of LocalDate classUsing java.sql.Date() function" }, { "code": null, "e": 494, "s": 456, "text": "Using now() method of LocalDate class" }, { "code": null, "e": 525, "s": 494, "text": "Using java.sql.Date() function" }, { "code": null, "e": 596, "s": 525, "text": "Let us go through them one by one to get a fair understanding of them." }, { "code": null, "e": 644, "s": 596, "text": "Method 1: Using now() method of LocalDate class" }, { "code": null, "e": 873, "s": 644, "text": "now() method of a LocalDate class used to obtain the current date from the system clock in the default time-zone. This method will return LocalDate based on the system clock with the default time-zone to obtain the current date." }, { "code": null, "e": 882, "s": 873, "text": "Example " }, { "code": null, "e": 887, "s": 882, "text": "Java" }, { "code": "// Java Program to Get Today's Date// Using now() method of LocalDate class // Importing required classesimport java.text.SimpleDateFormat;import java.util.Date; // Main class// Day of Todaypublic class GFG { // Main Driver Method public static void main(String[] args) { // Printing Today's date by calling // java.time.LocalDate.now() function System.out.println(java.time.LocalDate.now()); }}", "e": 1319, "s": 887, "text": null }, { "code": null, "e": 1331, "s": 1319, "text": "2021-05-31\n" }, { "code": null, "e": 1372, "s": 1331, "text": "Method 2: Using java.sql.Date() function" }, { "code": null, "e": 1377, "s": 1372, "text": "Java" }, { "code": "// Java Program to Get Today's Date// Using java.sql.Date() function // Importing required classesimport java.text.SimpleDateFormat;import java.util.Date; // Main classpublic class GFG { // Main Driver Method public static void main(String[] args) { // Printing Today's date by calling // java.sql.Date() function long millis = System.currentTimeMillis(); java.sql.Date date = new java.sql.Date(millis); System.out.println(date); }}", "e": 1863, "s": 1377, "text": null }, { "code": null, "e": 1875, "s": 1863, "text": "2021-05-31\n" }, { "code": null, "e": 1890, "s": 1875, "text": "Java-Date-Time" }, { "code": null, "e": 1897, "s": 1890, "text": "Picked" }, { "code": null, "e": 1902, "s": 1897, "text": "Java" }, { "code": null, "e": 1916, "s": 1902, "text": "Java Programs" }, { "code": null, "e": 1921, "s": 1916, "text": "Java" } ]
Page Rank Algorithm and Implementation
06 Nov, 2021 PageRank (PR) is an algorithm used by Google Search to rank websites in their search engine results. PageRank was named after Larry Page, one of the founders of Google. PageRank is a way of measuring the importance of website pages. According to Google: PageRank works by counting the number and quality of links to a page to determine a rough estimate of how important the website is. The underlying assumption is that more important websites are likely to receive more links from other websites. It is not the only algorithm used by Google to order search engine results, but it is the first algorithm that was used by the company, and it is the best-known.The above centrality measure is not implemented for multi-graphs. Algorithm The PageRank algorithm outputs a probability distribution used to represent the likelihood that a person randomly clicking on links will arrive at any particular page. PageRank can be calculated for collections of documents of any size. It is assumed in several research papers that the distribution is evenly divided among all documents in the collection at the beginning of the computational process. The PageRank computations require several passes, called “iterations”, through the collection to adjust approximate PageRank values to more closely reflect the theoretical true value. Simplified algorithm Assume a small universe of four web pages: A, B, C, and D. Links from a page to itself, or multiple outbound links from one single page to another single page, are ignored. PageRank is initialized to the same value for all pages. In the original form of PageRank, the sum of PageRank over all pages was the total number of pages on the web at that time, so each page in this example would have an initial value of 1. However, later versions of PageRank, and the remainder of this section, assume a probability distribution between 0 and 1. Hence the initial value for each page in this example is 0.25.The PageRank transferred from a given page to the targets of its outbound links upon the next iteration is divided equally among all outbound links.If the only links in the system were from pages B, C, and D to A, each link would transfer 0.25 PageRank to A upon the next iteration, for a total of 0.75.Suppose instead that page B had a link to pages C and A, page C had a link to page A, and page D had links to all three pages. Thus, upon the first iteration, page B would transfer half of its existing value, or 0.125, to page A and the other half, or 0.125, to page C. Page C would transfer all of its existing value, 0.25, to the only page it links to, A. Since D had three outbound links, it would transfer one-third of its existing value, or approximately 0.083, to A. At the completion of this iteration, page A will have a PageRank of approximately 0.458. In other words, the PageRank conferred by an outbound link is equal to the document’s own PageRank score divided by the number of outbound links L( ).In the general case, the PageRank value for any page u can be expressed as:,i.e. the PageRank value for a page u is dependent on the PageRank values for each page v contained in the set Bu (the set containing all pages linking to page u), divided by the number L(v) of links from page v. The algorithm involves a damping factor for the calculation of the PageRank. It is like the income tax which the govt extracts from one despite paying him itself. Following is the code for the calculation of the Page rank. Python def pagerank(G, alpha=0.85, personalization=None, max_iter=100, tol=1.0e-6, nstart=None, weight='weight', dangling=None): """Return the PageRank of the nodes in the graph. PageRank computes a ranking of the nodes in the graph G based on the structure of the incoming links. It was originally designed as an algorithm to rank web pages. Parameters ---------- G : graph A NetworkX graph. Undirected graphs will be converted to a directed graph with two directed edges for each undirected edge. alpha : float, optional Damping parameter for PageRank, default=0.85. personalization: dict, optional The "personalization vector" consisting of a dictionary with a key for every graph node and nonzero personalization value for each node. By default, a uniform distribution is used. max_iter : integer, optional Maximum number of iterations in power method eigenvalue solver. tol : float, optional Error tolerance used to check convergence in power method solver. nstart : dictionary, optional Starting value of PageRank iteration for each node. weight : key, optional Edge data key to use as weight. If None weights are set to 1. dangling: dict, optional The outedges to be assigned to any "dangling" nodes, i.e., nodes without any outedges. The dict key is the node the outedge points to and the dict value is the weight of that outedge. By default, dangling nodes are given outedges according to the personalization vector (uniform if not specified). This must be selected to result in an irreducible transition matrix (see notes under google_matrix). It may be common to have the dangling dict to be the same as the personalization dict. Returns ------- pagerank : dictionary Dictionary of nodes with PageRank as value Notes ----- The eigenvector calculation is done by the power iteration method and has no guarantee of convergence. The iteration will stop after max_iter iterations or an error tolerance of number_of_nodes(G)*tol has been reached. The PageRank algorithm was designed for directed graphs but this algorithm does not check if the input graph is directed and will execute on undirected graphs by converting each edge in the directed graph to two edges. """ if len(G) == 0: return {} if not G.is_directed(): D = G.to_directed() else: D = G # Create a copy in (right) stochastic form W = nx.stochastic_graph(D, weight=weight) N = W.number_of_nodes() # Choose fixed starting vector if not given if nstart is None: x = dict.fromkeys(W, 1.0 / N) else: # Normalized nstart vector s = float(sum(nstart.values())) x = dict((k, v / s) for k, v in nstart.items()) if personalization is None: # Assign uniform personalization vector if not given p = dict.fromkeys(W, 1.0 / N) else: missing = set(G) - set(personalization) if missing: raise NetworkXError('Personalization dictionary ' 'must have a value for every node. ' 'Missing nodes %s' % missing) s = float(sum(personalization.values())) p = dict((k, v / s) for k, v in personalization.items()) if dangling is None: # Use personalization vector if dangling vector not specified dangling_weights = p else: missing = set(G) - set(dangling) if missing: raise NetworkXError('Dangling node dictionary ' 'must have a value for every node. ' 'Missing nodes %s' % missing) s = float(sum(dangling.values())) dangling_weights = dict((k, v/s) for k, v in dangling.items()) dangling_nodes = [n for n in W if W.out_degree(n, weight=weight) == 0.0] # power iteration: make up to max_iter iterations for _ in range(max_iter): xlast = x x = dict.fromkeys(xlast.keys(), 0) danglesum = alpha * sum(xlast[n] for n in dangling_nodes) for n in x: # this matrix multiply looks odd because it is # doing a left multiply x^T=xlast^T*W for nbr in W[n]: x[nbr] += alpha * xlast[n] * W[n][nbr][weight] x[n] += danglesum * dangling_weights[n] + (1.0 - alpha) * p[n] # check convergence, l1 norm err = sum([abs(x[n] - xlast[n]) for n in x]) if err < N*tol: return x raise NetworkXError('pagerank: power iteration failed to converge ' 'in %d iterations.' % max_iter) The above code is the function that has been implemented in the networkx library. To implement the above in networkx, you will have to do the following: Python >>> import networkx as nx>>> G=nx.barabasi_albert_graph(60,41)>>> pr=nx.pagerank(G,0.4)>>> pr Below is the output, you would obtain on the IDLE after required installations. Python {0: 0.012774147598875784, 1: 0.013359655345577266, 2: 0.013157355731377924,3: 0.012142198569313045, 4: 0.013160014506830858, 5: 0.012973342862730735, 6: 0.012166706783753325, 7: 0.011985935451513014, 8: 0.012973502696061718,9: 0.013374146193499381, 10: 0.01296354505412387, 11: 0.013163220326063332, 12: 0.013368514624403237, 13: 0.013169335617283102, 14: 0.012752071800520563,15: 0.012951601882210992, 16: 0.013776032065400283, 17: 0.012356820581336275,18: 0.013151652554311779, 19: 0.012551059531065245, 20: 0.012583415756427995, 21: 0.013574117265891684, 22: 0.013167552803671937, 23: 0.013165528583400423, 24: 0.012584981049854336, 25: 0.013372989228254582, 26: 0.012569416076848989, 27: 0.013165322299539031, 28: 0.012954300960607157, 29: 0.012776091973397076, 30: 0.012771016515779594, 31: 0.012953404860268598, 32: 0.013364947854005844,33: 0.012370004022947507, 34: 0.012977539153099526, 35: 0.013170376268827118, 36: 0.012959579020039328, 37: 0.013155319659777197, 38: 0.013567147133137161, 39: 0.012171548109779459, 40: 0.01296692767996657, 41: 0.028089802328702826, 42: 0.027646981396639115, 43: 0.027300188191869485, 44: 0.02689771667021551, 45: 0.02650459107960327, 46: 0.025971186884778535, 47: 0.02585262571331937,48: 0.02565482923824489, 49: 0.024939722913691394, 50: 0.02458271197701402, 51: 0.024263128557312528, 52: 0.023505217517258568, 53: 0.023724311872578157, 54: 0.02312908947188023, 55: 0.02298716954828392, 56: 0.02270220663300396, 57: 0.022060403216132875, 58: 0.021932442105075004, 59: 0.021643288632623502} The above code has been run on IDLE(Python IDE of windows). You would need to download the networkx library before you run this code. The part inside the curly braces represents the output. It is almost similar to Ipython(for Ubuntu users). References https://en.wikipedia.org/wiki/PageRank http://networkx.readthedocs.io/en/networkx-1.10/index.html https://www.geeksforgeeks.org/ranking-google-search-works/ https://www.geeksforgeeks.org/google-search-works/ Thus, this way the centrality measure of Page Rank is calculated for the given graph. This way we have covered 2 centrality measures. I would like to write further on the various centrality measures used for the network analysis.This article is contributed by Jayant Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Anamitra Musib reenadevi98412200 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON Python | os.path.join() method
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Nov, 2021" }, { "code": null, "e": 306, "s": 52, "text": "PageRank (PR) is an algorithm used by Google Search to rank websites in their search engine results. PageRank was named after Larry Page, one of the founders of Google. PageRank is a way of measuring the importance of website pages. According to Google:" }, { "code": null, "e": 550, "s": 306, "text": "PageRank works by counting the number and quality of links to a page to determine a rough estimate of how important the website is. The underlying assumption is that more important websites are likely to receive more links from other websites." }, { "code": null, "e": 777, "s": 550, "text": "It is not the only algorithm used by Google to order search engine results, but it is the first algorithm that was used by the company, and it is the best-known.The above centrality measure is not implemented for multi-graphs." }, { "code": null, "e": 1374, "s": 777, "text": "Algorithm The PageRank algorithm outputs a probability distribution used to represent the likelihood that a person randomly clicking on links will arrive at any particular page. PageRank can be calculated for collections of documents of any size. It is assumed in several research papers that the distribution is evenly divided among all documents in the collection at the beginning of the computational process. The PageRank computations require several passes, called “iterations”, through the collection to adjust approximate PageRank values to more closely reflect the theoretical true value." }, { "code": null, "e": 3463, "s": 1374, "text": "Simplified algorithm Assume a small universe of four web pages: A, B, C, and D. Links from a page to itself, or multiple outbound links from one single page to another single page, are ignored. PageRank is initialized to the same value for all pages. In the original form of PageRank, the sum of PageRank over all pages was the total number of pages on the web at that time, so each page in this example would have an initial value of 1. However, later versions of PageRank, and the remainder of this section, assume a probability distribution between 0 and 1. Hence the initial value for each page in this example is 0.25.The PageRank transferred from a given page to the targets of its outbound links upon the next iteration is divided equally among all outbound links.If the only links in the system were from pages B, C, and D to A, each link would transfer 0.25 PageRank to A upon the next iteration, for a total of 0.75.Suppose instead that page B had a link to pages C and A, page C had a link to page A, and page D had links to all three pages. Thus, upon the first iteration, page B would transfer half of its existing value, or 0.125, to page A and the other half, or 0.125, to page C. Page C would transfer all of its existing value, 0.25, to the only page it links to, A. Since D had three outbound links, it would transfer one-third of its existing value, or approximately 0.083, to A. At the completion of this iteration, page A will have a PageRank of approximately 0.458. In other words, the PageRank conferred by an outbound link is equal to the document’s own PageRank score divided by the number of outbound links L( ).In the general case, the PageRank value for any page u can be expressed as:,i.e. the PageRank value for a page u is dependent on the PageRank values for each page v contained in the set Bu (the set containing all pages linking to page u), divided by the number L(v) of links from page v. The algorithm involves a damping factor for the calculation of the PageRank. It is like the income tax which the govt extracts from one despite paying him itself." }, { "code": null, "e": 3524, "s": 3463, "text": "Following is the code for the calculation of the Page rank. " }, { "code": null, "e": 3531, "s": 3524, "text": "Python" }, { "code": "def pagerank(G, alpha=0.85, personalization=None, max_iter=100, tol=1.0e-6, nstart=None, weight='weight', dangling=None): \"\"\"Return the PageRank of the nodes in the graph. PageRank computes a ranking of the nodes in the graph G based on the structure of the incoming links. It was originally designed as an algorithm to rank web pages. Parameters ---------- G : graph A NetworkX graph. Undirected graphs will be converted to a directed graph with two directed edges for each undirected edge. alpha : float, optional Damping parameter for PageRank, default=0.85. personalization: dict, optional The \"personalization vector\" consisting of a dictionary with a key for every graph node and nonzero personalization value for each node. By default, a uniform distribution is used. max_iter : integer, optional Maximum number of iterations in power method eigenvalue solver. tol : float, optional Error tolerance used to check convergence in power method solver. nstart : dictionary, optional Starting value of PageRank iteration for each node. weight : key, optional Edge data key to use as weight. If None weights are set to 1. dangling: dict, optional The outedges to be assigned to any \"dangling\" nodes, i.e., nodes without any outedges. The dict key is the node the outedge points to and the dict value is the weight of that outedge. By default, dangling nodes are given outedges according to the personalization vector (uniform if not specified). This must be selected to result in an irreducible transition matrix (see notes under google_matrix). It may be common to have the dangling dict to be the same as the personalization dict. Returns ------- pagerank : dictionary Dictionary of nodes with PageRank as value Notes ----- The eigenvector calculation is done by the power iteration method and has no guarantee of convergence. The iteration will stop after max_iter iterations or an error tolerance of number_of_nodes(G)*tol has been reached. The PageRank algorithm was designed for directed graphs but this algorithm does not check if the input graph is directed and will execute on undirected graphs by converting each edge in the directed graph to two edges. \"\"\" if len(G) == 0: return {} if not G.is_directed(): D = G.to_directed() else: D = G # Create a copy in (right) stochastic form W = nx.stochastic_graph(D, weight=weight) N = W.number_of_nodes() # Choose fixed starting vector if not given if nstart is None: x = dict.fromkeys(W, 1.0 / N) else: # Normalized nstart vector s = float(sum(nstart.values())) x = dict((k, v / s) for k, v in nstart.items()) if personalization is None: # Assign uniform personalization vector if not given p = dict.fromkeys(W, 1.0 / N) else: missing = set(G) - set(personalization) if missing: raise NetworkXError('Personalization dictionary ' 'must have a value for every node. ' 'Missing nodes %s' % missing) s = float(sum(personalization.values())) p = dict((k, v / s) for k, v in personalization.items()) if dangling is None: # Use personalization vector if dangling vector not specified dangling_weights = p else: missing = set(G) - set(dangling) if missing: raise NetworkXError('Dangling node dictionary ' 'must have a value for every node. ' 'Missing nodes %s' % missing) s = float(sum(dangling.values())) dangling_weights = dict((k, v/s) for k, v in dangling.items()) dangling_nodes = [n for n in W if W.out_degree(n, weight=weight) == 0.0] # power iteration: make up to max_iter iterations for _ in range(max_iter): xlast = x x = dict.fromkeys(xlast.keys(), 0) danglesum = alpha * sum(xlast[n] for n in dangling_nodes) for n in x: # this matrix multiply looks odd because it is # doing a left multiply x^T=xlast^T*W for nbr in W[n]: x[nbr] += alpha * xlast[n] * W[n][nbr][weight] x[n] += danglesum * dangling_weights[n] + (1.0 - alpha) * p[n] # check convergence, l1 norm err = sum([abs(x[n] - xlast[n]) for n in x]) if err < N*tol: return x raise NetworkXError('pagerank: power iteration failed to converge ' 'in %d iterations.' % max_iter)", "e": 8225, "s": 3531, "text": null }, { "code": null, "e": 8308, "s": 8225, "text": "The above code is the function that has been implemented in the networkx library. " }, { "code": null, "e": 8379, "s": 8308, "text": "To implement the above in networkx, you will have to do the following:" }, { "code": null, "e": 8386, "s": 8379, "text": "Python" }, { "code": ">>> import networkx as nx>>> G=nx.barabasi_albert_graph(60,41)>>> pr=nx.pagerank(G,0.4)>>> pr", "e": 8480, "s": 8386, "text": null }, { "code": null, "e": 8560, "s": 8480, "text": "Below is the output, you would obtain on the IDLE after required installations." }, { "code": null, "e": 8567, "s": 8560, "text": "Python" }, { "code": "{0: 0.012774147598875784, 1: 0.013359655345577266, 2: 0.013157355731377924,3: 0.012142198569313045, 4: 0.013160014506830858, 5: 0.012973342862730735, 6: 0.012166706783753325, 7: 0.011985935451513014, 8: 0.012973502696061718,9: 0.013374146193499381, 10: 0.01296354505412387, 11: 0.013163220326063332, 12: 0.013368514624403237, 13: 0.013169335617283102, 14: 0.012752071800520563,15: 0.012951601882210992, 16: 0.013776032065400283, 17: 0.012356820581336275,18: 0.013151652554311779, 19: 0.012551059531065245, 20: 0.012583415756427995, 21: 0.013574117265891684, 22: 0.013167552803671937, 23: 0.013165528583400423, 24: 0.012584981049854336, 25: 0.013372989228254582, 26: 0.012569416076848989, 27: 0.013165322299539031, 28: 0.012954300960607157, 29: 0.012776091973397076, 30: 0.012771016515779594, 31: 0.012953404860268598, 32: 0.013364947854005844,33: 0.012370004022947507, 34: 0.012977539153099526, 35: 0.013170376268827118, 36: 0.012959579020039328, 37: 0.013155319659777197, 38: 0.013567147133137161, 39: 0.012171548109779459, 40: 0.01296692767996657, 41: 0.028089802328702826, 42: 0.027646981396639115, 43: 0.027300188191869485, 44: 0.02689771667021551, 45: 0.02650459107960327, 46: 0.025971186884778535, 47: 0.02585262571331937,48: 0.02565482923824489, 49: 0.024939722913691394, 50: 0.02458271197701402, 51: 0.024263128557312528, 52: 0.023505217517258568, 53: 0.023724311872578157, 54: 0.02312908947188023, 55: 0.02298716954828392, 56: 0.02270220663300396, 57: 0.022060403216132875, 58: 0.021932442105075004, 59: 0.021643288632623502}", "e": 10102, "s": 8567, "text": null }, { "code": null, "e": 10343, "s": 10102, "text": "The above code has been run on IDLE(Python IDE of windows). You would need to download the networkx library before you run this code. The part inside the curly braces represents the output. It is almost similar to Ipython(for Ubuntu users)." }, { "code": null, "e": 10355, "s": 10343, "text": "References " }, { "code": null, "e": 10394, "s": 10355, "text": "https://en.wikipedia.org/wiki/PageRank" }, { "code": null, "e": 10453, "s": 10394, "text": "http://networkx.readthedocs.io/en/networkx-1.10/index.html" }, { "code": null, "e": 10512, "s": 10453, "text": "https://www.geeksforgeeks.org/ranking-google-search-works/" }, { "code": null, "e": 10563, "s": 10512, "text": "https://www.geeksforgeeks.org/google-search-works/" }, { "code": null, "e": 11213, "s": 10563, "text": "Thus, this way the centrality measure of Page Rank is calculated for the given graph. This way we have covered 2 centrality measures. I would like to write further on the various centrality measures used for the network analysis.This article is contributed by Jayant Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 11228, "s": 11213, "text": "Anamitra Musib" }, { "code": null, "e": 11246, "s": 11228, "text": "reenadevi98412200" }, { "code": null, "e": 11253, "s": 11246, "text": "Python" }, { "code": null, "e": 11351, "s": 11253, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11393, "s": 11351, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 11415, "s": 11393, "text": "Enumerate() in Python" }, { "code": null, "e": 11441, "s": 11415, "text": "Python String | replace()" }, { "code": null, "e": 11473, "s": 11441, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 11502, "s": 11473, "text": "*args and **kwargs in Python" }, { "code": null, "e": 11529, "s": 11502, "text": "Python Classes and Objects" }, { "code": null, "e": 11550, "s": 11529, "text": "Python OOPs Concepts" }, { "code": null, "e": 11586, "s": 11550, "text": "Convert integer to string in Python" }, { "code": null, "e": 11609, "s": 11586, "text": "Introduction To PYTHON" } ]
How to read/write data from/to .properties file in Java?
The .properties is an extension in java which is used to store configurable application. It is represented by the Properties class in Java, you can store a properties file and read from it using the methods of this class. This class inherits the HashTable class. Creating a .properties file − To create a properties file − Instantiate the Properties class. Instantiate the Properties class. Populate the created Properties object using the put() method. Populate the created Properties object using the put() method. Instantiate the FileOutputStream class by passing the path to store the file, as a parameter. Instantiate the FileOutputStream class by passing the path to store the file, as a parameter. The Following Java program creates a properties file in the path D:/ExampleDirectory/ Live Demo import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; public class CreatingPropertiesFile { public static void main(String args[]) throws IOException { //Instantiating the properties file Properties props = new Properties(); //Populating the properties file props.put("Device_name", "OnePlus7"); props.put("Android_version", "9"); props.put("Model", "GM1901"); props.put("CPU", "Snapdragon855"); //Instantiating the FileInputStream for output file String path = "D:\\ExampleDirectory\\myFile.properties"; FileOutputStream outputStrem = new FileOutputStream(path); //Storing the properties file props.store(outputStrem, "This is a sample properties file"); System.out.println("Properties file created......"); } } Properties file created...... If you observe the output file you can see the created contents as − You can store the properties file in XML format using the stored XML() method. Live Demo import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; public class CreatingPropertiesFile { public static void main(String args[]) throws IOException { //Instantiating the properties file Properties props = new Properties(); //Populating the properties file props.put("Device_name", "OnePlus7"); props.put("Android_version", "9"); props.put("Model", "GM1901"); props.put("CPU", "Snapdragon855"); //Instantiating the FileInputStream for output file String outputPath = "D:\\ExampleDirectory\\myFile.xml"; FileOutputStream outputStrem = new FileOutputStream(outputPath); //Storing the properties file in XML format props.storeToXML(outputStrem, "This is a sample properties file"); System.out.println("Properties file created......"); } } Properties file created......
[ { "code": null, "e": 1450, "s": 1187, "text": "The .properties is an extension in java which is used to store configurable application. It is represented by the Properties class in Java, you can store a properties file and read from it using the methods of this class. This class inherits the HashTable class." }, { "code": null, "e": 1480, "s": 1450, "text": "Creating a .properties file −" }, { "code": null, "e": 1510, "s": 1480, "text": "To create a properties file −" }, { "code": null, "e": 1544, "s": 1510, "text": "Instantiate the Properties class." }, { "code": null, "e": 1578, "s": 1544, "text": "Instantiate the Properties class." }, { "code": null, "e": 1641, "s": 1578, "text": "Populate the created Properties object using the put() method." }, { "code": null, "e": 1704, "s": 1641, "text": "Populate the created Properties object using the put() method." }, { "code": null, "e": 1798, "s": 1704, "text": "Instantiate the FileOutputStream class by passing the path to store the file, as a parameter." }, { "code": null, "e": 1892, "s": 1798, "text": "Instantiate the FileOutputStream class by passing the path to store the file, as a parameter." }, { "code": null, "e": 1978, "s": 1892, "text": "The Following Java program creates a properties file in the path D:/ExampleDirectory/" }, { "code": null, "e": 1989, "s": 1978, "text": " Live Demo" }, { "code": null, "e": 2822, "s": 1989, "text": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.util.Properties;\npublic class CreatingPropertiesFile {\n public static void main(String args[]) throws IOException {\n //Instantiating the properties file\n Properties props = new Properties();\n //Populating the properties file\n props.put(\"Device_name\", \"OnePlus7\");\n props.put(\"Android_version\", \"9\");\n props.put(\"Model\", \"GM1901\");\n props.put(\"CPU\", \"Snapdragon855\");\n //Instantiating the FileInputStream for output file\n String path = \"D:\\\\ExampleDirectory\\\\myFile.properties\";\n FileOutputStream outputStrem = new FileOutputStream(path);\n //Storing the properties file\n props.store(outputStrem, \"This is a sample properties file\");\n System.out.println(\"Properties file created......\");\n }\n}" }, { "code": null, "e": 2852, "s": 2822, "text": "Properties file created......" }, { "code": null, "e": 2921, "s": 2852, "text": "If you observe the output file you can see the created contents as −" }, { "code": null, "e": 3000, "s": 2921, "text": "You can store the properties file in XML format using the stored XML() method." }, { "code": null, "e": 3011, "s": 3000, "text": " Live Demo" }, { "code": null, "e": 3868, "s": 3011, "text": "import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.util.Properties;\npublic class CreatingPropertiesFile {\n public static void main(String args[]) throws IOException {\n //Instantiating the properties file\n Properties props = new Properties();\n //Populating the properties file\n props.put(\"Device_name\", \"OnePlus7\");\n props.put(\"Android_version\", \"9\");\n props.put(\"Model\", \"GM1901\");\n props.put(\"CPU\", \"Snapdragon855\");\n //Instantiating the FileInputStream for output file\n String outputPath = \"D:\\\\ExampleDirectory\\\\myFile.xml\";\n FileOutputStream outputStrem = new FileOutputStream(outputPath);\n //Storing the properties file in XML format\n props.storeToXML(outputStrem, \"This is a sample properties file\");\n System.out.println(\"Properties file created......\");\n }\n}" }, { "code": null, "e": 3898, "s": 3868, "text": "Properties file created......" } ]
ReactJS – bind() method
In this article, we are going to see how to pass arguments to a function in a React application React has a predefined bind() method which we can use to pass the arguments to a function in the class based components. this.func.bind(this,[args...]) It accepts two parameters, this keyword and the arguments. 'this' keyword is used to pass the reference to that function while the second parameter is passed as arguments to the function. In this example, we will build a React application that passes the arguments to a function when a button is clicked. App.jsx import React from 'react'; class App extends React.Component { constructor(){ super(); this.state = { name: 'Rahul Bansal', email: null, }; } fetch = (email) => { this.setState({ email: email }); }; render() { return ( <div> <h1>Name: {this.state.name}</h1> <h1>{this.state.email ? 'Email: ${this.state.email}' : null}</h1> <button onClick={this.fetch.bind(this, 'qwerty@gmail.com')}> Fetch Email </button> </div> ); } } export default App;
[ { "code": null, "e": 1283, "s": 1187, "text": "In this article, we are going to see how to pass arguments to a function in a React application" }, { "code": null, "e": 1404, "s": 1283, "text": "React has a predefined bind() method which we can use to pass the arguments to a function in the class based components." }, { "code": null, "e": 1435, "s": 1404, "text": "this.func.bind(this,[args...])" }, { "code": null, "e": 1623, "s": 1435, "text": "It accepts two parameters, this keyword and the arguments. 'this' keyword is used to pass the reference to that function while the second parameter is passed as arguments to the function." }, { "code": null, "e": 1740, "s": 1623, "text": "In this example, we will build a React application that passes the arguments to a function when a button is clicked." }, { "code": null, "e": 1748, "s": 1740, "text": "App.jsx" }, { "code": null, "e": 2344, "s": 1748, "text": "import React from 'react';\n\nclass App extends React.Component {\n constructor(){\n super();\n this.state = {\n name: 'Rahul Bansal',\n email: null,\n };\n }\n\n fetch = (email) => {\n this.setState({ email: email });\n };\n render() {\n return (\n <div>\n <h1>Name: {this.state.name}</h1>\n <h1>{this.state.email ? 'Email: ${this.state.email}' : null}</h1>\n <button onClick={this.fetch.bind(this, 'qwerty@gmail.com')}>\n Fetch Email\n </button>\n </div>\n );\n }\n}\nexport default App;" } ]
open Keyword in Kotlin - GeeksforGeeks
10 Nov, 2021 Keywords are some predefined or specific reserved words in programming languages each of which has a specific feature associated with it. Almost all of the words which help us use the functionality of the programming languages are included in the list of keywords. So you can imagine that the list of keywords is not going to be a small one, and the “open” keyword is also one of them, so this article is also based on open keyword. Now let’s try to understand the “open” keyword in kotlin. As we all know that kotlin is a modern and highly recommended language for android app development. because it really makes android app development easier a lot, and we all should know that it is also the modification of the java programming language, so why not we understand the “open” keyword by comparison with java. i.e what we can use instead of “open” keyword in java. So basically java has a keyword named “final“. but it works exactly opposite to the “open” keyword, so let’s quickly understand the “final” keyword. I hope you all know about it, but don’t worry if don’t. the “final” keyword is used in java mostly with classes and methods (functions) as: final method : A method that cannot be overridden. final class : A class that cannot be extended. But, Kotlin has a special feature i.e. classes and methods are not open for extension by default, which means they are by default final class or final function. It means Open classes and methods in Kotlin are equivalent to the opposite of final in Java, an open method is overridable and an open class is extendable in Kotlin. Note: your class is implicitly declared as open since it is abstract, hence you cannot create an instance of that class directly. Example 1: Extension of class Now we know that kotlin has everything final by default. So, if we try to extend the class then the compiler will show an error. Kotlin class Geeksclass student:Geeks() error: This type is final, so it cannot be inherited To make a class open for extension we should use “open” keyword as: Kotlin // mark the class with "open"open class Geeksclass student:Geeks() Example 2: Overriding of function(methods) Same as classes, functions(Methods) can’t be overridable in their default configuration, even if the class containing function is open Kotlin open class geeks{ fun student():string ="alok"}class batch: geeks() { override fun student():string = "ashish"} this code will show an error error: 'student' in 'geeks' is final and cannot be overridden To override a method in subclasses, we should use “open” keyword as: Kotlin open class geeks{ // mark the function with open open fun student():string ="alok"}class batch: geeks() { override fun student():string = "ashish"} Now our code is correct. Picked Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Retrofit with Kotlin Coroutine in Android How to Build a Weather App in Android? How to Get Current Location in Android? ImageView in Android with Example ScrollView in Android Kotlin Coroutines on Android Kotlin extension function Notifications in Android with Example How to Send Data From Activity to Fragment in Android? Suspend Function In Kotlin Coroutines
[ { "code": null, "e": 24544, "s": 24516, "text": "\n10 Nov, 2021" }, { "code": null, "e": 25616, "s": 24544, "text": "Keywords are some predefined or specific reserved words in programming languages each of which has a specific feature associated with it. Almost all of the words which help us use the functionality of the programming languages are included in the list of keywords. So you can imagine that the list of keywords is not going to be a small one, and the “open” keyword is also one of them, so this article is also based on open keyword. Now let’s try to understand the “open” keyword in kotlin. As we all know that kotlin is a modern and highly recommended language for android app development. because it really makes android app development easier a lot, and we all should know that it is also the modification of the java programming language, so why not we understand the “open” keyword by comparison with java. i.e what we can use instead of “open” keyword in java. So basically java has a keyword named “final“. but it works exactly opposite to the “open” keyword, so let’s quickly understand the “final” keyword. I hope you all know about it, but don’t worry if don’t." }, { "code": null, "e": 25700, "s": 25616, "text": "the “final” keyword is used in java mostly with classes and methods (functions) as:" }, { "code": null, "e": 25751, "s": 25700, "text": "final method : A method that cannot be overridden." }, { "code": null, "e": 25798, "s": 25751, "text": "final class : A class that cannot be extended." }, { "code": null, "e": 26125, "s": 25798, "text": "But, Kotlin has a special feature i.e. classes and methods are not open for extension by default, which means they are by default final class or final function. It means Open classes and methods in Kotlin are equivalent to the opposite of final in Java, an open method is overridable and an open class is extendable in Kotlin." }, { "code": null, "e": 26255, "s": 26125, "text": "Note: your class is implicitly declared as open since it is abstract, hence you cannot create an instance of that class directly." }, { "code": null, "e": 26286, "s": 26255, "text": "Example 1: Extension of class" }, { "code": null, "e": 26415, "s": 26286, "text": "Now we know that kotlin has everything final by default. So, if we try to extend the class then the compiler will show an error." }, { "code": null, "e": 26422, "s": 26415, "text": "Kotlin" }, { "code": "class Geeksclass student:Geeks()", "e": 26455, "s": 26422, "text": null }, { "code": null, "e": 26508, "s": 26455, "text": "error: This type is final, so it cannot be inherited" }, { "code": null, "e": 26576, "s": 26508, "text": "To make a class open for extension we should use “open” keyword as:" }, { "code": null, "e": 26583, "s": 26576, "text": "Kotlin" }, { "code": "// mark the class with \"open\"open class Geeksclass student:Geeks()", "e": 26650, "s": 26583, "text": null }, { "code": null, "e": 26693, "s": 26650, "text": "Example 2: Overriding of function(methods)" }, { "code": null, "e": 26828, "s": 26693, "text": "Same as classes, functions(Methods) can’t be overridable in their default configuration, even if the class containing function is open" }, { "code": null, "e": 26835, "s": 26828, "text": "Kotlin" }, { "code": "open class geeks{ fun student():string =\"alok\"}class batch: geeks() { override fun student():string = \"ashish\"}", "e": 26949, "s": 26835, "text": null }, { "code": null, "e": 26978, "s": 26949, "text": "this code will show an error" }, { "code": null, "e": 27040, "s": 26978, "text": "error: 'student' in 'geeks' is final and cannot be overridden" }, { "code": null, "e": 27109, "s": 27040, "text": "To override a method in subclasses, we should use “open” keyword as:" }, { "code": null, "e": 27116, "s": 27109, "text": "Kotlin" }, { "code": "open class geeks{ // mark the function with open open fun student():string =\"alok\"}class batch: geeks() { override fun student():string = \"ashish\"}", "e": 27266, "s": 27116, "text": null }, { "code": null, "e": 27291, "s": 27266, "text": "Now our code is correct." }, { "code": null, "e": 27298, "s": 27291, "text": "Picked" }, { "code": null, "e": 27305, "s": 27298, "text": "Kotlin" }, { "code": null, "e": 27403, "s": 27305, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27412, "s": 27403, "text": "Comments" }, { "code": null, "e": 27425, "s": 27412, "text": "Old Comments" }, { "code": null, "e": 27467, "s": 27425, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 27506, "s": 27467, "text": "How to Build a Weather App in Android?" }, { "code": null, "e": 27546, "s": 27506, "text": "How to Get Current Location in Android?" }, { "code": null, "e": 27580, "s": 27546, "text": "ImageView in Android with Example" }, { "code": null, "e": 27602, "s": 27580, "text": "ScrollView in Android" }, { "code": null, "e": 27631, "s": 27602, "text": "Kotlin Coroutines on Android" }, { "code": null, "e": 27657, "s": 27631, "text": "Kotlin extension function" }, { "code": null, "e": 27695, "s": 27657, "text": "Notifications in Android with Example" }, { "code": null, "e": 27750, "s": 27695, "text": "How to Send Data From Activity to Fragment in Android?" } ]
CSS - Margins
The margin property defines the space around an HTML element. It is possible to use negative values to overlap content. The values of the margin property are not inherited by the child elements. Remember that the adjacent vertical margins (top and bottom margins) will collapse into each other so that the distance between the blocks is not the sum of the margins, but only the greater of the two margins or the same size as one margin if both are equal. We have the following properties to set an element margin. The margin specifies a shorthand property for setting the margin properties in one declaration. The margin specifies a shorthand property for setting the margin properties in one declaration. The margin-bottom specifies the bottom margin of an element. The margin-bottom specifies the bottom margin of an element. The margin-top specifies the top margin of an element. The margin-top specifies the top margin of an element. The margin-left specifies the left margin of an element. The margin-left specifies the left margin of an element. The margin-right specifies the right margin of an element. The margin-right specifies the right margin of an element. Now, we will see how to use these properties with examples. The margin property allows you set all of the properties for the four margins in one declaration. Here is the syntax to set margin around a paragraph − Here is an example − <html> <head> </head> <body> <p style = "margin: 15px; border:1px solid black;"> all four margins will be 15px </p> <p style = "margin:10px 2%; border:1px solid black;"> top and bottom margin will be 10px, left and right margin will be 2% of the total width of the document. </p> <p style = "margin: 10px 2% -10px; border:1px solid black;"> top margin will be 10px, left and right margin will be 2% of the total width of the document, bottom margin will be -10px </p> <p style = "margin: 10px 2% -10px auto; border:1px solid black;"> top margin will be 10px, right margin will be 2% of the total width of the document, bottom margin will be -10px, left margin will be set by the browser </p> </body> </html> It will produce the following result − all four margins will be 15px top and bottom margin will be 10px, left and right margin will be 2% of the total width of the document. top margin will be 10px, left and right margin will be 2% of the total width of the document, bottom margin will be -10px top margin will be 10px, right margin will be 2% of the total width of the document, bottom margin will be -10px, left margin will be set by the browser The margin-bottom property allows you set bottom margin of an element. It can have a value in length, % or auto. Here is an example − <html> <head> </head> <body> <p style = "margin-bottom: 15px; border:1px solid black;"> This is a paragraph with a specified bottom margin </p> <p style = "margin-bottom: 5%; border:1px solid black;"> This is another paragraph with a specified bottom margin in percent </p> </body> </html> It will produce the following result − This is a paragraph with a specified bottom margin This is another paragraph with a specified bottom margin in percent The margin-top property allows you set top margin of an element. It can have a value in length, % or auto. Here is an example − <html> <head> </head> <body> <p style = "margin-top: 15px; border:1px solid black;"> This is a paragraph with a specified top margin </p> <p style = "margin-top: 5%; border:1px solid black;"> This is another paragraph with a specified top margin in percent </p> </body> </html> It will produce the following result − This is a paragraph with a specified top margin This is another paragraph with a specified top margin in percent The margin-left property allows you set left margin of an element. It can have a value in length, % or auto. Here is an example − <html> <head> </head> <body> <p style = "margin-left: 15px; border:1px solid black;"> This is a paragraph with a specified left margin </p> <p style = "margin-left: 5%; border:1px solid black;"> This is another paragraph with a specified top margin in percent </p> </body> </html> It will produce the following result − This is a paragraph with a specified left margin This is another paragraph with a specified top margin in percent The margin-right property allows you set right margin of an element. It can have a value in length, % or auto. Here is an example − <html> <head> </head> <body> <p style = "margin-right: 15px; border:1px solid black;"> This is a paragraph with a specified right margin </p> <p style = "margin-right: 5%; border:1px solid black;"> This is another paragraph with a specified right margin in percent </p> </body> </html> It will produce the following result − This is a paragraph with a specified right margin This is another paragraph with a specified right margin in percent 33 Lectures 2.5 hours Anadi Sharma 26 Lectures 2.5 hours Frahaan Hussain 44 Lectures 4.5 hours DigiFisk (Programming Is Fun) 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 51 Lectures 7.5 hours DigiFisk (Programming Is Fun) 52 Lectures 4 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2746, "s": 2626, "text": "The margin property defines the space around an HTML element. It is possible to use negative values to overlap content." }, { "code": null, "e": 3081, "s": 2746, "text": "The values of the margin property are not inherited by the child elements. Remember that the adjacent vertical margins (top and bottom margins) will collapse into each other so that the distance between the blocks is not the sum of the margins, but only the greater of the two margins or the same size as one margin if both are equal." }, { "code": null, "e": 3140, "s": 3081, "text": "We have the following properties to set an element margin." }, { "code": null, "e": 3236, "s": 3140, "text": "The margin specifies a shorthand property for setting the margin properties in one declaration." }, { "code": null, "e": 3332, "s": 3236, "text": "The margin specifies a shorthand property for setting the margin properties in one declaration." }, { "code": null, "e": 3393, "s": 3332, "text": "The margin-bottom specifies the bottom margin of an element." }, { "code": null, "e": 3454, "s": 3393, "text": "The margin-bottom specifies the bottom margin of an element." }, { "code": null, "e": 3509, "s": 3454, "text": "The margin-top specifies the top margin of an element." }, { "code": null, "e": 3564, "s": 3509, "text": "The margin-top specifies the top margin of an element." }, { "code": null, "e": 3621, "s": 3564, "text": "The margin-left specifies the left margin of an element." }, { "code": null, "e": 3678, "s": 3621, "text": "The margin-left specifies the left margin of an element." }, { "code": null, "e": 3737, "s": 3678, "text": "The margin-right specifies the right margin of an element." }, { "code": null, "e": 3796, "s": 3737, "text": "The margin-right specifies the right margin of an element." }, { "code": null, "e": 3856, "s": 3796, "text": "Now, we will see how to use these properties with examples." }, { "code": null, "e": 4008, "s": 3856, "text": "The margin property allows you set all of the properties for the four margins in one declaration. Here is the syntax to set margin around a paragraph −" }, { "code": null, "e": 4029, "s": 4008, "text": "Here is an example −" }, { "code": null, "e": 4899, "s": 4029, "text": "<html>\n <head>\n </head>\n \n <body>\n <p style = \"margin: 15px; border:1px solid black;\">\n all four margins will be 15px\n </p>\n \n <p style = \"margin:10px 2%; border:1px solid black;\">\n top and bottom margin will be 10px, left and right margin will be 2% \n of the total width of the document.\n </p>\n \n <p style = \"margin: 10px 2% -10px; border:1px solid black;\">\n top margin will be 10px, left and right margin will be 2% of the \n total width of the document, bottom margin will be -10px\n </p>\n \n <p style = \"margin: 10px 2% -10px auto; border:1px solid black;\">\n top margin will be 10px, right margin will be 2% of the total \n width of the document, bottom margin will be -10px, left margin \n will be set by the browser\n </p>\n </body>\n</html> " }, { "code": null, "e": 4938, "s": 4899, "text": "It will produce the following result −" }, { "code": null, "e": 4975, "s": 4938, "text": " \n all four margins will be 15px \n" }, { "code": null, "e": 5087, "s": 4975, "text": " \n top and bottom margin will be 10px, left and right margin will be 2% of the total width of the document. \n" }, { "code": null, "e": 5214, "s": 5087, "text": "\n top margin will be 10px, left and right margin will be 2% of the total width of the document, bottom margin will be -10px\n" }, { "code": null, "e": 5373, "s": 5214, "text": "\n top margin will be 10px, right margin will be 2% of the total width of the document, bottom margin will be -10px, left margin will be set by the browser \n" }, { "code": null, "e": 5486, "s": 5373, "text": "The margin-bottom property allows you set bottom margin of an element. It can have a value in length, % or auto." }, { "code": null, "e": 5507, "s": 5486, "text": "Here is an example −" }, { "code": null, "e": 5860, "s": 5507, "text": "<html>\n <head>\n </head>\n\n <body>\n <p style = \"margin-bottom: 15px; border:1px solid black;\">\n This is a paragraph with a specified bottom margin\n </p>\n \n <p style = \"margin-bottom: 5%; border:1px solid black;\">\n This is another paragraph with a specified bottom margin in percent\n </p>\n </body>\n</html> " }, { "code": null, "e": 5899, "s": 5860, "text": "It will produce the following result −" }, { "code": null, "e": 5956, "s": 5899, "text": "\n This is a paragraph with a specified bottom margin \n" }, { "code": null, "e": 6030, "s": 5956, "text": " \n This is another paragraph with a specified bottom margin in percent\n" }, { "code": null, "e": 6137, "s": 6030, "text": "The margin-top property allows you set top margin of an element. It can have a value in length, % or auto." }, { "code": null, "e": 6158, "s": 6137, "text": "Here is an example −" }, { "code": null, "e": 6498, "s": 6158, "text": "<html>\n <head>\n </head>\n\n <body>\n <p style = \"margin-top: 15px; border:1px solid black;\">\n This is a paragraph with a specified top margin\n </p>\n \n <p style = \"margin-top: 5%; border:1px solid black;\">\n This is another paragraph with a specified top margin in percent\n </p>\n </body>\n</html>" }, { "code": null, "e": 6537, "s": 6498, "text": "It will produce the following result −" }, { "code": null, "e": 6592, "s": 6537, "text": " \n This is a paragraph with a specified top margin \n" }, { "code": null, "e": 6664, "s": 6592, "text": " \n This is another paragraph with a specified top margin in percent \n" }, { "code": null, "e": 6773, "s": 6664, "text": "The margin-left property allows you set left margin of an element. It can have a value in length, % or auto." }, { "code": null, "e": 6794, "s": 6773, "text": "Here is an example −" }, { "code": null, "e": 7138, "s": 6794, "text": "<html>\n <head>\n </head>\n\n <body>\n <p style = \"margin-left: 15px; border:1px solid black;\">\n This is a paragraph with a specified left margin\n </p>\n \n <p style = \"margin-left: 5%; border:1px solid black;\">\n This is another paragraph with a specified top margin in percent\n </p>\n </body>\n</html> " }, { "code": null, "e": 7177, "s": 7138, "text": "It will produce the following result −" }, { "code": null, "e": 7233, "s": 7177, "text": " \n This is a paragraph with a specified left margin \n" }, { "code": null, "e": 7305, "s": 7233, "text": " \n This is another paragraph with a specified top margin in percent \n" }, { "code": null, "e": 7416, "s": 7305, "text": "The margin-right property allows you set right margin of an element. It can have a value in length, % or auto." }, { "code": null, "e": 7437, "s": 7416, "text": "Here is an example −" }, { "code": null, "e": 7782, "s": 7437, "text": "<html>\n <head>\n </head>\n \n <body>\n <p style = \"margin-right: 15px; border:1px solid black;\">\n This is a paragraph with a specified right margin\n </p>\n <p style = \"margin-right: 5%; border:1px solid black;\">\n This is another paragraph with a specified right margin in percent\n </p>\n </body>\n</html> " }, { "code": null, "e": 7821, "s": 7782, "text": "It will produce the following result −" }, { "code": null, "e": 7878, "s": 7821, "text": " \n This is a paragraph with a specified right margin \n" }, { "code": null, "e": 7952, "s": 7878, "text": " \n This is another paragraph with a specified right margin in percent \n" }, { "code": null, "e": 7987, "s": 7952, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8001, "s": 7987, "text": " Anadi Sharma" }, { "code": null, "e": 8036, "s": 8001, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8053, "s": 8036, "text": " Frahaan Hussain" }, { "code": null, "e": 8088, "s": 8053, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8119, "s": 8088, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8154, "s": 8119, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8185, "s": 8154, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8220, "s": 8185, "text": "\n 51 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8251, "s": 8220, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8284, "s": 8251, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 8315, "s": 8284, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8322, "s": 8315, "text": " Print" }, { "code": null, "e": 8333, "s": 8322, "text": " Add Notes" } ]
How to delete a temporary file in Java?
The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories. In certain scenarios such as unit testing, or for some application logics you might need to create temporary files. The File class in Java provides a method with name createTempFile(). This method accepts two String variables representing the prefix (starting name) and suffix(extension) of the temp file and a File object representing the directory (abstract path) at which you need to create the file. Following Java example creates a temporary file named exampleTempFile5387153267019244721.txt in the path D:/SampleDirectory import java.io.File; import java.io.IOException; public class TempararyFiles { public static void main(String args[]) throws IOException { String prefix = "exampleTempFile"; String suffix = ".txt"; //Creating a File object for directory File directoryPath = new File("D:/SampleDirectory"); //Creating a temp file File.createTempFile(prefix, suffix, directoryPath); System.out.println("Temp file created........."); } } Temp file created......... You can delete a temporary file in two ways using the File class and, using the Files class. The File class provides a delete() method which deletes the current file or directory, invoke this method on the temporary file. The following Java program creates and deletes a temp file. import java.io.File; import java.io.IOException; public class TempararyFiles { public static void main(String args[]) throws IOException { String prefix = "exampleTempFile"; String suffix = ".txt"; //Creating a File object for directory File directoryPath = new File("D:/SampleDirectory"); //Creating a temp file File tempFile = File.createTempFile(prefix, suffix, directoryPath); System.out.println("Temp file created: "+tempFile.getAbsolutePath()); //Deleting the file tempFile.delete(); System.out.println("Temp file deleted........."); } } Temp file created: D:\SampleDirectory\exampleTempFile7179732984227266899.txt Temp file deleted......... Just like the file class the Files class of java.nio package provides createTempFile() method which accepts two String parameters representing the prefix and suffix of and creates a temp file with specified details. The delete() method of this class accepts a path object and deletes the file in the specified path. Following Java program creates and deletes a temporary file using the using the Files class. import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public class TempararyFiles { public static void main(String args[]) throws IOException { String prefix = "exampleTempFile"; String suffix = ".txt"; //Creating a File object for directory File directoryPath = new File("D:/SampleDirectory"); //Creating a temp file Path tempFilePath = Files.createTempFile(prefix, suffix); System.out.println("Temp file created: "+tempFilePath.toString()); //Deleting the file Files.deleteIfExists(tempFilePath); System.out.println("Temp file deleted........."); } } Temp file created: C:\Users\TUTORI~2\AppData\Local\Temp\exampleTempFile1192122004600989866.txt Temp file deleted.........
[ { "code": null, "e": 1253, "s": 1062, "text": "The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories." }, { "code": null, "e": 1369, "s": 1253, "text": "In certain scenarios such as unit testing, or for some application logics you might need to create temporary files." }, { "code": null, "e": 1657, "s": 1369, "text": "The File class in Java provides a method with name createTempFile(). This method accepts two String variables representing the prefix (starting name) and suffix(extension) of the temp file and a File object representing the directory (abstract path) at which you need to create the file." }, { "code": null, "e": 1781, "s": 1657, "text": "Following Java example creates a temporary file named exampleTempFile5387153267019244721.txt in the path D:/SampleDirectory" }, { "code": null, "e": 2248, "s": 1781, "text": "import java.io.File;\nimport java.io.IOException;\npublic class TempararyFiles {\n public static void main(String args[]) throws IOException {\n String prefix = \"exampleTempFile\";\n String suffix = \".txt\";\n //Creating a File object for directory\n File directoryPath = new File(\"D:/SampleDirectory\");\n //Creating a temp file\n File.createTempFile(prefix, suffix, directoryPath);\n System.out.println(\"Temp file created.........\");\n }\n}" }, { "code": null, "e": 2275, "s": 2248, "text": "Temp file created........." }, { "code": null, "e": 2368, "s": 2275, "text": "You can delete a temporary file in two ways using the File class and, using the Files class." }, { "code": null, "e": 2497, "s": 2368, "text": "The File class provides a delete() method which deletes the current file or directory, invoke this method on the temporary file." }, { "code": null, "e": 2557, "s": 2497, "text": "The following Java program creates and deletes a temp file." }, { "code": null, "e": 3167, "s": 2557, "text": "import java.io.File;\nimport java.io.IOException;\npublic class TempararyFiles {\n public static void main(String args[]) throws IOException {\n String prefix = \"exampleTempFile\";\n String suffix = \".txt\";\n //Creating a File object for directory\n File directoryPath = new File(\"D:/SampleDirectory\");\n //Creating a temp file\n File tempFile = File.createTempFile(prefix, suffix, directoryPath);\n System.out.println(\"Temp file created: \"+tempFile.getAbsolutePath());\n //Deleting the file\n tempFile.delete();\n System.out.println(\"Temp file deleted.........\");\n }\n}" }, { "code": null, "e": 3271, "s": 3167, "text": "Temp file created: D:\\SampleDirectory\\exampleTempFile7179732984227266899.txt\nTemp file deleted........." }, { "code": null, "e": 3487, "s": 3271, "text": "Just like the file class the Files class of java.nio package provides createTempFile() method which accepts two String parameters representing the prefix and suffix of and creates a temp file with specified details." }, { "code": null, "e": 3587, "s": 3487, "text": "The delete() method of this class accepts a path object and deletes the file in the specified path." }, { "code": null, "e": 3680, "s": 3587, "text": "Following Java program creates and deletes a temporary file using the using the Files class." }, { "code": null, "e": 4349, "s": 3680, "text": "import java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\npublic class TempararyFiles {\n public static void main(String args[]) throws IOException {\n String prefix = \"exampleTempFile\";\n String suffix = \".txt\";\n //Creating a File object for directory\n File directoryPath = new File(\"D:/SampleDirectory\");\n //Creating a temp file\n Path tempFilePath = Files.createTempFile(prefix, suffix);\n System.out.println(\"Temp file created: \"+tempFilePath.toString());\n //Deleting the file\n Files.deleteIfExists(tempFilePath);\n System.out.println(\"Temp file deleted.........\");\n }\n}" }, { "code": null, "e": 4471, "s": 4349, "text": "Temp file created: C:\\Users\\TUTORI~2\\AppData\\Local\\Temp\\exampleTempFile1192122004600989866.txt\nTemp file deleted........." } ]
Matplotlib.ticker.AutoLocator Class in Python - GeeksforGeeks
07 Oct, 2021 Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. The matplotlib.ticker.AutoLocator class is a subclass of matplotlib.ticker.MaxNLocator, and has parameters nbins = ‘auto’ and steps = [1, 2, 2.5, 5, 10]. It is used to dynamically find major tick positions. Syntax:class matplotlib.ticker.AutoLocatorParameters: nbins: It is either an integer or ‘auto’, where the integer value represents the maximum number of intervals; one less than max number of ticks. The number of bins gets automatically determined on the basis of the length of the axis.It is an optional argument and has a default value of 10. steps: It is an optional parameter representing a nice number sequence that starts from 1 and ends with 10. integer: It is an optional boolean value. If set True, the ticks accepts only integer values, provided at least min_n_ticks integers are within the view limits. symmetric: It is an optional value. If set to True, auto-scaling will result in a range symmetric about zero. prune: It is an optional parameter that accepts either of the four values: {‘lower’, ‘upper’, ‘both’, None}. By default it is None. Example 1: Python3 import matplotlibimport matplotlib.pyplot as pltimport numpy as np fig, axes = plt.subplots(3, 4, sharex = 'row', sharey = 'row', squeeze = False) data = np.random.rand(20, 2, 10) for ax in axes.flatten()[:-1]: ax.plot(*np.random.randn(2, 10), marker ="o", ls ="") # Now remove axes[1, 5] from# the grouper for xaxisaxes[2, 3].get_shared_x_axes().remove(axes[2, 3]) # Create and assign new tickerxticker = matplotlib.axis.Ticker()axes[2, 3].xaxis.major = xticker # The new ticker needs new locator# and formattersxloc = matplotlib.ticker.AutoLocator()xfmt = matplotlib.ticker.ScalarFormatter() axes[2, 3].xaxis.set_major_locator(xloc)axes[2, 3].xaxis.set_major_formatter(xfmt) # Now plot to the "ungrouped" axesaxes[2, 3].plot(np.random.randn(10)*100 + 100, np.linspace(-3, 3, 10), marker ="o", ls ="", color ="green") plt.show() Output: Example 2: Python3 import pylab as plfrom matplotlib import ticker # helper functiondef AutoLocatorInit(self): ticker.MaxNLocator.__init__(self, nbins = 4, steps =[1, 2, 5, 10]) ticker.AutoLocator.__init__ = AutoLocatorInit pl.plot(pl.randn(100))pl.figure()pl.hist(pl.randn(1000), bins = 40) pl.show() Output: gabaa406 Python-matplotlib Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Convert integer to string in Python Convert string to integer in Python Python infinity How to set input type date in dd-mm-yyyy format using HTML ? Matplotlib.pyplot.title() in Python
[ { "code": null, "e": 24528, "s": 24500, "text": "\n07 Oct, 2021" }, { "code": null, "e": 24741, "s": 24528, "text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. " }, { "code": null, "e": 24949, "s": 24741, "text": "The matplotlib.ticker.AutoLocator class is a subclass of matplotlib.ticker.MaxNLocator, and has parameters nbins = ‘auto’ and steps = [1, 2, 2.5, 5, 10]. It is used to dynamically find major tick positions. " }, { "code": null, "e": 25005, "s": 24949, "text": "Syntax:class matplotlib.ticker.AutoLocatorParameters: " }, { "code": null, "e": 25297, "s": 25005, "text": "nbins: It is either an integer or ‘auto’, where the integer value represents the maximum number of intervals; one less than max number of ticks. The number of bins gets automatically determined on the basis of the length of the axis.It is an optional argument and has a default value of 10. " }, { "code": null, "e": 25406, "s": 25297, "text": "steps: It is an optional parameter representing a nice number sequence that starts from 1 and ends with 10. " }, { "code": null, "e": 25568, "s": 25406, "text": "integer: It is an optional boolean value. If set True, the ticks accepts only integer values, provided at least min_n_ticks integers are within the view limits. " }, { "code": null, "e": 25679, "s": 25568, "text": "symmetric: It is an optional value. If set to True, auto-scaling will result in a range symmetric about zero. " }, { "code": null, "e": 25813, "s": 25679, "text": "prune: It is an optional parameter that accepts either of the four values: {‘lower’, ‘upper’, ‘both’, None}. By default it is None. " }, { "code": null, "e": 25826, "s": 25813, "text": "Example 1: " }, { "code": null, "e": 25834, "s": 25826, "text": "Python3" }, { "code": "import matplotlibimport matplotlib.pyplot as pltimport numpy as np fig, axes = plt.subplots(3, 4, sharex = 'row', sharey = 'row', squeeze = False) data = np.random.rand(20, 2, 10) for ax in axes.flatten()[:-1]: ax.plot(*np.random.randn(2, 10), marker =\"o\", ls =\"\") # Now remove axes[1, 5] from# the grouper for xaxisaxes[2, 3].get_shared_x_axes().remove(axes[2, 3]) # Create and assign new tickerxticker = matplotlib.axis.Ticker()axes[2, 3].xaxis.major = xticker # The new ticker needs new locator# and formattersxloc = matplotlib.ticker.AutoLocator()xfmt = matplotlib.ticker.ScalarFormatter() axes[2, 3].xaxis.set_major_locator(xloc)axes[2, 3].xaxis.set_major_formatter(xfmt) # Now plot to the \"ungrouped\" axesaxes[2, 3].plot(np.random.randn(10)*100 + 100, np.linspace(-3, 3, 10), marker =\"o\", ls =\"\", color =\"green\") plt.show()", "e": 26792, "s": 25834, "text": null }, { "code": null, "e": 26802, "s": 26792, "text": "Output: " }, { "code": null, "e": 26815, "s": 26802, "text": "Example 2: " }, { "code": null, "e": 26823, "s": 26815, "text": "Python3" }, { "code": "import pylab as plfrom matplotlib import ticker # helper functiondef AutoLocatorInit(self): ticker.MaxNLocator.__init__(self, nbins = 4, steps =[1, 2, 5, 10]) ticker.AutoLocator.__init__ = AutoLocatorInit pl.plot(pl.randn(100))pl.figure()pl.hist(pl.randn(1000), bins = 40) pl.show()", "e": 27178, "s": 26823, "text": null }, { "code": null, "e": 27188, "s": 27178, "text": "Output: " }, { "code": null, "e": 27199, "s": 27190, "text": "gabaa406" }, { "code": null, "e": 27217, "s": 27199, "text": "Python-matplotlib" }, { "code": null, "e": 27224, "s": 27217, "text": "Python" }, { "code": null, "e": 27240, "s": 27224, "text": "Write From Home" }, { "code": null, "e": 27338, "s": 27240, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27356, "s": 27338, "text": "Python Dictionary" }, { "code": null, "e": 27391, "s": 27356, "text": "Read a file line by line in Python" }, { "code": null, "e": 27413, "s": 27391, "text": "Enumerate() in Python" }, { "code": null, "e": 27445, "s": 27413, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27475, "s": 27445, "text": "Iterate over a list in Python" }, { "code": null, "e": 27511, "s": 27475, "text": "Convert integer to string in Python" }, { "code": null, "e": 27547, "s": 27511, "text": "Convert string to integer in Python" }, { "code": null, "e": 27563, "s": 27547, "text": "Python infinity" }, { "code": null, "e": 27624, "s": 27563, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
How to sort one-dimensional array in ascending order using non-static method?
Set the unsorted array first. int[] list = {87, 45, 56, 22, 84, 65}; Now use a nested for loop to sort the list, which is passed to a function. for(int i=0; i< arr.Length; i++) { for(int j=i+1; j<arr.Length; j++) { if(arr[i]>=arr[j]) { temp=arr[j]; arr[j]=arr[i]; arr[i]=temp; } } Console.Write(arr[i] + " "); } The following is the complete code to sort one-dimensional array in ascending order using non-static method. Live Demo using System; namespace Demo { public class MyApplication { public static void Main(string[] args) { int[] list = {87, 45, 56, 22, 84, 65}; Console.WriteLine("Original Unsorted List"); foreach (int i in list) { Console.Write(i + " "); } MyApplication m = new MyApplication(); m.sortFunc(list); } public void sortFunc(int[] arr) { int temp = 0; Console.WriteLine("\nSorted List"); for(int i=0; i< arr.Length; i++) { for(int j=i+1; j<arr.Length; j++) { if(arr[i]>=arr[j]) { temp=arr[j]; arr[j]=arr[i]; arr[i]=temp; } } Console.Write(arr[i] + " "); } } } } Original Unsorted List 87 45 56 22 84 65 Sorted List 22 45 56 65 84 87
[ { "code": null, "e": 1092, "s": 1062, "text": "Set the unsorted array first." }, { "code": null, "e": 1131, "s": 1092, "text": "int[] list = {87, 45, 56, 22, 84, 65};" }, { "code": null, "e": 1206, "s": 1131, "text": "Now use a nested for loop to sort the list, which is passed to a function." }, { "code": null, "e": 1422, "s": 1206, "text": "for(int i=0; i< arr.Length; i++) {\n for(int j=i+1; j<arr.Length; j++) {\n if(arr[i]>=arr[j]) {\n temp=arr[j];\n arr[j]=arr[i];\n arr[i]=temp;\n }\n }\n Console.Write(arr[i] + \" \");\n}" }, { "code": null, "e": 1531, "s": 1422, "text": "The following is the complete code to sort one-dimensional array in ascending order using non-static method." }, { "code": null, "e": 1542, "s": 1531, "text": " Live Demo" }, { "code": null, "e": 2348, "s": 1542, "text": "using System;\nnamespace Demo {\n public class MyApplication {\n public static void Main(string[] args) {\n int[] list = {87, 45, 56, 22, 84, 65};\n Console.WriteLine(\"Original Unsorted List\");\n foreach (int i in list) {\n Console.Write(i + \" \");\n }\n MyApplication m = new MyApplication();\n m.sortFunc(list);\n }\n public void sortFunc(int[] arr) {\n int temp = 0;\n Console.WriteLine(\"\\nSorted List\");\n for(int i=0; i< arr.Length; i++) {\n for(int j=i+1; j<arr.Length; j++) {\n if(arr[i]>=arr[j]) {\n temp=arr[j];\n arr[j]=arr[i];\n arr[i]=temp;\n }\n }\n Console.Write(arr[i] + \" \");\n }\n }\n }\n}" }, { "code": null, "e": 2419, "s": 2348, "text": "Original Unsorted List\n87 45 56 22 84 65\nSorted List\n22 45 56 65 84 87" } ]
How to execute a cube of numbers of a given array in JavaScript?
To find the cubes of elements of given array we need to run a for loop to access each and every element and we need to use "=" operator to replace elements with their cubes.To get the desired values the below steps need to be followed. 1) Declared an array a = [1,2,3,4,5] 2) For loop was introduced to access each and every element in the array(a[i]). 3) Inside for loop "=" operator is used to replace the element with their cubic values(a[i]*a[i]*a[i]). so, from the above steps the output obtained will be 1,8,27,64,125.By following the above steps we can get not only cubes but also any power of elements in a provided array. Live Demo <html> <body> <script> var a = [1,2,3,4,5]; for ( var i = 0; i < a.length;i++) { a[i] = a[i]*a[i]*a[i]; } document.write(a); </script> </body> </html> [1, 8, 27, 64, 125]
[ { "code": null, "e": 1298, "s": 1062, "text": "To find the cubes of elements of given array we need to run a for loop to access each and every element and we need to use \"=\" operator to replace elements with their cubes.To get the desired values the below steps need to be followed." }, { "code": null, "e": 1335, "s": 1298, "text": "1) Declared an array a = [1,2,3,4,5]" }, { "code": null, "e": 1415, "s": 1335, "text": "2) For loop was introduced to access each and every element in the array(a[i])." }, { "code": null, "e": 1519, "s": 1415, "text": "3) Inside for loop \"=\" operator is used to replace the element with their cubic values(a[i]*a[i]*a[i])." }, { "code": null, "e": 1693, "s": 1519, "text": "so, from the above steps the output obtained will be 1,8,27,64,125.By following the above steps we can get not only cubes but also any power of elements in a provided array." }, { "code": null, "e": 1703, "s": 1693, "text": "Live Demo" }, { "code": null, "e": 1872, "s": 1703, "text": "<html>\n<body>\n<script>\n var a = [1,2,3,4,5];\n for ( var i = 0; i < a.length;i++) {\n a[i] = a[i]*a[i]*a[i];\n }\n document.write(a);\n</script>\n</body>\n</html>" }, { "code": null, "e": 1892, "s": 1872, "text": "[1, 8, 27, 64, 125]" } ]
clone() - 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 clone, __clone2 - create a child process #include <sched.h> int clone(int (*fn)(void *), void *child_stack, int flags, void *arg, ... /* pid_t *pid, struct user_desc *tls ", pid_t *" ctid " */ );" int __clone2(int (*fn)(void *), void *child_stack_base, size_t stack_size, int flags, void *arg, ... /* pid_t *pid, struct user_desc *tls ", pid_t *" ctid " */ );" int clone(int (*fn)(void *), void *child_stack, int flags, void *arg, ... /* pid_t *pid, struct user_desc *tls ", pid_t *" ctid " */ );" int __clone2(int (*fn)(void *), void *child_stack_base, size_t stack_size, int flags, void *arg, ... /* pid_t *pid, struct user_desc *tls ", pid_t *" ctid " */ );" clone() creates a new process, in a manner similar to fork(2). It is actually a library function layered on top of the underlying clone() system call, hereinafter referred to as sys_clone. A description of sys_clone is given towards the end of this page. Unlike fork(2), these calls allow the child process to share parts of its execution context with the calling process, such as the memory space, the table of file descriptors, and the table of signal handlers. (Note that on this manual page, "calling process" normally corresponds to "parent process". But see the description of CLONE_PARENT below.) The main use of clone() is to implement threads: multiple threads of control in a program that run concurrently in a shared memory space. When the child process is created with clone(), it executes the function application fn(arg). (This differs from fork(2), where execution continues in the child from the point of the fork(2) call.) The fn argument is a pointer to a function that is called by the child process at the beginning of its execution. The arg argument is passed to the fn function. When the fn(arg) function application returns, the child process terminates. The integer returned by fn is the exit code for the child process. The child process may also terminate explicitly by calling exit(2) or after receiving a fatal signal. The child_stack argument specifies the location of the stack used by the child process. Since the child and calling process may share memory, it is not possible for the child process to execute in the same stack as the calling process. The calling process must therefore set up memory space for the child stack and pass a pointer to this space to clone(). Stacks grow downwards on all processors that run Linux (except the HP PA processors), so child_stack usually points to the topmost address of the memory space set up for the child stack. The low byte of flags contains the number of the termination signal sent to the parent when the child dies. If this signal is specified as anything other than SIGCHLD, then the parent process must specify the __WALL or __WCLONE options when waiting for the child with wait(2). If no signal is specified, then the parent process is not signaled when the child terminates. flags may also be bitwise-or’ed with zero or more of the following constants, in order to specify what is shared between the calling process and the child process: If CLONE_PARENT is not set, then (as with fork(2)) the child’s parent is the calling process. Note that it is the parent process, as returned by getppid(2), which is signaled when the child terminates, so that if CLONE_PARENT is set, then the parent of the calling process, rather than the calling process itself, will be signaled. If CLONE_FS is not set, the child process works on a copy of the file system information of the calling process at the time of the clone() call. Calls to chroot(2), chdir(2), umask(2) performed later by one of the processes do not affect the other process. If CLONE_FILES is not set, the child process inherits a copy of all file descriptors opened in the calling process at the time of clone(). (The duplicated file descriptors in the child refer to the same open file descriptions (see open(2)) as the corresponding file descriptors in the calling process.) Subsequent operations that open or close file descriptors, or change file descriptor flags, performed by either the calling process or the child process do not affect the other process. Every process lives in a namespace. The namespace of a process is the data (the set of mounts) describing the file hierarchy as seen by that process. After a fork(2) or clone(2) where the CLONE_NEWNS flag is not set, the child lives in the same namespace as the parent. The system calls mount(2) and umount(2) change the namespace of the calling process, and hence affect all processes that live in the same namespace, but do not affect processes in a different namespace. After a clone(2) where the CLONE_NEWNS flag is set, the cloned child is started in a new namespace, initialized with a copy of the namespace of the parent. Only a privileged process (one having the CAP_SYS_ADMIN capability) may specify the CLONE_NEWNS flag. It is not permitted to specify both CLONE_NEWNS and CLONE_FS in the same clone() call. If CLONE_SIGHAND is not set, the child process inherits a copy of the signal handlers of the calling process at the time clone() is called. Calls to sigaction(2) performed later by one of the processes have no effect on the other process. Since Linux 2.6.0-test6, flags must also include CLONE_VM if CLONE_SIGHAND is specified If CLONE_VFORK is not set then both the calling process and the child are schedulable after the call, and an application should not rely on execution occurring in any particular order. If CLONE_VM is not set, the child process runs in a separate copy of the memory space of the calling process at the time of clone(). Memory writes or file mappings/unmappings performed by one of the processes do not affect the other, as with fork(2). Thread groups were a feature added in Linux 2.4 to support the POSIX threads notion of a set of threads that share a single PID. Internally, this shared PID is the so-called thread group identifier (TGID) for the thread group. Since Linux 2.4, calls to getpid(2) return the TGID of the caller. The threads within a group can be distinguished by their (system-wide) unique thread IDs (TID). A new thread’s TID is available as the function result returned to the caller of clone(), and a thread can obtain its own TID using gettid(2). When a call is made to clone() without specifying CLONE_THREAD, then the resulting thread is placed in a new thread group whose TGID is the same as the thread’s TID. This thread is the leader of the new thread group. A new thread created with CLONE_THREAD has the same parent process as the caller of clone() (i.e., like CLONE_PARENT), so that calls to getppid(2) return the same value for all of the threads in a thread group. When a CLONE_THREAD thread terminates, the thread that created it using clone() is not sent a SIGCHLD (or other termination) signal; nor can the status of such a thread be obtained using wait(2). (The thread is said to be detached.) After all of the threads in a thread group terminate the parent process of the thread group is sent a SIGCHLD (or other termination) signal. If any of the threads in a thread group performs an execve(2), then all threads other than the thread group leader are terminated, and the new program is executed in the thread group leader. If one of the threads in a thread group creates a child using fork(2), then any thread in the group can wait(2) for that child. Since Linux 2.5.35, flags must also include CLONE_SIGHAND if CLONE_THREAD is specified. Signals may be sent to a thread group as a whole (i.e., a TGID) using kill(2), or to a specific thread (i.e., TID) using tgkill(2). Signal dispositions and actions are process-wide: if an unhandled signal is delivered to a thread, then it will affect (terminate, stop, continue, be ignored in) all members of the thread group. Each thread has its own signal mask, as set by sigprocmask(2), but signals can be pending either: for the whole process (i.e., deliverable to any member of the thread group), when sent with kill(2); or for an individual thread, when sent with tgkill(2). A call to sigpending(2) returns a signal set that is the union of the signals pending for the whole process and the signals that are pending for the calling thread. If kill(2) is used to send a signal to a thread group, and the thread group has installed a handler for the signal, then the handler will be invoked in exactly one, arbitrarily selected member of the thread group that has not blocked the signal. If multiple threads in a group are waiting to accept the same signal using sigwaitinfo(2), the kernel will arbitrarily select one of these threads to receive a signal sent using kill(2). Another difference for sys_clone is that the child_stack argument may be zero, in which case copy-on-write semantics ensure that the child gets separate copies of stack pages when either process modifies the stack. In this case, for correct operation, the CLONE_VM option should not be specified. Since Linux 2.5.49 the system call has five parameters. The two new parameters are parent_tidptr which points to the location (in parent and child memory) where the child thread ID will be written in case CLONE_PARENT_SETTID was specified, and child_tidptr which points to the location (in child memory) where the child thread ID will be written in case CLONE_CHILD_SETTID was specified. There is no entry for clone() in libc5. glibc2 provides clone() as described in this manual page. The clone() and sys_clone calls are Linux specific and should not be used in programs intended to be portable. In the kernel 2.4.x series, CLONE_THREAD generally does not make the parent of the new thread the same as the parent of the calling process. However, for kernel versions 2.4.7 to 2.4.18 the CLONE_THREAD flag implied the CLONE_PARENT flag (as in kernel 2.6). For a while there was CLONE_DETACHED (introduced in 2.5.32): parent wants no child-exit signal. In 2.6.2 the need to give this together with CLONE_THREAD disappeared. This flag is still defined, but has no effect. On x86, clone() should not be called through vsyscall, but directly through int $0x80. On IA-64, a different system call is used: int __clone2(int (*fn)(void *), void *child_stack_base, size_t stack_size, int flags, void *arg, ... /* pid_t *pid, struct user_desc *tls ", pid_t *" ctid " */ );" int __clone2(int (*fn)(void *), void *child_stack_base, size_t stack_size, int flags, void *arg, ... /* pid_t *pid, struct user_desc *tls ", pid_t *" ctid " */ );" The __clone2() system call operates in the same way as clone(), except that child_stack_base points to the lowest address of the child’s stack area, and stack_size specifies the size of the stack pointed to by child_stack_base. Versions of the GNU C library that include the NPTL threading library contain a wrapper function for getpid(2) that performs caching of PIDs. In programs linked against such libraries, calls to getpid(2) may return the same value, even when the threads were not created using CLONE_THREAD (and thus are not in the same thread group). To get the truth, it may be necessary to use code such as the following #include <syscall.h> pid_t mypid; mypid = syscall(SYS_getpid); fork (2) fork (2) futex (2) futex (2) getpid (2) getpid (2) gettid (2) gettid (2) set_thread_area (2) set_thread_area (2) set_tid_address (2) set_tid_address (2) tkill (2) tkill (2) unshare (2) unshare (2) wait (2) wait (2) Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 1466, "s": 1454, "text": "Unix - Home" }, { "code": null, "e": 1489, "s": 1466, "text": "Unix - Getting Started" }, { "code": null, "e": 1512, "s": 1489, "text": "Unix - File Management" }, { "code": null, "e": 1531, "s": 1512, "text": "Unix - Directories" }, { "code": null, "e": 1554, "s": 1531, "text": "Unix - File Permission" }, { "code": null, "e": 1573, "s": 1554, "text": "Unix - Environment" }, { "code": null, "e": 1596, "s": 1573, "text": "Unix - Basic Utilities" }, { "code": null, "e": 1619, "s": 1596, "text": "Unix - Pipes & Filters" }, { "code": null, "e": 1636, "s": 1619, "text": "Unix - Processes" }, { "code": null, "e": 1657, "s": 1636, "text": "Unix - Communication" }, { "code": null, "e": 1678, "s": 1657, "text": "Unix - The vi Editor" }, { "code": null, "e": 1700, "s": 1678, "text": "Unix - What is Shell?" }, { "code": null, "e": 1723, "s": 1700, "text": "Unix - Using Variables" }, { "code": null, "e": 1748, "s": 1723, "text": "Unix - Special Variables" }, { "code": null, "e": 1768, "s": 1748, "text": "Unix - Using Arrays" }, { "code": null, "e": 1791, "s": 1768, "text": "Unix - Basic Operators" }, { "code": null, "e": 1814, "s": 1791, "text": "Unix - Decision Making" }, { "code": null, "e": 1833, "s": 1814, "text": "Unix - Shell Loops" }, { "code": null, "e": 1853, "s": 1833, "text": "Unix - Loop Control" }, { "code": null, "e": 1880, "s": 1853, "text": "Unix - Shell Substitutions" }, { "code": null, "e": 1906, "s": 1880, "text": "Unix - Quoting Mechanisms" }, { "code": null, "e": 1929, "s": 1906, "text": "Unix - IO Redirections" }, { "code": null, "e": 1952, "s": 1929, "text": "Unix - Shell Functions" }, { "code": null, "e": 1972, "s": 1952, "text": "Unix - Manpage Help" }, { "code": null, "e": 1999, "s": 1972, "text": "Unix - Regular Expressions" }, { "code": null, "e": 2025, "s": 1999, "text": "Unix - File System Basics" }, { "code": null, "e": 2052, "s": 2025, "text": "Unix - User Administration" }, { "code": null, "e": 2078, "s": 2052, "text": "Unix - System Performance" }, { "code": null, "e": 2100, "s": 2078, "text": "Unix - System Logging" }, { "code": null, "e": 2125, "s": 2100, "text": "Unix - Signals and Traps" }, { "code": null, "e": 2148, "s": 2125, "text": "Unix - Useful Commands" }, { "code": null, "e": 2167, "s": 2148, "text": "Unix - Quick Guide" }, { "code": null, "e": 2192, "s": 2167, "text": "Unix - Builtin Functions" }, { "code": null, "e": 2212, "s": 2192, "text": "Unix - System Calls" }, { "code": null, "e": 2233, "s": 2212, "text": "Unix - Commands List" }, { "code": null, "e": 2255, "s": 2233, "text": "Unix Useful Resources" }, { "code": null, "e": 2273, "s": 2255, "text": "Computer Glossary" }, { "code": null, "e": 2284, "s": 2273, "text": "Who is Who" }, { "code": null, "e": 2319, "s": 2284, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2360, "s": 2319, "text": "clone, __clone2 - create a child process" }, { "code": null, "e": 2740, "s": 2360, "text": "#include <sched.h> \n\nint clone(int (*fn)(void *), void *child_stack, \n int flags, void *arg, ... \n /* pid_t *pid, struct user_desc *tls \n\", pid_t *\" ctid \" */ );\"\n\n\nint __clone2(int (*fn)(void *), void *child_stack_base, \n size_t stack_size, int flags, void *arg, ... \n /* pid_t *pid, struct user_desc *tls \n\", pid_t *\" ctid \" */ );\"\n" }, { "code": null, "e": 2904, "s": 2740, "text": "\nint clone(int (*fn)(void *), void *child_stack, \n int flags, void *arg, ... \n /* pid_t *pid, struct user_desc *tls \n\", pid_t *\" ctid \" */ );\"\n" }, { "code": null, "e": 3101, "s": 2904, "text": "\n\nint __clone2(int (*fn)(void *), void *child_stack_base, \n size_t stack_size, int flags, void *arg, ... \n /* pid_t *pid, struct user_desc *tls \n\", pid_t *\" ctid \" */ );\"\n" }, { "code": null, "e": 3358, "s": 3101, "text": "clone() creates a new process, in a manner similar to fork(2). It is actually a library function layered on top of the underlying clone() system call, hereinafter referred to as \nsys_clone. A description of sys_clone is given towards the end of this page." }, { "code": null, "e": 3707, "s": 3358, "text": "Unlike fork(2), these calls allow the child process to share parts of its execution context with the calling process, such as the memory space, the table of file descriptors, and the table of signal handlers. (Note that on this manual\npage, \"calling process\" normally corresponds to \"parent process\". But see the description of CLONE_PARENT below.)" }, { "code": null, "e": 3845, "s": 3707, "text": "The main use of clone() is to implement threads: multiple threads of control in a program that run concurrently in a shared memory space." }, { "code": null, "e": 4204, "s": 3845, "text": "When the child process is created with clone(), it executes the function application fn(arg). (This differs from fork(2), where execution continues in the child from the point of the fork(2)\ncall.) The fn argument is a pointer to a function that is called by the child process at the beginning of its execution. The arg argument is passed to the fn function." }, { "code": null, "e": 4450, "s": 4204, "text": "When the fn(arg) function application returns, the child process terminates. The integer returned by fn is the exit code for the child process. The child process may also terminate explicitly by calling\nexit(2) or after receiving a fatal signal." }, { "code": null, "e": 4993, "s": 4450, "text": "The child_stack argument specifies the location of the stack used by the child process. Since the child and calling process may share memory, it is not possible for the child process to execute in the\nsame stack as the calling process. The calling process must therefore set up memory space for the child stack and pass a pointer to this space to clone(). Stacks grow downwards on all processors that run Linux\n(except the HP PA processors), so child_stack usually points to the topmost address of the memory space set up for the child stack." }, { "code": null, "e": 5365, "s": 4993, "text": "The low byte of flags contains the number of the termination signal sent to the parent when the child dies. If this signal is specified as anything other than SIGCHLD, then the parent process must specify the \n__WALL or __WCLONE options when waiting for the child with wait(2). If no signal is specified, then the parent process is not signaled when the child terminates." }, { "code": null, "e": 5529, "s": 5365, "text": "flags may also be bitwise-or’ed with zero or more of the following constants, in order to specify what is shared between the calling process and the child process:" }, { "code": null, "e": 5625, "s": 5529, "text": "\nIf\nCLONE_PARENT is not set, then (as with\nfork(2))\nthe child’s parent is the calling process.\n" }, { "code": null, "e": 5865, "s": 5625, "text": "\nNote that it is the parent process, as returned by\ngetppid(2),\nwhich is signaled when the child terminates, so that\nif\nCLONE_PARENT is set, then the parent of the calling process, rather than the\ncalling process itself, will be signaled.\n" }, { "code": null, "e": 6124, "s": 5865, "text": "\nIf\nCLONE_FS is not set, the child process works on a copy of the file system\ninformation of the calling process at the time of the\nclone() call.\nCalls to\nchroot(2),\nchdir(2),\numask(2)\nperformed later by one of the processes do not affect the other process.\n" }, { "code": null, "e": 6615, "s": 6124, "text": "\nIf\nCLONE_FILES is not set, the child process inherits a copy of all file descriptors\nopened in the calling process at the time of\nclone(). (The duplicated file descriptors in the child refer to the\nsame open file descriptions (see\nopen(2))\nas the corresponding file descriptors in the calling process.)\nSubsequent operations that open or close file descriptors,\nor change file descriptor flags,\nperformed by either the calling\nprocess or the child process do not affect the other process.\n" }, { "code": null, "e": 7090, "s": 6615, "text": "\nEvery process lives in a namespace.\nThe\nnamespace of a process is the data (the set of mounts) describing the file hierarchy\nas seen by that process.\nAfter a\nfork(2)\nor\nclone(2)\nwhere the\nCLONE_NEWNS flag is not set, the child lives in the same namespace as the parent.\nThe system calls\nmount(2)\nand\numount(2)\nchange the namespace of the calling process, and hence affect\nall processes that live in the same namespace, but do not affect\nprocesses in a different namespace.\n" }, { "code": null, "e": 7248, "s": 7090, "text": "\nAfter a\nclone(2)\nwhere the\nCLONE_NEWNS flag is set, the cloned child is started in a new namespace,\ninitialized with a copy of the namespace of the parent.\n" }, { "code": null, "e": 7439, "s": 7248, "text": "\nOnly a privileged process (one having the CAP_SYS_ADMIN capability)\nmay specify the\nCLONE_NEWNS flag.\nIt is not permitted to specify both\nCLONE_NEWNS and\nCLONE_FS in the same\nclone() call.\n" }, { "code": null, "e": 7680, "s": 7439, "text": "\nIf\nCLONE_SIGHAND is not set, the child process inherits a copy of the signal handlers\nof the calling process at the time\nclone() is called.\nCalls to\nsigaction(2)\nperformed later by one of the processes have no effect on the other\nprocess.\n" }, { "code": null, "e": 7770, "s": 7680, "text": "\nSince Linux 2.6.0-test6,\nflags must also include\nCLONE_VM if\nCLONE_SIGHAND is specified\n" }, { "code": null, "e": 7957, "s": 7770, "text": "\nIf\nCLONE_VFORK is not set then both the calling process and the child are schedulable\nafter the call, and an application should not rely on execution occurring\nin any particular order.\n" }, { "code": null, "e": 8210, "s": 7957, "text": "\nIf\nCLONE_VM is not set, the child process runs in a separate copy of the memory\nspace of the calling process at the time of\nclone(). Memory writes or file mappings/unmappings performed by one of the\nprocesses do not affect the other, as with\nfork(2).\n" }, { "code": null, "e": 8506, "s": 8210, "text": "\nThread groups were a feature added in Linux 2.4 to support the\nPOSIX threads notion of a set of threads that share a single PID.\nInternally, this shared PID is the so-called\nthread group identifier (TGID) for the thread group.\nSince Linux 2.4, calls to\ngetpid(2)\nreturn the TGID of the caller.\n" }, { "code": null, "e": 8747, "s": 8506, "text": "\nThe threads within a group can be distinguished by their (system-wide)\nunique thread IDs (TID).\nA new thread’s TID is available as the function result\nreturned to the caller of\nclone(), and a thread can obtain\nits own TID using\ngettid(2).\n" }, { "code": null, "e": 8966, "s": 8747, "text": "\nWhen a call is made to\nclone() without specifying\nCLONE_THREAD, then the resulting thread is placed in a new thread group\nwhose TGID is the same as the thread’s TID.\nThis thread is the\nleader of the new thread group.\n" }, { "code": null, "e": 9412, "s": 8966, "text": "\nA new thread created with\nCLONE_THREAD has the same parent process as the caller of\nclone() (i.e., like\nCLONE_PARENT), so that calls to\ngetppid(2)\nreturn the same value for all of the threads in a thread group.\nWhen a\nCLONE_THREAD thread terminates, the thread that created it using\nclone() is not sent a\nSIGCHLD (or other termination) signal;\nnor can the status of such a thread be obtained\nusing\nwait(2).\n(The thread is said to be\ndetached.) " }, { "code": null, "e": 9555, "s": 9412, "text": "\nAfter all of the threads in a thread group terminate\nthe parent process of the thread group is sent a\nSIGCHLD (or other termination) signal.\n" }, { "code": null, "e": 9748, "s": 9555, "text": "\nIf any of the threads in a thread group performs an\nexecve(2),\nthen all threads other than the thread group leader are terminated,\nand the new program is executed in the thread group leader.\n" }, { "code": null, "e": 9878, "s": 9748, "text": "\nIf one of the threads in a thread group creates a child using\nfork(2),\nthen any thread in the group can\nwait(2)\nfor that child.\n" }, { "code": null, "e": 9968, "s": 9878, "text": "\nSince Linux 2.5.35,\nflags must also include\nCLONE_SIGHAND if\nCLONE_THREAD is specified.\n" }, { "code": null, "e": 10102, "s": 9968, "text": "\nSignals may be sent to a thread group as a whole (i.e., a TGID) using\nkill(2),\nor to a specific thread (i.e., TID) using\ntgkill(2).\n" }, { "code": null, "e": 10299, "s": 10102, "text": "\nSignal dispositions and actions are process-wide:\nif an unhandled signal is delivered to a thread, then\nit will affect (terminate, stop, continue, be ignored in)\nall members of the thread group.\n" }, { "code": null, "e": 10720, "s": 10299, "text": "\nEach thread has its own signal mask, as set by\nsigprocmask(2),\nbut signals can be pending either: for the whole process\n(i.e., deliverable to any member of the thread group),\nwhen sent with\nkill(2);\nor for an individual thread, when sent with\ntgkill(2).\nA call to\nsigpending(2)\nreturns a signal set that is the union of the signals pending for the\nwhole process and the signals that are pending for the calling thread.\n" }, { "code": null, "e": 11155, "s": 10720, "text": "\nIf\nkill(2)\nis used to send a signal to a thread group,\nand the thread group has installed a handler for the signal, then\nthe handler will be invoked in exactly one, arbitrarily selected\nmember of the thread group that has not blocked the signal.\nIf multiple threads in a group are waiting to accept the same signal using\nsigwaitinfo(2),\nthe kernel will arbitrarily select one of these threads\nto receive a signal sent using\nkill(2).\n" }, { "code": null, "e": 11454, "s": 11155, "text": "\nAnother difference for\nsys_clone is that the\nchild_stack argument may be zero, in which case copy-on-write semantics ensure that the\nchild gets separate copies of stack pages when either process modifies\nthe stack.\nIn this case, for correct operation, the\nCLONE_VM option should not be specified.\n" }, { "code": null, "e": 11844, "s": 11454, "text": "\nSince Linux 2.5.49 the system call has five parameters.\nThe two new parameters are\nparent_tidptr which points to the location (in parent and child memory) where\nthe child thread ID will be written in case CLONE_PARENT_SETTID\nwas specified, and\nchild_tidptr which points to the location (in child memory) where the child thread ID\nwill be written in case CLONE_CHILD_SETTID was specified.\n" }, { "code": null, "e": 11942, "s": 11844, "text": "There is no entry for clone() in libc5. glibc2 provides clone() as described in this manual page." }, { "code": null, "e": 12053, "s": 11942, "text": "The clone() and sys_clone calls are Linux specific and should not be used in programs intended to be portable." }, { "code": null, "e": 12312, "s": 12053, "text": "In the kernel 2.4.x series, CLONE_THREAD generally does not make the parent of the new thread the same as the parent of the calling process. However, for kernel versions 2.4.7 to 2.4.18 the CLONE_THREAD flag implied the\nCLONE_PARENT flag (as in kernel 2.6). " }, { "code": null, "e": 12656, "s": 12312, "text": "For a while there was CLONE_DETACHED (introduced in 2.5.32): parent wants no child-exit signal. In 2.6.2 the need to give this together with CLONE_THREAD disappeared. This flag is still defined, but has no effect. On x86, clone() should not be called through vsyscall, but directly through int $0x80. On IA-64, a different system call is used:" }, { "code": null, "e": 12852, "s": 12656, "text": "\nint __clone2(int (*fn)(void *), void *child_stack_base, \n size_t stack_size, int flags, void *arg, ... \n /* pid_t *pid, struct user_desc *tls \n\", pid_t *\" ctid \" */ );\"\n" }, { "code": null, "e": 13048, "s": 12852, "text": "\nint __clone2(int (*fn)(void *), void *child_stack_base, \n size_t stack_size, int flags, void *arg, ... \n /* pid_t *pid, struct user_desc *tls \n\", pid_t *\" ctid \" */ );\"\n" }, { "code": null, "e": 13277, "s": 13048, "text": "The __clone2() system call operates in the same way as clone(), except that child_stack_base points to the lowest address of the child’s stack area, and\nstack_size specifies the size of the stack pointed to by child_stack_base." }, { "code": null, "e": 13683, "s": 13277, "text": "Versions of the GNU C library that include the NPTL threading library contain a wrapper function for getpid(2) that performs caching of PIDs. In programs linked against such libraries, calls to\ngetpid(2) may return the same value, even when the threads were not created using CLONE_THREAD (and thus are not in the same thread group). To get the truth, it may be necessary to use code such as the following" }, { "code": null, "e": 13749, "s": 13683, "text": "#include <syscall.h>\n\npid_t mypid;\n\nmypid = syscall(SYS_getpid);\n" }, { "code": null, "e": 13758, "s": 13749, "text": "fork (2)" }, { "code": null, "e": 13767, "s": 13758, "text": "fork (2)" }, { "code": null, "e": 13777, "s": 13767, "text": "futex (2)" }, { "code": null, "e": 13787, "s": 13777, "text": "futex (2)" }, { "code": null, "e": 13798, "s": 13787, "text": "getpid (2)" }, { "code": null, "e": 13809, "s": 13798, "text": "getpid (2)" }, { "code": null, "e": 13820, "s": 13809, "text": "gettid (2)" }, { "code": null, "e": 13831, "s": 13820, "text": "gettid (2)" }, { "code": null, "e": 13851, "s": 13831, "text": "set_thread_area (2)" }, { "code": null, "e": 13871, "s": 13851, "text": "set_thread_area (2)" }, { "code": null, "e": 13891, "s": 13871, "text": "set_tid_address (2)" }, { "code": null, "e": 13911, "s": 13891, "text": "set_tid_address (2)" }, { "code": null, "e": 13921, "s": 13911, "text": "tkill (2)" }, { "code": null, "e": 13931, "s": 13921, "text": "tkill (2)" }, { "code": null, "e": 13943, "s": 13931, "text": "unshare (2)" }, { "code": null, "e": 13955, "s": 13943, "text": "unshare (2)" }, { "code": null, "e": 13964, "s": 13955, "text": "wait (2)" }, { "code": null, "e": 13973, "s": 13964, "text": "wait (2)" }, { "code": null, "e": 13990, "s": 13973, "text": "\nAdvertisements\n" }, { "code": null, "e": 14025, "s": 13990, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 14053, "s": 14025, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 14087, "s": 14053, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 14104, "s": 14087, "text": " Frahaan Hussain" }, { "code": null, "e": 14137, "s": 14104, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 14148, "s": 14137, "text": " Pradeep D" }, { "code": null, "e": 14183, "s": 14148, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 14199, "s": 14183, "text": " Musab Zayadneh" }, { "code": null, "e": 14232, "s": 14199, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 14244, "s": 14232, "text": " GUHARAJANM" }, { "code": null, "e": 14276, "s": 14244, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 14284, "s": 14276, "text": " Uplatz" }, { "code": null, "e": 14291, "s": 14284, "text": " Print" }, { "code": null, "e": 14302, "s": 14291, "text": " Add Notes" } ]
10 Tricks for Converting Numbers and Strings to Datetime in Pandas | by B. Chen | Towards Data Science
When doing data analysis, it is important to ensure correct data types. Otherwise, you may get unexpected results or errors. Datetime is a common data type in data science projects and the data is often saved as numbers or strings. During data analysis, you will likely need to explicitly convert them to a datetime type. This article will discuss how to convert numbers and strings to a datetime type. More specifically, you will learn how to use the Pandas built-in methods to_datetime() and astype() to deal with the following common problems: Converting numbers to datetimeConverting strings to datetimeHandling day first formatDealing with custom datetime formatHandling parse errorHandling missing valuesAssembling datetime from multiple columnsConverting multiple columns at onceParsing date column when reading a CSV fileDifference between astype() and to_datetime() Converting numbers to datetime Converting strings to datetime Handling day first format Dealing with custom datetime format Handling parse error Handling missing values Assembling datetime from multiple columns Converting multiple columns at once Parsing date column when reading a CSV file Difference between astype() and to_datetime() Please check out the Notebook for the source code. Pandas has 2 built-in methods astype() and to_datetime() that can be used to convert numbers to datetime. For instance, to convert numbers denote second to datetime: df = pd.DataFrame({'date': [1470195805, 1480195805, 1490195805], 'value': [2, 3, 4]}) When using to_datetime() , we need to call it from Pandas and set the argument unit='s': >>> pd.to_datetime(df['date'], unit='s')0 2016-08-03 03:43:251 2016-11-26 21:30:052 2017-03-22 15:16:45Name: date, dtype: datetime64[ns] When using astype() , we need to call it from a Series (the date column) and pass in 'datetime[s]': >>> df['date'].astype('datetime64[s]')0 2016-08-03 03:43:251 2016-11-26 21:30:052 2017-03-22 15:16:45Name: date, dtype: datetime64[ns] Similarly, we can convert numbers denote other units (D,s, ms, us, ns) to datetime, for instance, numbers denote the day df = pd.DataFrame({'date': [1470, 1480, 1490], 'value': [2, 3, 4]})>>> pd.to_datetime(df['date'], unit='D')0 1974-01-101 1974-01-202 1974-01-30Name: date, dtype: datetime64[ns]>>> df['date'].astype('datetime64[D]')0 1974-01-101 1974-01-202 1974-01-30Name: date, dtype: datetime64[ns] Often, you’ll find that dates are represented as strings. In Pandas, strings are shown as object, it’s the internal Pandas lingo for the string. >>> df = pd.DataFrame({'date':['3/10/2015','3/11/2015','3/12/2015'], 'value': [2, 3, 4]})>>> df.dtypesdate objectvalue int64dtype: object Both to_datetime() and astype() can be used to convert strings to datetime. >>> pd.to_datetime(df['date'])0 2015-03-101 2015-03-112 2015-03-12Name: date, dtype: datetime64[ns]>>> df['date'].astype('datetime64')0 2015-03-101 2015-03-112 2015-03-12Name: date, dtype: datetime64[ns] By default, to_datetime() will parse strings with month first (MM/DD, MM DD, or MM-DD) format, and this arrangement is relatively unique in the United State. In most of the rest of the world, the day is written first (DD/MM, DD MM, or DD-MM). If you would like Pandas to consider day first instead of month, you can set the argument dayfirst to True. df = pd.DataFrame({'date': ['3/10/2000', '3/11/2000', '3/12/2000'], 'value': [2, 3, 4]})df['date'] = pd.to_datetime(df['date'], dayfirst=True) Alternatively, you pass a custom format to the argument format. By default, strings are parsed using the Pandas built-in parser from dateutil.parser.parse. Sometimes, your strings might be in a custom format, for example, YYYY-d-m HH:MM:SS. Pandas to_datetime() has an argument called format that allows you to pass a custom format: df = pd.DataFrame({'date': ['2016-6-10 20:30:0', '2016-7-1 19:45:30', '2013-10-12 4:5:1'], 'value': [2, 3, 4]})df['date'] = pd.to_datetime(df['date'], format="%Y-%d-%m %H:%M:%S") If a date does not meet the timestamp limitations, we will get a ParseError when converting. For instance, an invalid string a/11/2000: df = pd.DataFrame({'date': ['3/10/2000', 'a/11/2000', '3/12/2000'], 'value': [2, 3, 4]})# Getting ParseErrordf['date'] = pd.to_datetime(df['date']) to_datetime() has an argument called errors that allows you to ignore the error or force an invalid value to NaT. df['date'] = pd.to_datetime(df['date'], errors='ignore')df And to force an invalid value to NaT: df['date'] = pd.to_datetime(df['date'], errors='coerce') In Pandas, missing values are given the value NaN, short for “Not a Number”. df = pd.DataFrame({'date': ['3/10/2000', np.nan, '3/12/2000'], 'value': [2, 3, 4]}) When converting a column with missing values to datetime, both to_datetime() and astype() are changing Numpy’s NaN to Pandas’ NaT and this allows it to be a datetime. >>> df['date'].astype('datetime64')0 2000-03-101 NaT2 2000-03-12Name: date, dtype: datetime64[ns]>>> pd.to_datetime(df['date'])0 2000-03-101 NaT2 2000-03-12Name: date, dtype: datetime64[ns] Alternatively, we can replace Numpy NaN with another value (for example replacing NaN with '3/11/2000') df = pd.DataFrame({'date': ['3/10/2000', np.nan, '3/12/2000'], 'value': [2, 3, 4]})df['date'] = df['date'].fillna('3/11/2000').astype('datetime64[ns]') To learn more about working with missing values towardsdatascience.com to_datetime() can be used to assemble a datetime from multiple columns as well. The keys (columns label) can be common abbreviations like [‘year’, ‘month’, ‘day’, ‘minute’, ‘second’, ‘ms’, ‘us’, ‘ns’]) or plurals of the same. df = pd.DataFrame({'year': [2015, 2016], 'month': [2, 3], 'day': [4, 5], 'hour': [10,11] }) To create a datetime column from a subset of columns >>> pd.to_datetime(df[['month','day','year']])0 2015-02-041 2016-03-05dtype: datetime64[ns] To create a datetime column from the entire DataFrame >>> pd.to_datetime(df)0 2015-02-04 10:00:001 2016-03-05 11:00:00dtype: datetime64[ns] So far, we have been converting data type one column at a time. There is a DataFrame method also called astype() allows us to convert multiple column data types at once. It is time-saving when you have a bunch of columns you want to change. df = df.astype({ 'date_start': 'datetime64', 'date_end': 'datetime64'}) If you want to set the data type for each column when reading a CSV file, you can use the argument parse_date when loading data with read_csv(): Note the data type datetime64 is not supported by dtype, and we should use parse_dates argument instead. df = pd.read_csv( 'dataset.csv', dtype={ # datetime64[ns] is not supported 'value': 'float16' }, parse_dates=['date']) To learn more about parsing date column with Pandas read_csv(): towardsdatascience.com astype() is the common method to convert data type from one to other. The method is supported by both Pandas DataFrame and Series. If you need to convert a bunch of columns, the astype() should be the first choice as it: can convert multiple columns at once has the best performance (shown in the screenshot below) However, astype() won’t work for a column with invalid data. For instance, an invalid date string a/11/2000. If we try to use astype() we would get a ParseError. As of Pandas 0.20.0, this error can be suppressed by setting the argument errors='ignore', but your original data will be returned untouched. The Pandas to_datetime() function can handle these values more gracefully. Rather than fail, we can set the argument errors='coerce' to coerce invalid values to NaT. In addition, it can be very difficult to use astype() when dealing with custom datetime format. The Pandas to_datetime() has an argument called format and offers more possibility in the way of custom conversion. We have seen how we can convert a Pandas data column to a datetime type with astype() and to_datetime(). to_datetime() is the simplest way and offers error handling and more possibility in the way of custom conversion, while astype() has better performance and can convert multiple columns at once. I hope this article will help you to save time in learning Pandas. I recommend you to check out the documentation for the astypes() and to_datetime() API and to know about other things you can do. Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning. 10 tricks to convert data to a numeric type in Pandas Pandas json_normalize() you should know for flattening JSON All Pandas cut() you should know for transforming numerical data into categorical data Using Pandas method chaining to improve code readability How to do a Custom Sort on Pandas DataFrame All the Pandas shift() you should know for data analysis When to use Pandas transform() function Pandas concat() tricks you should know All the Pandas merge() you should know Working with datetime in Pandas DataFrame Pandas read_csv() tricks you should know 4 tricks you should know to parse date columns with Pandas read_csv() More tutorials can be found on my Github
[ { "code": null, "e": 494, "s": 172, "text": "When doing data analysis, it is important to ensure correct data types. Otherwise, you may get unexpected results or errors. Datetime is a common data type in data science projects and the data is often saved as numbers or strings. During data analysis, you will likely need to explicitly convert them to a datetime type." }, { "code": null, "e": 719, "s": 494, "text": "This article will discuss how to convert numbers and strings to a datetime type. More specifically, you will learn how to use the Pandas built-in methods to_datetime() and astype() to deal with the following common problems:" }, { "code": null, "e": 1047, "s": 719, "text": "Converting numbers to datetimeConverting strings to datetimeHandling day first formatDealing with custom datetime formatHandling parse errorHandling missing valuesAssembling datetime from multiple columnsConverting multiple columns at onceParsing date column when reading a CSV fileDifference between astype() and to_datetime()" }, { "code": null, "e": 1078, "s": 1047, "text": "Converting numbers to datetime" }, { "code": null, "e": 1109, "s": 1078, "text": "Converting strings to datetime" }, { "code": null, "e": 1135, "s": 1109, "text": "Handling day first format" }, { "code": null, "e": 1171, "s": 1135, "text": "Dealing with custom datetime format" }, { "code": null, "e": 1192, "s": 1171, "text": "Handling parse error" }, { "code": null, "e": 1216, "s": 1192, "text": "Handling missing values" }, { "code": null, "e": 1258, "s": 1216, "text": "Assembling datetime from multiple columns" }, { "code": null, "e": 1294, "s": 1258, "text": "Converting multiple columns at once" }, { "code": null, "e": 1338, "s": 1294, "text": "Parsing date column when reading a CSV file" }, { "code": null, "e": 1384, "s": 1338, "text": "Difference between astype() and to_datetime()" }, { "code": null, "e": 1435, "s": 1384, "text": "Please check out the Notebook for the source code." }, { "code": null, "e": 1601, "s": 1435, "text": "Pandas has 2 built-in methods astype() and to_datetime() that can be used to convert numbers to datetime. For instance, to convert numbers denote second to datetime:" }, { "code": null, "e": 1705, "s": 1601, "text": "df = pd.DataFrame({'date': [1470195805, 1480195805, 1490195805], 'value': [2, 3, 4]})" }, { "code": null, "e": 1794, "s": 1705, "text": "When using to_datetime() , we need to call it from Pandas and set the argument unit='s':" }, { "code": null, "e": 1937, "s": 1794, "text": ">>> pd.to_datetime(df['date'], unit='s')0 2016-08-03 03:43:251 2016-11-26 21:30:052 2017-03-22 15:16:45Name: date, dtype: datetime64[ns]" }, { "code": null, "e": 2037, "s": 1937, "text": "When using astype() , we need to call it from a Series (the date column) and pass in 'datetime[s]':" }, { "code": null, "e": 2178, "s": 2037, "text": ">>> df['date'].astype('datetime64[s]')0 2016-08-03 03:43:251 2016-11-26 21:30:052 2017-03-22 15:16:45Name: date, dtype: datetime64[ns]" }, { "code": null, "e": 2299, "s": 2178, "text": "Similarly, we can convert numbers denote other units (D,s, ms, us, ns) to datetime, for instance, numbers denote the day" }, { "code": null, "e": 2613, "s": 2299, "text": "df = pd.DataFrame({'date': [1470, 1480, 1490], 'value': [2, 3, 4]})>>> pd.to_datetime(df['date'], unit='D')0 1974-01-101 1974-01-202 1974-01-30Name: date, dtype: datetime64[ns]>>> df['date'].astype('datetime64[D]')0 1974-01-101 1974-01-202 1974-01-30Name: date, dtype: datetime64[ns]" }, { "code": null, "e": 2758, "s": 2613, "text": "Often, you’ll find that dates are represented as strings. In Pandas, strings are shown as object, it’s the internal Pandas lingo for the string." }, { "code": null, "e": 2926, "s": 2758, "text": ">>> df = pd.DataFrame({'date':['3/10/2015','3/11/2015','3/12/2015'], 'value': [2, 3, 4]})>>> df.dtypesdate objectvalue int64dtype: object" }, { "code": null, "e": 3002, "s": 2926, "text": "Both to_datetime() and astype() can be used to convert strings to datetime." }, { "code": null, "e": 3218, "s": 3002, "text": ">>> pd.to_datetime(df['date'])0 2015-03-101 2015-03-112 2015-03-12Name: date, dtype: datetime64[ns]>>> df['date'].astype('datetime64')0 2015-03-101 2015-03-112 2015-03-12Name: date, dtype: datetime64[ns]" }, { "code": null, "e": 3376, "s": 3218, "text": "By default, to_datetime() will parse strings with month first (MM/DD, MM DD, or MM-DD) format, and this arrangement is relatively unique in the United State." }, { "code": null, "e": 3569, "s": 3376, "text": "In most of the rest of the world, the day is written first (DD/MM, DD MM, or DD-MM). If you would like Pandas to consider day first instead of month, you can set the argument dayfirst to True." }, { "code": null, "e": 3730, "s": 3569, "text": "df = pd.DataFrame({'date': ['3/10/2000', '3/11/2000', '3/12/2000'], 'value': [2, 3, 4]})df['date'] = pd.to_datetime(df['date'], dayfirst=True)" }, { "code": null, "e": 3794, "s": 3730, "text": "Alternatively, you pass a custom format to the argument format." }, { "code": null, "e": 4063, "s": 3794, "text": "By default, strings are parsed using the Pandas built-in parser from dateutil.parser.parse. Sometimes, your strings might be in a custom format, for example, YYYY-d-m HH:MM:SS. Pandas to_datetime() has an argument called format that allows you to pass a custom format:" }, { "code": null, "e": 4316, "s": 4063, "text": "df = pd.DataFrame({'date': ['2016-6-10 20:30:0', '2016-7-1 19:45:30', '2013-10-12 4:5:1'], 'value': [2, 3, 4]})df['date'] = pd.to_datetime(df['date'], format=\"%Y-%d-%m %H:%M:%S\")" }, { "code": null, "e": 4452, "s": 4316, "text": "If a date does not meet the timestamp limitations, we will get a ParseError when converting. For instance, an invalid string a/11/2000:" }, { "code": null, "e": 4618, "s": 4452, "text": "df = pd.DataFrame({'date': ['3/10/2000', 'a/11/2000', '3/12/2000'], 'value': [2, 3, 4]})# Getting ParseErrordf['date'] = pd.to_datetime(df['date'])" }, { "code": null, "e": 4732, "s": 4618, "text": "to_datetime() has an argument called errors that allows you to ignore the error or force an invalid value to NaT." }, { "code": null, "e": 4791, "s": 4732, "text": "df['date'] = pd.to_datetime(df['date'], errors='ignore')df" }, { "code": null, "e": 4829, "s": 4791, "text": "And to force an invalid value to NaT:" }, { "code": null, "e": 4886, "s": 4829, "text": "df['date'] = pd.to_datetime(df['date'], errors='coerce')" }, { "code": null, "e": 4963, "s": 4886, "text": "In Pandas, missing values are given the value NaN, short for “Not a Number”." }, { "code": null, "e": 5065, "s": 4963, "text": "df = pd.DataFrame({'date': ['3/10/2000', np.nan, '3/12/2000'], 'value': [2, 3, 4]})" }, { "code": null, "e": 5232, "s": 5065, "text": "When converting a column with missing values to datetime, both to_datetime() and astype() are changing Numpy’s NaN to Pandas’ NaT and this allows it to be a datetime." }, { "code": null, "e": 5448, "s": 5232, "text": ">>> df['date'].astype('datetime64')0 2000-03-101 NaT2 2000-03-12Name: date, dtype: datetime64[ns]>>> pd.to_datetime(df['date'])0 2000-03-101 NaT2 2000-03-12Name: date, dtype: datetime64[ns]" }, { "code": null, "e": 5552, "s": 5448, "text": "Alternatively, we can replace Numpy NaN with another value (for example replacing NaN with '3/11/2000')" }, { "code": null, "e": 5722, "s": 5552, "text": "df = pd.DataFrame({'date': ['3/10/2000', np.nan, '3/12/2000'], 'value': [2, 3, 4]})df['date'] = df['date'].fillna('3/11/2000').astype('datetime64[ns]')" }, { "code": null, "e": 5770, "s": 5722, "text": "To learn more about working with missing values" }, { "code": null, "e": 5793, "s": 5770, "text": "towardsdatascience.com" }, { "code": null, "e": 6019, "s": 5793, "text": "to_datetime() can be used to assemble a datetime from multiple columns as well. The keys (columns label) can be common abbreviations like [‘year’, ‘month’, ‘day’, ‘minute’, ‘second’, ‘ms’, ‘us’, ‘ns’]) or plurals of the same." }, { "code": null, "e": 6182, "s": 6019, "text": "df = pd.DataFrame({'year': [2015, 2016], 'month': [2, 3], 'day': [4, 5], 'hour': [10,11] })" }, { "code": null, "e": 6235, "s": 6182, "text": "To create a datetime column from a subset of columns" }, { "code": null, "e": 6331, "s": 6235, "text": ">>> pd.to_datetime(df[['month','day','year']])0 2015-02-041 2016-03-05dtype: datetime64[ns]" }, { "code": null, "e": 6385, "s": 6331, "text": "To create a datetime column from the entire DataFrame" }, { "code": null, "e": 6475, "s": 6385, "text": ">>> pd.to_datetime(df)0 2015-02-04 10:00:001 2016-03-05 11:00:00dtype: datetime64[ns]" }, { "code": null, "e": 6716, "s": 6475, "text": "So far, we have been converting data type one column at a time. There is a DataFrame method also called astype() allows us to convert multiple column data types at once. It is time-saving when you have a bunch of columns you want to change." }, { "code": null, "e": 6794, "s": 6716, "text": "df = df.astype({ 'date_start': 'datetime64', 'date_end': 'datetime64'})" }, { "code": null, "e": 6939, "s": 6794, "text": "If you want to set the data type for each column when reading a CSV file, you can use the argument parse_date when loading data with read_csv():" }, { "code": null, "e": 7044, "s": 6939, "text": "Note the data type datetime64 is not supported by dtype, and we should use parse_dates argument instead." }, { "code": null, "e": 7189, "s": 7044, "text": "df = pd.read_csv( 'dataset.csv', dtype={ # datetime64[ns] is not supported 'value': 'float16' }, parse_dates=['date'])" }, { "code": null, "e": 7253, "s": 7189, "text": "To learn more about parsing date column with Pandas read_csv():" }, { "code": null, "e": 7276, "s": 7253, "text": "towardsdatascience.com" }, { "code": null, "e": 7497, "s": 7276, "text": "astype() is the common method to convert data type from one to other. The method is supported by both Pandas DataFrame and Series. If you need to convert a bunch of columns, the astype() should be the first choice as it:" }, { "code": null, "e": 7534, "s": 7497, "text": "can convert multiple columns at once" }, { "code": null, "e": 7591, "s": 7534, "text": "has the best performance (shown in the screenshot below)" }, { "code": null, "e": 7895, "s": 7591, "text": "However, astype() won’t work for a column with invalid data. For instance, an invalid date string a/11/2000. If we try to use astype() we would get a ParseError. As of Pandas 0.20.0, this error can be suppressed by setting the argument errors='ignore', but your original data will be returned untouched." }, { "code": null, "e": 8061, "s": 7895, "text": "The Pandas to_datetime() function can handle these values more gracefully. Rather than fail, we can set the argument errors='coerce' to coerce invalid values to NaT." }, { "code": null, "e": 8273, "s": 8061, "text": "In addition, it can be very difficult to use astype() when dealing with custom datetime format. The Pandas to_datetime() has an argument called format and offers more possibility in the way of custom conversion." }, { "code": null, "e": 8572, "s": 8273, "text": "We have seen how we can convert a Pandas data column to a datetime type with astype() and to_datetime(). to_datetime() is the simplest way and offers error handling and more possibility in the way of custom conversion, while astype() has better performance and can convert multiple columns at once." }, { "code": null, "e": 8769, "s": 8572, "text": "I hope this article will help you to save time in learning Pandas. I recommend you to check out the documentation for the astypes() and to_datetime() API and to know about other things you can do." }, { "code": null, "e": 8921, "s": 8769, "text": "Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning." }, { "code": null, "e": 8975, "s": 8921, "text": "10 tricks to convert data to a numeric type in Pandas" }, { "code": null, "e": 9035, "s": 8975, "text": "Pandas json_normalize() you should know for flattening JSON" }, { "code": null, "e": 9122, "s": 9035, "text": "All Pandas cut() you should know for transforming numerical data into categorical data" }, { "code": null, "e": 9179, "s": 9122, "text": "Using Pandas method chaining to improve code readability" }, { "code": null, "e": 9223, "s": 9179, "text": "How to do a Custom Sort on Pandas DataFrame" }, { "code": null, "e": 9280, "s": 9223, "text": "All the Pandas shift() you should know for data analysis" }, { "code": null, "e": 9320, "s": 9280, "text": "When to use Pandas transform() function" }, { "code": null, "e": 9359, "s": 9320, "text": "Pandas concat() tricks you should know" }, { "code": null, "e": 9398, "s": 9359, "text": "All the Pandas merge() you should know" }, { "code": null, "e": 9440, "s": 9398, "text": "Working with datetime in Pandas DataFrame" }, { "code": null, "e": 9481, "s": 9440, "text": "Pandas read_csv() tricks you should know" }, { "code": null, "e": 9551, "s": 9481, "text": "4 tricks you should know to parse date columns with Pandas read_csv()" } ]
Algorithm to get the combinations of all items in array JavaScript
We are required to write a JavaScript function that takes in an array of string literals. The function should generate and return all possible combinations of the strings in the array. For example − If the input array is − const arr = ['a', 'b', 'c', 'd']; Then the output should be − const output = ["a", "ab", "abc", "abcd", "abd", "ac", "acd", "ad", "b", "bc", "bcd", "bd", "c", "cd", "d"]; const getCombinations = (arr = []) => { const combine = (sub, ind) => { let result = [] let i, l, p; for (i = ind, l = arr.length; i < l; i++) { p = sub.slice(0); p.push(arr[i]); result = result.concat(combine(p, i + 1)); result.push(p.join('')); }; return result; } return combine([], 0); }; console.log(getCombinations(["a", "b", "c", "d"])); And the output in the console will be − [ 'abcd', 'abc', 'abd', 'ab', 'acd', 'ac', 'ad', 'a', 'bcd', 'bc', 'bd', 'b', 'cd', 'c', 'd' ]
[ { "code": null, "e": 1247, "s": 1062, "text": "We are required to write a JavaScript function that takes in an array of string literals. The function should generate and return all possible combinations of the strings in the array." }, { "code": null, "e": 1261, "s": 1247, "text": "For example −" }, { "code": null, "e": 1285, "s": 1261, "text": "If the input array is −" }, { "code": null, "e": 1319, "s": 1285, "text": "const arr = ['a', 'b', 'c', 'd'];" }, { "code": null, "e": 1347, "s": 1319, "text": "Then the output should be −" }, { "code": null, "e": 1456, "s": 1347, "text": "const output = [\"a\", \"ab\", \"abc\", \"abcd\", \"abd\", \"ac\", \"acd\", \"ad\", \"b\", \"bc\", \"bcd\", \"bd\", \"c\", \"cd\", \"d\"];" }, { "code": null, "e": 1876, "s": 1456, "text": "const getCombinations = (arr = []) => {\n const combine = (sub, ind) => {\n let result = []\n let i, l, p;\n for (i = ind, l = arr.length; i < l; i++) {\n p = sub.slice(0);\n p.push(arr[i]);\n result = result.concat(combine(p, i + 1));\n result.push(p.join(''));\n };\n return result;\n }\n return combine([], 0);\n};\nconsole.log(getCombinations([\"a\", \"b\", \"c\", \"d\"]));" }, { "code": null, "e": 1916, "s": 1876, "text": "And the output in the console will be −" }, { "code": null, "e": 2026, "s": 1916, "text": "[\n 'abcd', 'abc', 'abd',\n 'ab', 'acd', 'ac',\n 'ad', 'a', 'bcd',\n 'bc', 'bd', 'b',\n 'cd', 'c', 'd'\n]" } ]
Array Copy in C#
Use the array. copy method in C# to copy a section of one array to another. Our original array has 10 elements − int [] n = new int[10]; /* n is an array of 10 integers */ Our new array that would copy a section of array 1 has 5 elements − int [] m = new int[5]; /* m is an array of 5 integers */ The array.copy() method allow you to add the source and destination array. With that, include the size of the section of the first array that includes in the second array. You can try to run the following to implement Array copy in C# − Live Demo using System; namespace ArrayApplication { class MyArray { static void Main(string[] args) { int [] n = new int[10]; /* n is an array of 10 integers */ int [] m = new int[5]; /* m is an array of 5 integers */ for ( int i = 0; i < 10; i++ ) { n[i] = i + 100; } Console.WriteLine("Original Array..."); foreach (int j in n ) { int i = j-100; Console.WriteLine("Element[{0}] = {1}", i, j); } Array.Copy(n, 0, m, 0, 5); Console.WriteLine("New Array..."); foreach (int res in m) { Console.WriteLine(res); } Console.ReadKey(); } } } Original Array... Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109 New Array... 100 101 102 103 104
[ { "code": null, "e": 1138, "s": 1062, "text": "Use the array. copy method in C# to copy a section of one array to another." }, { "code": null, "e": 1175, "s": 1138, "text": "Our original array has 10 elements −" }, { "code": null, "e": 1234, "s": 1175, "text": "int [] n = new int[10]; /* n is an array of 10 integers */" }, { "code": null, "e": 1302, "s": 1234, "text": "Our new array that would copy a section of array 1 has 5 elements −" }, { "code": null, "e": 1359, "s": 1302, "text": "int [] m = new int[5]; /* m is an array of 5 integers */" }, { "code": null, "e": 1531, "s": 1359, "text": "The array.copy() method allow you to add the source and destination array. With that, include the size of the section of the first array that includes in the second array." }, { "code": null, "e": 1596, "s": 1531, "text": "You can try to run the following to implement Array copy in C# −" }, { "code": null, "e": 1606, "s": 1596, "text": "Live Demo" }, { "code": null, "e": 2306, "s": 1606, "text": "using System;\nnamespace ArrayApplication {\n class MyArray {\n static void Main(string[] args) {\n int [] n = new int[10]; /* n is an array of 10 integers */\n int [] m = new int[5]; /* m is an array of 5 integers */\n for ( int i = 0; i < 10; i++ ) {\n n[i] = i + 100;\n }\n Console.WriteLine(\"Original Array...\");\n foreach (int j in n ) {\n int i = j-100;\n Console.WriteLine(\"Element[{0}] = {1}\", i, j);\n }\n Array.Copy(n, 0, m, 0, 5);\n Console.WriteLine(\"New Array...\");\n foreach (int res in m) {\n Console.WriteLine(res);\n }\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 2527, "s": 2306, "text": "Original Array...\nElement[0] = 100\nElement[1] = 101\nElement[2] = 102\nElement[3] = 103\nElement[4] = 104\nElement[5] = 105\nElement[6] = 106\nElement[7] = 107\nElement[8] = 108\nElement[9] = 109\nNew Array...\n100\n101\n102\n103\n104" } ]
How to Build a Roman Numeral Convertor in Android Studio? - GeeksforGeeks
08 Feb, 2022 Roman Numeral converter is an app through which we can convert a decimal number to its corresponding roman number or a roman number to its corresponding decimal number in the range of 1 to 3999. The user will enter a decimal number and on clicking the convert to roman numeral button, the entered number will convert into its corresponding roman numeral and if the user enters a roman number, on clicking convert to decimal, the entered number will convert into its corresponding decimal number. In this article, we will be Roman Numeral convertors in Android Studio using Kotlin and XML. Prerequisite: Converting Decimal Number lying between 1 to 3999 to Roman Numerals Converting Roman Numerals to Decimal lying between 1 to 3999 Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language. Step 2: Working with the build.gradle(Module) File You need to apply the plugin kotlin-android-extensions in app build.gradle module like this plugins { id 'com.android.application' id 'kotlin-android' id 'kotlin-android-extensions' } Step 3: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="20dp" android:text="Roman Numeral Convertor" android:textSize="30sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="50dp" android:text="Decimal to Roman Numeral" android:textSize="20sp" android:textStyle="bold" /> <EditText android:id="@+id/decimal_et" android:layout_width="150dp" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="10dp"/> <Button android:id="@+id/convert_to_roman_numeral" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="10dp" android:backgroundTint="#A1F6EE" android:text="Convert to roman numeral" /> <TextView android:id="@+id/roman_numeral_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:textSize="20sp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="50dp" android:text="Roman to Decimal Number" android:textSize="20sp" android:textStyle="bold" /> <EditText android:id="@+id/roman_et" android:layout_width="150dp" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="10dp" android:capitalize="characters" /> <Button android:id="@+id/convert_to_decimal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="10dp" android:backgroundTint="#A1F6EE" android:text="Convert to decimal " /> <TextView android:id="@+id/decimal_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:textSize="20sp" /> </LinearLayout> After writing this much code our UI looks like this: Step 4: Working with the MainActivity.kt file Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import android.support.v7.app.AppCompatActivityimport android.os.Bundleimport android.widget.Toastimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Decimal to Roman convertor convert_to_roman_numeral.setOnClickListener { // check if decimal_et.text is empty or not. if (decimal_et.text.isNotEmpty()) { val number = decimal_et.text.toString().toInt() if (number <= 3999) { // int_to_Roman function convert a decimal // number to its corresponding Roman number. val roman = decimal_to_Roman(number) roman_numeral_tv.text = roman.toString() } else { Toast.makeText(this, "please enter a number in range between 1 to 3999",Toast.LENGTH_SHORT).show() } } else { Toast.makeText(this, "please enter a number ", Toast.LENGTH_SHORT).show() } } // Roman to Decimal convertor. convert_to_decimal.setOnClickListener { // check if roman_et.text is empty or not. if (roman_et.text.isNotEmpty()) { val roman = roman_et.text.toString() // RomanToDecimal function convert a Roman number // to its corresponding decimal number. decimal_tv.text = RomanToDecimal(roman).toString() } else { Toast.makeText(this, "please enter a Roman Numeral ", Toast.LENGTH_SHORT).show() } } } private fun decimal_to_Roman(num: Int): Any { val m = arrayOf("", "M", "MM", "MMM") val c = arrayOf( "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" ) val x = arrayOf( "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" ) val i = arrayOf( "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" ) // Converting to roman val thousands = m[num / 1000] val hundreds = c[num % 1000 / 100] val tens = x[num % 100 / 10] val ones = i[num % 10] return thousands + hundreds + tens + ones } fun value(r: Char): Int { if (r == 'I') return 1 if (r == 'V') return 5 if (r == 'X') return 10 if (r == 'L') return 50 if (r == 'C') return 100 if (r == 'D') return 500 return if (r == 'M') 1000 else -1 } // Finds decimal value of a // given roman numeral fun RomanToDecimal(str: String): Int { // Initialize result var res = 0 var i = 0 while (i < str.length) { // Getting value of symbol s[i] val s1 = value(str[i]) // Getting value of symbol s[i+1] if (i + 1 < str.length) { val s2 = value(str[i + 1]) // Comparing both values if (s1 >= s2) { // Value of current symbol // is greater or equalto // the next symbol res = res + s1 } else { // Value of current symbol is // less than the next symbol res = res + s2 - s1 i++ } } else { res = res + s1 } i++ } return res }} Output: simmytarika5 surinderdawra388 Android How To Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android Android Listview in Java with Example How to Change the Background Color After Clicking the Button in Android? How to Read Data from SQLite Database in Android? How to Install PIP on Windows ? How to Find the Wi-Fi Password Using CMD in Windows? How to Align Text in HTML? How to install Jupyter Notebook on Windows? How to Install OpenCV for Python on Windows?
[ { "code": null, "e": 25116, "s": 25088, "text": "\n08 Feb, 2022" }, { "code": null, "e": 25705, "s": 25116, "text": "Roman Numeral converter is an app through which we can convert a decimal number to its corresponding roman number or a roman number to its corresponding decimal number in the range of 1 to 3999. The user will enter a decimal number and on clicking the convert to roman numeral button, the entered number will convert into its corresponding roman numeral and if the user enters a roman number, on clicking convert to decimal, the entered number will convert into its corresponding decimal number. In this article, we will be Roman Numeral convertors in Android Studio using Kotlin and XML." }, { "code": null, "e": 25719, "s": 25705, "text": "Prerequisite:" }, { "code": null, "e": 25787, "s": 25719, "text": "Converting Decimal Number lying between 1 to 3999 to Roman Numerals" }, { "code": null, "e": 25848, "s": 25787, "text": "Converting Roman Numerals to Decimal lying between 1 to 3999" }, { "code": null, "e": 25879, "s": 25848, "text": "Step 1: Create a New Project " }, { "code": null, "e": 26043, "s": 25879, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language." }, { "code": null, "e": 26094, "s": 26043, "text": "Step 2: Working with the build.gradle(Module) File" }, { "code": null, "e": 26186, "s": 26094, "text": "You need to apply the plugin kotlin-android-extensions in app build.gradle module like this" }, { "code": null, "e": 26291, "s": 26186, "text": "plugins {\n\n id 'com.android.application'\n\n id 'kotlin-android'\n\n id 'kotlin-android-extensions'\n\n}" }, { "code": null, "e": 26339, "s": 26291, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 26482, "s": 26339, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 26486, "s": 26482, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:layout_marginTop=\"20dp\" android:text=\"Roman Numeral Convertor\" android:textSize=\"30sp\" android:textStyle=\"bold\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:layout_marginTop=\"50dp\" android:text=\"Decimal to Roman Numeral\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> <EditText android:id=\"@+id/decimal_et\" android:layout_width=\"150dp\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:layout_marginTop=\"10dp\"/> <Button android:id=\"@+id/convert_to_roman_numeral\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:layout_marginTop=\"10dp\" android:backgroundTint=\"#A1F6EE\" android:text=\"Convert to roman numeral\" /> <TextView android:id=\"@+id/roman_numeral_tv\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:textSize=\"20sp\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:layout_marginTop=\"50dp\" android:text=\"Roman to Decimal Number\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> <EditText android:id=\"@+id/roman_et\" android:layout_width=\"150dp\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:layout_marginTop=\"10dp\" android:capitalize=\"characters\" /> <Button android:id=\"@+id/convert_to_decimal\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:layout_marginTop=\"10dp\" android:backgroundTint=\"#A1F6EE\" android:text=\"Convert to decimal \" /> <TextView android:id=\"@+id/decimal_tv\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center_horizontal\" android:textSize=\"20sp\" /> </LinearLayout>", "e": 29558, "s": 26486, "text": null }, { "code": null, "e": 29615, "s": 29562, "text": "After writing this much code our UI looks like this:" }, { "code": null, "e": 29665, "s": 29619, "text": "Step 4: Working with the MainActivity.kt file" }, { "code": null, "e": 29854, "s": 29667, "text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. " }, { "code": null, "e": 29863, "s": 29856, "text": "Kotlin" }, { "code": "import android.support.v7.app.AppCompatActivityimport android.os.Bundleimport android.widget.Toastimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Decimal to Roman convertor convert_to_roman_numeral.setOnClickListener { // check if decimal_et.text is empty or not. if (decimal_et.text.isNotEmpty()) { val number = decimal_et.text.toString().toInt() if (number <= 3999) { // int_to_Roman function convert a decimal // number to its corresponding Roman number. val roman = decimal_to_Roman(number) roman_numeral_tv.text = roman.toString() } else { Toast.makeText(this, \"please enter a number in range between 1 to 3999\",Toast.LENGTH_SHORT).show() } } else { Toast.makeText(this, \"please enter a number \", Toast.LENGTH_SHORT).show() } } // Roman to Decimal convertor. convert_to_decimal.setOnClickListener { // check if roman_et.text is empty or not. if (roman_et.text.isNotEmpty()) { val roman = roman_et.text.toString() // RomanToDecimal function convert a Roman number // to its corresponding decimal number. decimal_tv.text = RomanToDecimal(roman).toString() } else { Toast.makeText(this, \"please enter a Roman Numeral \", Toast.LENGTH_SHORT).show() } } } private fun decimal_to_Roman(num: Int): Any { val m = arrayOf(\"\", \"M\", \"MM\", \"MMM\") val c = arrayOf( \"\", \"C\", \"CC\", \"CCC\", \"CD\", \"D\", \"DC\", \"DCC\", \"DCCC\", \"CM\" ) val x = arrayOf( \"\", \"X\", \"XX\", \"XXX\", \"XL\", \"L\", \"LX\", \"LXX\", \"LXXX\", \"XC\" ) val i = arrayOf( \"\", \"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VIII\", \"IX\" ) // Converting to roman val thousands = m[num / 1000] val hundreds = c[num % 1000 / 100] val tens = x[num % 100 / 10] val ones = i[num % 10] return thousands + hundreds + tens + ones } fun value(r: Char): Int { if (r == 'I') return 1 if (r == 'V') return 5 if (r == 'X') return 10 if (r == 'L') return 50 if (r == 'C') return 100 if (r == 'D') return 500 return if (r == 'M') 1000 else -1 } // Finds decimal value of a // given roman numeral fun RomanToDecimal(str: String): Int { // Initialize result var res = 0 var i = 0 while (i < str.length) { // Getting value of symbol s[i] val s1 = value(str[i]) // Getting value of symbol s[i+1] if (i + 1 < str.length) { val s2 = value(str[i + 1]) // Comparing both values if (s1 >= s2) { // Value of current symbol // is greater or equalto // the next symbol res = res + s1 } else { // Value of current symbol is // less than the next symbol res = res + s2 - s1 i++ } } else { res = res + s1 } i++ } return res }}", "e": 33476, "s": 29863, "text": null }, { "code": null, "e": 33488, "s": 33480, "text": "Output:" }, { "code": null, "e": 33505, "s": 33492, "text": "simmytarika5" }, { "code": null, "e": 33522, "s": 33505, "text": "surinderdawra388" }, { "code": null, "e": 33530, "s": 33522, "text": "Android" }, { "code": null, "e": 33537, "s": 33530, "text": "How To" }, { "code": null, "e": 33544, "s": 33537, "text": "Kotlin" }, { "code": null, "e": 33552, "s": 33544, "text": "Android" }, { "code": null, "e": 33650, "s": 33552, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33689, "s": 33650, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 33731, "s": 33689, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 33769, "s": 33731, "text": "Android Listview in Java with Example" }, { "code": null, "e": 33842, "s": 33769, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 33892, "s": 33842, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 33924, "s": 33892, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 33977, "s": 33924, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 34004, "s": 33977, "text": "How to Align Text in HTML?" }, { "code": null, "e": 34048, "s": 34004, "text": "How to install Jupyter Notebook on Windows?" } ]
Adding labels to points plotted on world map in R - GeeksforGeeks
17 Jun, 2021 In this article, we are going to see how to add labels to points plotted on the world map in R Programming Language. Maps: The “maps” package in R is used to draw and display geographical maps. It contains various databases for denoting countries, continents and seas. The package can be installed and loaded into the working space using the following command : install.packages("maps") The package contains the ‘world’ database, which contains descriptive images of continents and it no longer contains lakes and lake islands. The map function of this package is used to draw lines and polygons as specified by a map database, which incorporates the geographical map. map(database = “world”) The data can be specified in the form of latitudes and longitudes and the names of the cities. The text can then be annotated over this plot using the text() method. It can be customized with various attributes to improve readability and enhance the graphics. R # Load required librarieslibrary(maps) # capturing data of citiesdata_frame <- data.frame(name = c("Greece" , "France" , "Nigeria"), latitude = c(38.0,46.0,7.0), longitude = c(23.7,2.0,6.0))map(database = "world") # marking points on maptext(x = data_frame$longitude, y = data_frame$latitude, data_frame$name, pos = 1, col = "magenta") Output The “rworldmap” can be used for mapping global data and also enables the mapping of country-level and gridded user datasets. It can be downloaded and installed into the working space by the following command : install.packages("rworldmap") The getMap() method can be used to access maps stored in the package. getMap(resolution = “coarse”) The plot() method is used to plot the world map over an opened graphical device. It can be customized to add color to the plot and specify the dimensions of the plotting device. plot (worldMap , col = , border = ) The points() can be added by the specification of longitude, latitude coordinates. The text() method can be used to annotate these points using the text() method. Syntax: text ( x , y , names, col = ) Arguments : x, y: The x and y coordinates respectively. names: The names to be assigned equivalent to the x and y coordinates. col: The colour used to annotate the points. R # load librarylibrary(rworldmap) # get world mapworldmap <- getMap(resolution = "coarse") # plot world mapplot(worldmap, col = "lightgrey", fill = T, border = "darkgray", xlim = c(-180, 180), ylim = c(-90, 90), bg = "aliceblue" ) # defining data framedata_frame <- data.frame(name = c("Greece" , "France" , "Nigeria"), latitude = c(38.0,46.0,7.0), longitude = c(23.7,2.0,6.0)) # marking the points in the map points(x = data_frame$longitude, y = data_frame$latitude) # adding text to map text(x = data_frame$longitude, y = data_frame$latitude, data_frame$name, pos = 4, col = "blue") Output Picked R-Packages R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? How to change the order of bars in bar chart in R ?
[ { "code": null, "e": 24851, "s": 24823, "text": "\n17 Jun, 2021" }, { "code": null, "e": 24969, "s": 24851, "text": "In this article, we are going to see how to add labels to points plotted on the world map in R Programming Language. " }, { "code": null, "e": 25215, "s": 24969, "text": "Maps: The “maps” package in R is used to draw and display geographical maps. It contains various databases for denoting countries, continents and seas. The package can be installed and loaded into the working space using the following command : " }, { "code": null, "e": 25240, "s": 25215, "text": "install.packages(\"maps\")" }, { "code": null, "e": 25523, "s": 25240, "text": "The package contains the ‘world’ database, which contains descriptive images of continents and it no longer contains lakes and lake islands. The map function of this package is used to draw lines and polygons as specified by a map database, which incorporates the geographical map. " }, { "code": null, "e": 25547, "s": 25523, "text": "map(database = “world”)" }, { "code": null, "e": 25808, "s": 25547, "text": "The data can be specified in the form of latitudes and longitudes and the names of the cities. The text can then be annotated over this plot using the text() method. It can be customized with various attributes to improve readability and enhance the graphics. " }, { "code": null, "e": 25810, "s": 25808, "text": "R" }, { "code": "# Load required librarieslibrary(maps) # capturing data of citiesdata_frame <- data.frame(name = c(\"Greece\" , \"France\" , \"Nigeria\"), latitude = c(38.0,46.0,7.0), longitude = c(23.7,2.0,6.0))map(database = \"world\") # marking points on maptext(x = data_frame$longitude, y = data_frame$latitude, data_frame$name, pos = 1, col = \"magenta\")", "e": 26201, "s": 25810, "text": null }, { "code": null, "e": 26208, "s": 26201, "text": "Output" }, { "code": null, "e": 26419, "s": 26208, "text": "The “rworldmap” can be used for mapping global data and also enables the mapping of country-level and gridded user datasets. It can be downloaded and installed into the working space by the following command : " }, { "code": null, "e": 26449, "s": 26419, "text": "install.packages(\"rworldmap\")" }, { "code": null, "e": 26520, "s": 26449, "text": "The getMap() method can be used to access maps stored in the package. " }, { "code": null, "e": 26550, "s": 26520, "text": "getMap(resolution = “coarse”)" }, { "code": null, "e": 26729, "s": 26550, "text": "The plot() method is used to plot the world map over an opened graphical device. It can be customized to add color to the plot and specify the dimensions of the plotting device. " }, { "code": null, "e": 26765, "s": 26729, "text": "plot (worldMap , col = , border = )" }, { "code": null, "e": 26929, "s": 26765, "text": "The points() can be added by the specification of longitude, latitude coordinates. The text() method can be used to annotate these points using the text() method. " }, { "code": null, "e": 26967, "s": 26929, "text": "Syntax: text ( x , y , names, col = )" }, { "code": null, "e": 26980, "s": 26967, "text": "Arguments : " }, { "code": null, "e": 27024, "s": 26980, "text": "x, y: The x and y coordinates respectively." }, { "code": null, "e": 27095, "s": 27024, "text": "names: The names to be assigned equivalent to the x and y coordinates." }, { "code": null, "e": 27140, "s": 27095, "text": "col: The colour used to annotate the points." }, { "code": null, "e": 27142, "s": 27140, "text": "R" }, { "code": "# load librarylibrary(rworldmap) # get world mapworldmap <- getMap(resolution = \"coarse\") # plot world mapplot(worldmap, col = \"lightgrey\", fill = T, border = \"darkgray\", xlim = c(-180, 180), ylim = c(-90, 90), bg = \"aliceblue\" ) # defining data framedata_frame <- data.frame(name = c(\"Greece\" , \"France\" , \"Nigeria\"), latitude = c(38.0,46.0,7.0), longitude = c(23.7,2.0,6.0)) # marking the points in the map points(x = data_frame$longitude, y = data_frame$latitude) # adding text to map text(x = data_frame$longitude, y = data_frame$latitude, data_frame$name, pos = 4, col = \"blue\")", "e": 27801, "s": 27142, "text": null }, { "code": null, "e": 27808, "s": 27801, "text": "Output" }, { "code": null, "e": 27815, "s": 27808, "text": "Picked" }, { "code": null, "e": 27826, "s": 27815, "text": "R-Packages" }, { "code": null, "e": 27837, "s": 27826, "text": "R Language" }, { "code": null, "e": 27935, "s": 27837, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27944, "s": 27935, "text": "Comments" }, { "code": null, "e": 27957, "s": 27944, "text": "Old Comments" }, { "code": null, "e": 28009, "s": 27957, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28047, "s": 28009, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28082, "s": 28047, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28140, "s": 28082, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28189, "s": 28140, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28232, "s": 28189, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28282, "s": 28232, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 28299, "s": 28282, "text": "R - if statement" }, { "code": null, "e": 28336, "s": 28299, "text": "How to import an Excel File into R ?" } ]
Power BI Functions — (List.MaxN, R-slice_max, TOPN) | by Peter Hui | Towards Data Science
Top N by groups. I personally think it’s a very underrated way of exploring data. It’s like a saw, you just want to saw off the first few rows of a data set for analysis. I’m sure you have had to group summaries before, but you can also do some cool EDA with it using Power BI. If you are able to group the data you have, get the difference of the top 2 items by the group, you almost always find something interesting there. Sometimes the “magic” happens when you see a big difference between specific groups and you begin asking yourself why. Here in this article, I want to lay out a few methods you can use to get Top N by any grouping - Use Power Query’s List.MaxN to get the top n by groups.Use top_n / slice_max in R — incorporate that into a Power Query scriptUse visuals and filters to get Top N by groups.Use a calculated column to get Top N by groups.(combination of COUNTROWS, ALLEXCEPT and EARLIER) Use Power Query’s List.MaxN to get the top n by groups. Use top_n / slice_max in R — incorporate that into a Power Query script Use visuals and filters to get Top N by groups. Use a calculated column to get Top N by groups.(combination of COUNTROWS, ALLEXCEPT and EARLIER) Let’s take a look at the function in Power BI, you know I love Power Query, so let’s start there. I have a simple table here — a list of units by company. Basically, I want to rejig this simple data frame into a table that has 2 rows of each company. Company A should display 21 and 4. Company B should display 44 and 33 and finally, Company C should display 66 and 22. If you use power query, you gotta love the group by function :) There is one problem though — the group by feature here only allows you to group by Max, Sum and Count, etc but doesn’t allow you to display the Max 2 by group, or Max 3 by group and so on. What do you do? Hmm.. let’s still use the group by and use the Max for now. Summarizing by Max only provides a summary like this. It’s not exactly what we want. We want top 2 by group. ( Top 2 by company A, B,C) Here is a tip — you may not know every Power Query functions, that’s okay, you just need to use the UI to get you close to where you need to go and then tweak it from there. Here I will tweak the List.Max function. Instead of List.Max, I now used List.MaxN and add 2 in the parameter. List.MaxN takes a list as input and a count as a second input. Here we have the [Units] as a list and 2 is the N number we wish to return. Now it returns a list of the 2 max values by group. We will expand this column though, so we can do this by copying the result into a new column. Let’s expand it and it’ll get us to what we want. Simple right? We now have top 2 by [Company]. You can also do the same by running an R script. You can do this via Transform > Run R Script. You will need to have R downloaded first. This is where you can find some info on downloading it. To run the R script — select the Run R script ribbon and it will give you an empty dialogue box. Here, you will need to load your R package and run the script. This message at the top is saying the current table is called “dataset”. Let’s add in our script. I love the Tidyverse — here the script reads, Load the dplyr package. Take the dataset, group it by Company, then take the top_n or top 2 in this case of each group and return it in a table called “New” and ta da! Side note: you can also use slice_max which is the most current function since top_n has been superseded. You can just replace top_n with slice_max How about top n without Power Query and just straight in Power BI? If you want the Top 2 for each company, you can simply drag in the columns of company and units into the visualization pane using the table visual. Step 1 — After you have loaded in your data — select the table visual. Step 2 — put in the columns [Company] and [Units]. I jazzed it up a bit using the table styles. Step 3 — Select Top N and input 2 since we want to see the top 2 by group and the value being evaluated is [Units]. You will get this — Wait a minute — that doesn’t make sense! I want the top 2 by group, not all of the groups. This is the great thing about Power BI — you can add in a filter to change the context of the entire visual. ( A single visual, single page or all pages for that matter) Select a company and it will give you the top 2 in [Company] A, B or C. On the side panels, if you prefer, you can use those buckets as filters as well if you don’t want the filters to be displayed on the page itself. Now another way of doing this is using COUNTROWS and display this as a calculated column. I always believe that calculated columns should be done for categories you want to slice and dice by. Here is an article if that helps. Here, we can slice and dice by the ranking of 1 and 2. I’ll insert a new column using the below formula. Ranking_Column = CALCULATE( COUNTROWS('Table (3)'), FILTER( ALLEXCEPT('Table (3)','Table (3)'[Company]), 'Table (3)'[Units] >= EARLIER('Table (3)'[Units])) ) It’s a bit complicated — but these are the functions you will need to know. COUNTROWS — it counts rows. ALLEXCEPT — it’s a grouping function, if you use it for ‘Table (3)’[Company], it will group the [Company] column for measures you will use. EARLIER — it’s somewhat like R lag function but not exactly, since the order of the evaluation doesn’t change the the value of the column is sorted. FILTER — returns a table, according to your filter conditions. In Power BI, when you see a FILTER function, read it from there first. Here the script reads, Return a table that creates a grouping of [Company] using ALLEXCEPT and compare the [Units] using EARLIER. Then count the rows of the units column of units that have the same value or more using COUNTROWS. The result once filtered will give you this. You can then build measures based on the ranking of 1 and 2 and go from there. What do I do with this? Ask yourself — at your work and the dataset you deal with, did you only take the max or min of a group summarized it, and reported it? Maybe comparing the top 2 will give you something interesting. There you have it — a simple Top n analysis using Power Query, R, and Power BI. Thank you everyone for the claps and ‘Hello’ to all the new followers :) I hope to write these articles every 2 weeks or so. I learn a lot from writing these and I hope you learn something from them too. Be safe! Take care of yourself and good luck with your data journey!
[ { "code": null, "e": 325, "s": 47, "text": "Top N by groups. I personally think it’s a very underrated way of exploring data. It’s like a saw, you just want to saw off the first few rows of a data set for analysis. I’m sure you have had to group summaries before, but you can also do some cool EDA with it using Power BI." }, { "code": null, "e": 592, "s": 325, "text": "If you are able to group the data you have, get the difference of the top 2 items by the group, you almost always find something interesting there. Sometimes the “magic” happens when you see a big difference between specific groups and you begin asking yourself why." }, { "code": null, "e": 689, "s": 592, "text": "Here in this article, I want to lay out a few methods you can use to get Top N by any grouping -" }, { "code": null, "e": 959, "s": 689, "text": "Use Power Query’s List.MaxN to get the top n by groups.Use top_n / slice_max in R — incorporate that into a Power Query scriptUse visuals and filters to get Top N by groups.Use a calculated column to get Top N by groups.(combination of COUNTROWS, ALLEXCEPT and EARLIER)" }, { "code": null, "e": 1015, "s": 959, "text": "Use Power Query’s List.MaxN to get the top n by groups." }, { "code": null, "e": 1087, "s": 1015, "text": "Use top_n / slice_max in R — incorporate that into a Power Query script" }, { "code": null, "e": 1135, "s": 1087, "text": "Use visuals and filters to get Top N by groups." }, { "code": null, "e": 1232, "s": 1135, "text": "Use a calculated column to get Top N by groups.(combination of COUNTROWS, ALLEXCEPT and EARLIER)" }, { "code": null, "e": 1330, "s": 1232, "text": "Let’s take a look at the function in Power BI, you know I love Power Query, so let’s start there." }, { "code": null, "e": 1387, "s": 1330, "text": "I have a simple table here — a list of units by company." }, { "code": null, "e": 1483, "s": 1387, "text": "Basically, I want to rejig this simple data frame into a table that has 2 rows of each company." }, { "code": null, "e": 1602, "s": 1483, "text": "Company A should display 21 and 4. Company B should display 44 and 33 and finally, Company C should display 66 and 22." }, { "code": null, "e": 1666, "s": 1602, "text": "If you use power query, you gotta love the group by function :)" }, { "code": null, "e": 1856, "s": 1666, "text": "There is one problem though — the group by feature here only allows you to group by Max, Sum and Count, etc but doesn’t allow you to display the Max 2 by group, or Max 3 by group and so on." }, { "code": null, "e": 1872, "s": 1856, "text": "What do you do?" }, { "code": null, "e": 1986, "s": 1872, "text": "Hmm.. let’s still use the group by and use the Max for now. Summarizing by Max only provides a summary like this." }, { "code": null, "e": 2068, "s": 1986, "text": "It’s not exactly what we want. We want top 2 by group. ( Top 2 by company A, B,C)" }, { "code": null, "e": 2242, "s": 2068, "text": "Here is a tip — you may not know every Power Query functions, that’s okay, you just need to use the UI to get you close to where you need to go and then tweak it from there." }, { "code": null, "e": 2353, "s": 2242, "text": "Here I will tweak the List.Max function. Instead of List.Max, I now used List.MaxN and add 2 in the parameter." }, { "code": null, "e": 2416, "s": 2353, "text": "List.MaxN takes a list as input and a count as a second input." }, { "code": null, "e": 2492, "s": 2416, "text": "Here we have the [Units] as a list and 2 is the N number we wish to return." }, { "code": null, "e": 2544, "s": 2492, "text": "Now it returns a list of the 2 max values by group." }, { "code": null, "e": 2638, "s": 2544, "text": "We will expand this column though, so we can do this by copying the result into a new column." }, { "code": null, "e": 2688, "s": 2638, "text": "Let’s expand it and it’ll get us to what we want." }, { "code": null, "e": 2734, "s": 2688, "text": "Simple right? We now have top 2 by [Company]." }, { "code": null, "e": 2783, "s": 2734, "text": "You can also do the same by running an R script." }, { "code": null, "e": 2927, "s": 2783, "text": "You can do this via Transform > Run R Script. You will need to have R downloaded first. This is where you can find some info on downloading it." }, { "code": null, "e": 3024, "s": 2927, "text": "To run the R script — select the Run R script ribbon and it will give you an empty dialogue box." }, { "code": null, "e": 3087, "s": 3024, "text": "Here, you will need to load your R package and run the script." }, { "code": null, "e": 3160, "s": 3087, "text": "This message at the top is saying the current table is called “dataset”." }, { "code": null, "e": 3185, "s": 3160, "text": "Let’s add in our script." }, { "code": null, "e": 3231, "s": 3185, "text": "I love the Tidyverse — here the script reads," }, { "code": null, "e": 3255, "s": 3231, "text": "Load the dplyr package." }, { "code": null, "e": 3388, "s": 3255, "text": "Take the dataset, group it by Company, then take the top_n or top 2 in this case of each group and return it in a table called “New”" }, { "code": null, "e": 3399, "s": 3388, "text": "and ta da!" }, { "code": null, "e": 3547, "s": 3399, "text": "Side note: you can also use slice_max which is the most current function since top_n has been superseded. You can just replace top_n with slice_max" }, { "code": null, "e": 3614, "s": 3547, "text": "How about top n without Power Query and just straight in Power BI?" }, { "code": null, "e": 3762, "s": 3614, "text": "If you want the Top 2 for each company, you can simply drag in the columns of company and units into the visualization pane using the table visual." }, { "code": null, "e": 3833, "s": 3762, "text": "Step 1 — After you have loaded in your data — select the table visual." }, { "code": null, "e": 3929, "s": 3833, "text": "Step 2 — put in the columns [Company] and [Units]. I jazzed it up a bit using the table styles." }, { "code": null, "e": 4045, "s": 3929, "text": "Step 3 — Select Top N and input 2 since we want to see the top 2 by group and the value being evaluated is [Units]." }, { "code": null, "e": 4065, "s": 4045, "text": "You will get this —" }, { "code": null, "e": 4156, "s": 4065, "text": "Wait a minute — that doesn’t make sense! I want the top 2 by group, not all of the groups." }, { "code": null, "e": 4326, "s": 4156, "text": "This is the great thing about Power BI — you can add in a filter to change the context of the entire visual. ( A single visual, single page or all pages for that matter)" }, { "code": null, "e": 4398, "s": 4326, "text": "Select a company and it will give you the top 2 in [Company] A, B or C." }, { "code": null, "e": 4544, "s": 4398, "text": "On the side panels, if you prefer, you can use those buckets as filters as well if you don’t want the filters to be displayed on the page itself." }, { "code": null, "e": 4634, "s": 4544, "text": "Now another way of doing this is using COUNTROWS and display this as a calculated column." }, { "code": null, "e": 4825, "s": 4634, "text": "I always believe that calculated columns should be done for categories you want to slice and dice by. Here is an article if that helps. Here, we can slice and dice by the ranking of 1 and 2." }, { "code": null, "e": 4875, "s": 4825, "text": "I’ll insert a new column using the below formula." }, { "code": null, "e": 5059, "s": 4875, "text": "Ranking_Column = CALCULATE( COUNTROWS('Table (3)'), FILTER( ALLEXCEPT('Table (3)','Table (3)'[Company]), 'Table (3)'[Units] >= EARLIER('Table (3)'[Units])) )" }, { "code": null, "e": 5135, "s": 5059, "text": "It’s a bit complicated — but these are the functions you will need to know." }, { "code": null, "e": 5163, "s": 5135, "text": "COUNTROWS — it counts rows." }, { "code": null, "e": 5303, "s": 5163, "text": "ALLEXCEPT — it’s a grouping function, if you use it for ‘Table (3)’[Company], it will group the [Company] column for measures you will use." }, { "code": null, "e": 5452, "s": 5303, "text": "EARLIER — it’s somewhat like R lag function but not exactly, since the order of the evaluation doesn’t change the the value of the column is sorted." }, { "code": null, "e": 5515, "s": 5452, "text": "FILTER — returns a table, according to your filter conditions." }, { "code": null, "e": 5609, "s": 5515, "text": "In Power BI, when you see a FILTER function, read it from there first. Here the script reads," }, { "code": null, "e": 5815, "s": 5609, "text": "Return a table that creates a grouping of [Company] using ALLEXCEPT and compare the [Units] using EARLIER. Then count the rows of the units column of units that have the same value or more using COUNTROWS." }, { "code": null, "e": 5860, "s": 5815, "text": "The result once filtered will give you this." }, { "code": null, "e": 5939, "s": 5860, "text": "You can then build measures based on the ranking of 1 and 2 and go from there." }, { "code": null, "e": 5963, "s": 5939, "text": "What do I do with this?" }, { "code": null, "e": 6161, "s": 5963, "text": "Ask yourself — at your work and the dataset you deal with, did you only take the max or min of a group summarized it, and reported it? Maybe comparing the top 2 will give you something interesting." }, { "code": null, "e": 6241, "s": 6161, "text": "There you have it — a simple Top n analysis using Power Query, R, and Power BI." }, { "code": null, "e": 6314, "s": 6241, "text": "Thank you everyone for the claps and ‘Hello’ to all the new followers :)" }, { "code": null, "e": 6445, "s": 6314, "text": "I hope to write these articles every 2 weeks or so. I learn a lot from writing these and I hope you learn something from them too." } ]
TestNG - Exception Test
TestNG provides an option of tracing the exception handling of code. You can test whether a code throws a desired exception or not. Here the expectedExceptions parameter is used along with the @Test annotation. Now, let's see @Test(expectedExceptions) in action. Create a java class to be tested, say, MessageUtil.java in /work/testng/src. Add an error condition inside the printMessage() method. /* * This class prints the given message on console. */ public class MessageUtil { private String message; //Constructor //@param message to be printed public MessageUtil(String message) { this.message = message; } // prints the message public void printMessage() { System.out.println(message); int a =0; int b = 1/a; } // add "Hi!" to the message public String salutationMessage() { message = "Hi!" + message; System.out.println(message); return message; } } Create a java test class, say, ExpectedExceptionTest.java in /work/testng/src. Create a java test class, say, ExpectedExceptionTest.java in /work/testng/src. Add an expected exception ArithmeticException to the testPrintMessage() test case. Add an expected exception ArithmeticException to the testPrintMessage() test case. Following are the contents of ExpectedExceptionTest.java. import org.testng.Assert; import org.testng.annotations.Test; public class ExpectedExceptionTest { String message = "Manisha"; MessageUtil messageUtil = new MessageUtil(message); @Test(expectedExceptions = ArithmeticException.class) public void testPrintMessage() { System.out.println("Inside testPrintMessage()"); messageUtil.printMessage(); } @Test public void testSalutationMessage() { System.out.println("Inside testSalutationMessage()"); message = "Hi!" + "Manisha"; Assert.assertEquals(message,messageUtil.salutationMessage()); } } Create testng.xml in /work/testng/src to execute test case(s). <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > <suite name = "Suite1"> <test name = "test1"> <classes> <class name = "ExpectedExceptionTest" /> </classes> </test> </suite> Compile the MessageUtil, Test case classes using javac. /work/testng/src$ javac MessageUtil.java TestJunit.java Now, run the Test Runner, which will run test cases defined in the provided Test Case class. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. testPrintMessage() test case will be passed. Inside testPrintMessage() Manisha Inside testSalutationMessage() Hi!Manisha =============================================== Suite1 Total tests run: 2, Failures: 0, Skips: 0 =============================================== 38 Lectures 4.5 hours Lets Kode It 15 Lectures 1.5 hours Quaatso Learning 28 Lectures 3 hours Dezlearn Education Print Add Notes Bookmark this page
[ { "code": null, "e": 2323, "s": 2060, "text": "TestNG provides an option of tracing the exception handling of code. You can test whether a code throws a desired exception or not. Here the expectedExceptions parameter is used along with the @Test annotation. Now, let's see @Test(expectedExceptions) in action." }, { "code": null, "e": 2457, "s": 2323, "text": "Create a java class to be tested, say, MessageUtil.java in /work/testng/src. Add an error condition inside the printMessage() method." }, { "code": null, "e": 2996, "s": 2457, "text": "/*\n* This class prints the given message on console.\n*/\npublic class MessageUtil {\n\n private String message;\n\n //Constructor\n //@param message to be printed\n public MessageUtil(String message) {\n this.message = message;\n }\n\n // prints the message\n public void printMessage() {\n System.out.println(message);\n int a =0;\n int b = 1/a;\n }\n\n // add \"Hi!\" to the message\n public String salutationMessage() {\n message = \"Hi!\" + message;\n System.out.println(message);\n return message;\n }\n}" }, { "code": null, "e": 3075, "s": 2996, "text": "Create a java test class, say, ExpectedExceptionTest.java in /work/testng/src." }, { "code": null, "e": 3154, "s": 3075, "text": "Create a java test class, say, ExpectedExceptionTest.java in /work/testng/src." }, { "code": null, "e": 3238, "s": 3154, "text": "Add an expected exception ArithmeticException to the testPrintMessage() test case." }, { "code": null, "e": 3322, "s": 3238, "text": "Add an expected exception ArithmeticException to the testPrintMessage() test case." }, { "code": null, "e": 3380, "s": 3322, "text": "Following are the contents of ExpectedExceptionTest.java." }, { "code": null, "e": 3975, "s": 3380, "text": "import org.testng.Assert;\nimport org.testng.annotations.Test;\n\npublic class ExpectedExceptionTest {\n String message = \"Manisha\";\n MessageUtil messageUtil = new MessageUtil(message);\n\n @Test(expectedExceptions = ArithmeticException.class)\n public void testPrintMessage() {\n System.out.println(\"Inside testPrintMessage()\");\n messageUtil.printMessage();\n }\n\n @Test\n public void testSalutationMessage() {\n System.out.println(\"Inside testSalutationMessage()\");\n message = \"Hi!\" + \"Manisha\";\n Assert.assertEquals(message,messageUtil.salutationMessage());\n }\n}" }, { "code": null, "e": 4038, "s": 3975, "text": "Create testng.xml in /work/testng/src to execute test case(s)." }, { "code": null, "e": 4294, "s": 4038, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\" >\n\n<suite name = \"Suite1\">\n <test name = \"test1\">\n <classes>\n <class name = \"ExpectedExceptionTest\" />\n </classes>\n </test>\n</suite>" }, { "code": null, "e": 4350, "s": 4294, "text": "Compile the MessageUtil, Test case classes using javac." }, { "code": null, "e": 4407, "s": 4350, "text": "/work/testng/src$ javac MessageUtil.java TestJunit.java\n" }, { "code": null, "e": 4500, "s": 4407, "text": "Now, run the Test Runner, which will run test cases defined in the provided Test Case class." }, { "code": null, "e": 4553, "s": 4500, "text": "/work/testng/src$ java org.testng.TestNG testng.xml\n" }, { "code": null, "e": 4617, "s": 4553, "text": "Verify the output. testPrintMessage() test case will be passed." }, { "code": null, "e": 4840, "s": 4617, "text": "Inside testPrintMessage()\nManisha\nInside testSalutationMessage()\nHi!Manisha\n\n===============================================\nSuite1\nTotal tests run: 2, Failures: 0, Skips: 0\n===============================================\n" }, { "code": null, "e": 4875, "s": 4840, "text": "\n 38 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4889, "s": 4875, "text": " Lets Kode It" }, { "code": null, "e": 4924, "s": 4889, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4942, "s": 4924, "text": " Quaatso Learning" }, { "code": null, "e": 4975, "s": 4942, "text": "\n 28 Lectures \n 3 hours \n" }, { "code": null, "e": 4995, "s": 4975, "text": " Dezlearn Education" }, { "code": null, "e": 5002, "s": 4995, "text": " Print" }, { "code": null, "e": 5013, "s": 5002, "text": " Add Notes" } ]
Ruby on Rails - Installation
To develop a web application using Ruby on Rails Framework, you need to install the following software − Ruby The Rails Framework A Web Server A Database System We assume that you already have installed a Web Server and a Database System on your computer. You can use the WEBrick Web Server, which comes with Ruby. Most websites however use Apache or lightTPD web servers in production. Rails works with many database systems, including MySQL, PostgreSQL, SQLite, Oracle, DB2 and SQL Server. Please refer to a corresponding Database System Setup manual to set up your database. Let's look at the installation instructions for Rails on Windows and Linux. Follow the steps given below for installing Ruby on Rails. First, check if you already have Ruby installed. Open the command prompt and type ruby -v. If Ruby responds, and if it shows a version number at or above 2.2.2, then type gem --version. If you don't get an error, skip Install Ruby step. Otherwise, we'll install a fresh Ruby. If Ruby is not installed, then download an installation package from rubyinstaller.org. Follow the download link, and run the resulting installer. This is an exe file rubyinstaller-2.2.2.x.exe and will be installed in a single click. It's a very small package, and you'll get RubyGems as well along with this package. Please check the Release Notes for more detail. Install Rails − With Rubygems loaded, you can install all of Rails and its dependencies using the following command through the command line − C:\> gem install rails Note − The above command may take some time to install all dependencies. Make sure you are connected to the internet while installing gems dependencies. Use the following command to check the rails version. C:\> rails -v Output Rails 4.2.4 Congratulations! You are now on Rails over Windows. We are installing Ruby On Rails on Linux using rbenv. It is a lightweight Ruby Version Management Tool. The rbenv provides an easy installation procedure to manage various versions of Ruby, and a solid environment for developing Ruby on Rails applications. Follow the steps given below to install Ruby on Rails using rbenv tool. First of all, we have to install git - core and some ruby dependences that help to install Ruby on Rails. Use the following command for installing Rails dependencies using yum. tp> sudo yum install -y git-core zlib zlib-devel gcc-c++ patch readline readline-devel libyaml-devel libffi-devel openssl-devel make bzip2 autoconf automake libtool bison curl sqlite-devel Now we will install rbenv and set the appropriate environment variables. Use the following set of commands to get rbenv for git repository. tp> git clone git://github.com/sstephenson/rbenv.git .rbenv tp> echo 'export PATH = "$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile tp> echo 'eval "$(rbenv init -)"' >> ~/.bash_profile tp> exec $SHELL tp> git clone git://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build tp> echo 'export PATH = "$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' << ~/.bash_profile tp> exec $SHELL Before installing Ruby, determine which version of Ruby you want to install. We will install Ruby 2.2.3. Use the following command for installing Ruby. tp> rbenv install -v 2.2.3 Use the following command for setting up the current Ruby version as default. tp> rbenv global 2.2.3 Use the following command to verify the Ruby version. tp> ruby -v Output ruby 2.2.3p173 (2015-08-18 revivion 51636) [X86_64-linux] Ruby provides a keyword gem for installing the supported dependencies; we call them gems. If you don't want to install the documentation for Ruby-gems, then use the following command. tp> echo "gem: --no-document" > ~/.gemrc Thereafter, it is better to install the Bundler gem, because it helps to manage your application dependencies. Use the following command to install bundler gem. tp> gem install bundler Use the following command for installing Rails version 4.2.4. tp> install rails -v 4.2.4 Use the following command to make Rails executable available. tp> rbenv rehash Use the following command for checking the rails version. tp> rails -v Output tp> Rails 4.2.4 Ruby on Rails framework requires JavaScript Runtime Environment (Node.js) to manage the features of Rails. Next, we will see how we can use Node.js to manage Asset Pipeline which is a Rails feature. Let us install Node.js from the Yum repository. We will take Node.js from EPEL yum repository. Use the following command to add the EPEL package to the yum repository. tp> sudo yum -y install epel-release Use the following command for installing the Node.js package. tp> sudo yum install nodejs Congratulations! You are now on Rails over Linux. By default, Rails uses sqlite3, but you may want to install MySQL, PostgreSQL, or other RDBMS. This is optional; if you have the database installed, then you may skip this step and it is not mandatory that you have a database installed to start the rails server. For this tutorial, we are using PostgreSQL database. Therefore use the following commands to install PostgreSQL. tp> sudo yum install postgresql-server postgresql-contrib Accept the prompt, by responding with a y. Use the following command to create a PostgreSQl database cluster. tp> sudo postgresql-setup initdb Use the following command to start and enable PostgreSQL. tp> sudo systemctl start postgresql tp> sudo systemctl enable postgresql Assuming you have installed Rails using RubyGems, keeping it up-to-date is relatively easy. We can use the same command in both Windows and Linux platform. Use the following command − tp> gem update rails Output The following screenshot shows a Windows command prompt. The Linux terminal also provides the same output. This will automatically update your Rails installation. The next time you restart your application, it will pick up this latest version of Rails. While using this command, make sure you are connected to the internet. You can verify if everything is set up according to your requirements or not. Use the following command to create a demo project. tp> rails new demo Output It will generate a demo rail project; we will discuss about it later. Currently we have to check if the environment is set up or not. Next, use the following command to run WEBrick web server on your machine. tp> cd demo tp> rails server It will generate auto-code to start the server Now open your browser and type the following − http://localhost:3000 It should display a message, something like, "Welcome aboard" or "Congratulations". Print Add Notes Bookmark this page
[ { "code": null, "e": 2208, "s": 2103, "text": "To develop a web application using Ruby on Rails Framework, you need to install the following software −" }, { "code": null, "e": 2213, "s": 2208, "text": "Ruby" }, { "code": null, "e": 2233, "s": 2213, "text": "The Rails Framework" }, { "code": null, "e": 2246, "s": 2233, "text": "A Web Server" }, { "code": null, "e": 2264, "s": 2246, "text": "A Database System" }, { "code": null, "e": 2490, "s": 2264, "text": "We assume that you already have installed a Web Server and a Database System on your computer. You can use the WEBrick Web Server, which comes with Ruby. Most websites however use Apache or lightTPD web servers in production." }, { "code": null, "e": 2681, "s": 2490, "text": "Rails works with many database systems, including MySQL, PostgreSQL, SQLite, Oracle, DB2 and SQL Server. Please refer to a corresponding Database System Setup manual to set up your database." }, { "code": null, "e": 2757, "s": 2681, "text": "Let's look at the installation instructions for Rails on Windows and Linux." }, { "code": null, "e": 2816, "s": 2757, "text": "Follow the steps given below for installing Ruby on Rails." }, { "code": null, "e": 3092, "s": 2816, "text": "First, check if you already have Ruby installed. Open the command prompt and type ruby -v. If Ruby responds, and if it shows a version number at or above 2.2.2, then type gem --version. If you don't get an error, skip Install Ruby step. Otherwise, we'll install a fresh Ruby." }, { "code": null, "e": 3458, "s": 3092, "text": "If Ruby is not installed, then download an installation package from rubyinstaller.org. Follow the download link, and run the resulting installer. This is an exe file rubyinstaller-2.2.2.x.exe and will be installed in a single click. It's a very small package, and you'll get RubyGems as well along with this package. Please check the Release Notes for more detail." }, { "code": null, "e": 3601, "s": 3458, "text": "Install Rails − With Rubygems loaded, you can install all of Rails and its dependencies using the following command through the command line −" }, { "code": null, "e": 3625, "s": 3601, "text": "C:\\> gem install rails\n" }, { "code": null, "e": 3778, "s": 3625, "text": "Note − The above command may take some time to install all dependencies. Make sure you are connected to the internet while installing gems dependencies." }, { "code": null, "e": 3832, "s": 3778, "text": "Use the following command to check the rails version." }, { "code": null, "e": 3847, "s": 3832, "text": "C:\\> rails -v\n" }, { "code": null, "e": 3854, "s": 3847, "text": "Output" }, { "code": null, "e": 3867, "s": 3854, "text": "Rails 4.2.4\n" }, { "code": null, "e": 3919, "s": 3867, "text": "Congratulations! You are now on Rails over Windows." }, { "code": null, "e": 4176, "s": 3919, "text": "We are installing Ruby On Rails on Linux using rbenv. It is a lightweight Ruby Version Management Tool. The rbenv provides an easy installation procedure to manage various versions of Ruby, and a solid environment for developing Ruby on Rails applications." }, { "code": null, "e": 4248, "s": 4176, "text": "Follow the steps given below to install Ruby on Rails using rbenv tool." }, { "code": null, "e": 4425, "s": 4248, "text": "First of all, we have to install git - core and some ruby dependences that help to install Ruby on Rails. Use the following command for installing Rails dependencies using yum." }, { "code": null, "e": 4615, "s": 4425, "text": "tp> sudo yum install -y git-core zlib zlib-devel gcc-c++ patch readline readline-devel libyaml-devel libffi-devel openssl-devel make bzip2 autoconf automake libtool bison curl sqlite-devel\n" }, { "code": null, "e": 4755, "s": 4615, "text": "Now we will install rbenv and set the appropriate environment variables. Use the following set of commands to get rbenv for git repository." }, { "code": null, "e": 5145, "s": 4755, "text": "tp> git clone git://github.com/sstephenson/rbenv.git .rbenv\ntp> echo 'export PATH = \"$HOME/.rbenv/bin:$PATH\"' >> ~/.bash_profile\ntp> echo 'eval \"$(rbenv init -)\"' >> ~/.bash_profile\ntp> exec $SHELL\n\ntp> git clone git://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build\ntp> echo 'export PATH = \"$HOME/.rbenv/plugins/ruby-build/bin:$PATH\"' << ~/.bash_profile\ntp> exec $SHELL\n" }, { "code": null, "e": 5297, "s": 5145, "text": "Before installing Ruby, determine which version of Ruby you want to install. We will install Ruby 2.2.3. Use the following command for installing Ruby." }, { "code": null, "e": 5325, "s": 5297, "text": "tp> rbenv install -v 2.2.3\n" }, { "code": null, "e": 5403, "s": 5325, "text": "Use the following command for setting up the current Ruby version as default." }, { "code": null, "e": 5427, "s": 5403, "text": "tp> rbenv global 2.2.3\n" }, { "code": null, "e": 5481, "s": 5427, "text": "Use the following command to verify the Ruby version." }, { "code": null, "e": 5494, "s": 5481, "text": "tp> ruby -v\n" }, { "code": null, "e": 5501, "s": 5494, "text": "Output" }, { "code": null, "e": 5560, "s": 5501, "text": "ruby 2.2.3p173 (2015-08-18 revivion 51636) [X86_64-linux]\n" }, { "code": null, "e": 5744, "s": 5560, "text": "Ruby provides a keyword gem for installing the supported dependencies; we call them gems. If you don't want to install the documentation for Ruby-gems, then use the following command." }, { "code": null, "e": 5786, "s": 5744, "text": "tp> echo \"gem: --no-document\" > ~/.gemrc\n" }, { "code": null, "e": 5947, "s": 5786, "text": "Thereafter, it is better to install the Bundler gem, because it helps to manage your application dependencies. Use the following command to install bundler gem." }, { "code": null, "e": 5972, "s": 5947, "text": "tp> gem install bundler\n" }, { "code": null, "e": 6034, "s": 5972, "text": "Use the following command for installing Rails version 4.2.4." }, { "code": null, "e": 6062, "s": 6034, "text": "tp> install rails -v 4.2.4\n" }, { "code": null, "e": 6124, "s": 6062, "text": "Use the following command to make Rails executable available." }, { "code": null, "e": 6142, "s": 6124, "text": "tp> rbenv rehash\n" }, { "code": null, "e": 6200, "s": 6142, "text": "Use the following command for checking the rails version." }, { "code": null, "e": 6214, "s": 6200, "text": "tp> rails -v\n" }, { "code": null, "e": 6221, "s": 6214, "text": "Output" }, { "code": null, "e": 6238, "s": 6221, "text": "tp> Rails 4.2.4\n" }, { "code": null, "e": 6437, "s": 6238, "text": "Ruby on Rails framework requires JavaScript Runtime Environment (Node.js) to manage the features of Rails. Next, we will see how we can use Node.js to manage Asset Pipeline which is a Rails feature." }, { "code": null, "e": 6605, "s": 6437, "text": "Let us install Node.js from the Yum repository. We will take Node.js from EPEL yum repository. Use the following command to add the EPEL package to the yum repository." }, { "code": null, "e": 6643, "s": 6605, "text": "tp> sudo yum -y install epel-release\n" }, { "code": null, "e": 6705, "s": 6643, "text": "Use the following command for installing the Node.js package." }, { "code": null, "e": 6734, "s": 6705, "text": "tp> sudo yum install nodejs\n" }, { "code": null, "e": 6784, "s": 6734, "text": "Congratulations! You are now on Rails over Linux." }, { "code": null, "e": 7160, "s": 6784, "text": "By default, Rails uses sqlite3, but you may want to install MySQL, PostgreSQL, or other RDBMS. This is optional; if you have the database installed, then you may skip this step and it is not mandatory that you have a database installed to start the rails server. For this tutorial, we are using PostgreSQL database. Therefore use the following commands to install PostgreSQL." }, { "code": null, "e": 7219, "s": 7160, "text": "tp> sudo yum install postgresql-server postgresql-contrib\n" }, { "code": null, "e": 7329, "s": 7219, "text": "Accept the prompt, by responding with a y. Use the following command to create a PostgreSQl database cluster." }, { "code": null, "e": 7363, "s": 7329, "text": "tp> sudo postgresql-setup initdb\n" }, { "code": null, "e": 7421, "s": 7363, "text": "Use the following command to start and enable PostgreSQL." }, { "code": null, "e": 7495, "s": 7421, "text": "tp> sudo systemctl start postgresql\ntp> sudo systemctl enable postgresql\n" }, { "code": null, "e": 7679, "s": 7495, "text": "Assuming you have installed Rails using RubyGems, keeping it up-to-date is relatively easy. We can use the same command in both Windows and Linux platform. Use the following command −" }, { "code": null, "e": 7701, "s": 7679, "text": "tp> gem update rails\n" }, { "code": null, "e": 7708, "s": 7701, "text": "Output" }, { "code": null, "e": 7815, "s": 7708, "text": "The following screenshot shows a Windows command prompt. The Linux terminal also provides the same output." }, { "code": null, "e": 8032, "s": 7815, "text": "This will automatically update your Rails installation. The next time you restart your application, it will pick up this latest version of Rails. While using this command, make sure you are connected to the internet." }, { "code": null, "e": 8162, "s": 8032, "text": "You can verify if everything is set up according to your requirements or not. Use the following command to create a demo project." }, { "code": null, "e": 8182, "s": 8162, "text": "tp> rails new demo\n" }, { "code": null, "e": 8189, "s": 8182, "text": "Output" }, { "code": null, "e": 8398, "s": 8189, "text": "It will generate a demo rail project; we will discuss about it later. Currently we have to check if the environment is set up or not. Next, use the following command to run WEBrick web server on your machine." }, { "code": null, "e": 8428, "s": 8398, "text": "tp> cd demo\ntp> rails server\n" }, { "code": null, "e": 8475, "s": 8428, "text": "It will generate auto-code to start the server" }, { "code": null, "e": 8522, "s": 8475, "text": "Now open your browser and type the following −" }, { "code": null, "e": 8545, "s": 8522, "text": "http://localhost:3000\n" }, { "code": null, "e": 8629, "s": 8545, "text": "It should display a message, something like, \"Welcome aboard\" or \"Congratulations\"." }, { "code": null, "e": 8636, "s": 8629, "text": " Print" }, { "code": null, "e": 8647, "s": 8636, "text": " Add Notes" } ]
How to use Unicode and Special Characters in Tkinter?
Sometimes we need to add unicode and special charset in our Tkinter application. We can add unicode characters in our labels or widgets concatenating the signature as, u ‘/<Unicode of Character>’. You can find the list of all unicode characters from here In this example, we will add a unicode character in the button widget. # Import the required Libraries from tkinter import * #Create an instance of tkinter frame win= Tk() win.geometry("700x200") #Create a button Button(win, text='Click'+u'\u01CF', font=('Poppins bold', 10)).pack(pady=20) #Keep running the window or frame win.mainloop() Running the above code will create a button with a unicode character (u01CF).
[ { "code": null, "e": 1317, "s": 1062, "text": "Sometimes we need to add unicode and special charset in our Tkinter application. We can add unicode characters in our labels or widgets concatenating the signature as, u ‘/<Unicode of Character>’. You can find the list of all unicode characters from here" }, { "code": null, "e": 1388, "s": 1317, "text": "In this example, we will add a unicode character in the button widget." }, { "code": null, "e": 1660, "s": 1388, "text": "# Import the required Libraries\nfrom tkinter import *\n\n#Create an instance of tkinter frame\nwin= Tk()\nwin.geometry(\"700x200\")\n\n#Create a button\n\nButton(win, text='Click'+u'\\u01CF', font=('Poppins bold',\n10)).pack(pady=20)\n\n#Keep running the window or frame\nwin.mainloop()" }, { "code": null, "e": 1738, "s": 1660, "text": "Running the above code will create a button with a unicode character (u01CF)." } ]