title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Command Line arguments in C# | If you want to pass arguments by command line, then use command line arguments in C# −
When we create a program in c#, static void main is used and we can see the arguments in it .
class HelloWorld {
static void Main(string[] args) {
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
The string[] args is a variable that has all the values passed from the command line as shown above.
Now to print those arguments, let’s say we have an argument, “One” −
Console.WriteLine("Length of the arguments: "+args.Length);
Console.WriteLine("Arguments:");
foreach (Object obj in args) {
Console.WriteLine(obj);
}
The above will print −
Length of the arguments: 1
Arguments: One | [
{
"code": null,
"e": 1149,
"s": 1062,
"text": "If you want to pass arguments by command line, then use command line arguments in C# −"
},
{
"code": null,
"e": 1243,
"s": 1149,
"text": "When we create a program in c#, static void main is used and we can see the arguments in it ."
},
{
"code": null,
"e": 1404,
"s": 1243,
"text": "class HelloWorld {\n static void Main(string[] args) {\n /* my first program in C# */\n Console.WriteLine(\"Hello World\");\n Console.ReadKey();\n }"
},
{
"code": null,
"e": 1505,
"s": 1404,
"text": "The string[] args is a variable that has all the values passed from the command line as shown above."
},
{
"code": null,
"e": 1574,
"s": 1505,
"text": "Now to print those arguments, let’s say we have an argument, “One” −"
},
{
"code": null,
"e": 1727,
"s": 1574,
"text": "Console.WriteLine(\"Length of the arguments: \"+args.Length);\nConsole.WriteLine(\"Arguments:\");\nforeach (Object obj in args) {\n Console.WriteLine(obj);\n}"
},
{
"code": null,
"e": 1750,
"s": 1727,
"text": "The above will print −"
},
{
"code": null,
"e": 1792,
"s": 1750,
"text": "Length of the arguments: 1\nArguments: One"
}
]
|
Working with Amazon S3 with Boto3. | Towards Data Science | Amazon Simple Storage Service, or S3, offers space to store, protect, and share data with finely-tuned access control. When working with Python, one can easily interact with S3 with the Boto3 package. In this post, I will put together a cheat sheet of Python commands that I use a lot when working with S3. I hope you will find it useful.
Let’s kick off with a few words about the S3 data structures. On your own computer, you store files in folders. On S3, the folders are called buckets. Inside buckets, you can store objects, such as .csv files. You can refer to buckets by their name, while to objects — by their key. To make the code chunks more tractable, we will use emojis. Here’s the key to symbols:
🗑 — a bucket’s name, e.g. “mybucket”🔑 — an object’s key, e.g. "myfile_s3_name.csv"📄 - a file's name on your computer, e.g. "myfile_local_name.csv"
Both 🗑 and 🔑 can either denote a name already existing on S3 or a name you want to give a newly created bucket or object. 📄 denotes a file you have or want to have somewhere locally on your machine.
To access any AWS service with Boto3, we have to connect to it with a client. Here, we create an S3 client. We specify the region in which our data lives. We also have to pass the access key and the password, which we can generate in the AWS console, as described here.
To list the buckets existing on S3, delete one or create a new one, we simply use the list_buckets(), create_bucket() and delete_bucket() functions, respectively.
Within a bucket, there reside objects. We can list them with list_objects(). The MaxKeys argument sets the maximum number of objects listed; it’s like calling head() on the results before printing them. We can also list only objects whose keys (names) start with a specific prefix using the Prefix argument.We can use upload_file() to upload a file called 📄 to S3 under the name 🔑. Similarly, download_file() will save a file called 🔑 on S3 locally under the name 📄.To get some metadata about an object, such as creation or modification time, permission rights or size, we can call head_object().Deleting an object works the same way as deleting a bucket: we just need to pass the bucket name and object key to delete_object().
Oftentimes, data are spread across several files. For instance, you can have sales data for different stores or regions in different CSV files with matching column names. For analytics or modeling, we might want to have all these data in a single pandas data frame. The following code chunk will do just that: download all data files in 🗑 whose name starts with “some_prefix” and put it into a single data frame.
One way to manage access rights on S3 is with access control lists or ACLs. By default, all files are private, which is the best (and safest!) practice. You can specify a file to be "public-read", in which case, everyone can access it, or "private", making yourself the only authorized person, among others. Look here for the exhaustive list of access options. You can set a file’s ACL both when it’s already on S3 using put_object_acl() as well as upon upload via passing appropriate ExtraArgs to upload_file().
You can also grant anyone short-time access to a private file by generating a temporary pre-signed URL using the generate_presigned_url() function. This will yield a string that can be inserted right into pandas’ read_csv(), for instance, to download the data. You can specify how long this temporary access link will be valid via the ExpiresIn argument. Here, we create a link valid for 1 hour (3600 seconds).
Thanks for reading!
If you liked this post, why don’t you subscribe for email updates on my new articles? And by becoming a Medium member, you can support my writing and get unlimited access to all stories by other authors and myself.
Need consulting? You can ask me anything or book me for a 1:1 here.
You can also try one of my other articles. Can’t choose? Pick one of these: | [
{
"code": null,
"e": 386,
"s": 47,
"text": "Amazon Simple Storage Service, or S3, offers space to store, protect, and share data with finely-tuned access control. When working with Python, one can easily interact with S3 with the Boto3 package. In this post, I will put together a cheat sheet of Python commands that I use a lot when working with S3. I hope you will find it useful."
},
{
"code": null,
"e": 756,
"s": 386,
"text": "Let’s kick off with a few words about the S3 data structures. On your own computer, you store files in folders. On S3, the folders are called buckets. Inside buckets, you can store objects, such as .csv files. You can refer to buckets by their name, while to objects — by their key. To make the code chunks more tractable, we will use emojis. Here’s the key to symbols:"
},
{
"code": null,
"e": 903,
"s": 756,
"text": "🗑 — a bucket’s name, e.g. “mybucket”🔑 — an object’s key, e.g. \"myfile_s3_name.csv\"📄 - a file's name on your computer, e.g. \"myfile_local_name.csv\""
},
{
"code": null,
"e": 1102,
"s": 903,
"text": "Both 🗑 and 🔑 can either denote a name already existing on S3 or a name you want to give a newly created bucket or object. 📄 denotes a file you have or want to have somewhere locally on your machine."
},
{
"code": null,
"e": 1372,
"s": 1102,
"text": "To access any AWS service with Boto3, we have to connect to it with a client. Here, we create an S3 client. We specify the region in which our data lives. We also have to pass the access key and the password, which we can generate in the AWS console, as described here."
},
{
"code": null,
"e": 1535,
"s": 1372,
"text": "To list the buckets existing on S3, delete one or create a new one, we simply use the list_buckets(), create_bucket() and delete_bucket() functions, respectively."
},
{
"code": null,
"e": 2263,
"s": 1535,
"text": "Within a bucket, there reside objects. We can list them with list_objects(). The MaxKeys argument sets the maximum number of objects listed; it’s like calling head() on the results before printing them. We can also list only objects whose keys (names) start with a specific prefix using the Prefix argument.We can use upload_file() to upload a file called 📄 to S3 under the name 🔑. Similarly, download_file() will save a file called 🔑 on S3 locally under the name 📄.To get some metadata about an object, such as creation or modification time, permission rights or size, we can call head_object().Deleting an object works the same way as deleting a bucket: we just need to pass the bucket name and object key to delete_object()."
},
{
"code": null,
"e": 2676,
"s": 2263,
"text": "Oftentimes, data are spread across several files. For instance, you can have sales data for different stores or regions in different CSV files with matching column names. For analytics or modeling, we might want to have all these data in a single pandas data frame. The following code chunk will do just that: download all data files in 🗑 whose name starts with “some_prefix” and put it into a single data frame."
},
{
"code": null,
"e": 3189,
"s": 2676,
"text": "One way to manage access rights on S3 is with access control lists or ACLs. By default, all files are private, which is the best (and safest!) practice. You can specify a file to be \"public-read\", in which case, everyone can access it, or \"private\", making yourself the only authorized person, among others. Look here for the exhaustive list of access options. You can set a file’s ACL both when it’s already on S3 using put_object_acl() as well as upon upload via passing appropriate ExtraArgs to upload_file()."
},
{
"code": null,
"e": 3600,
"s": 3189,
"text": "You can also grant anyone short-time access to a private file by generating a temporary pre-signed URL using the generate_presigned_url() function. This will yield a string that can be inserted right into pandas’ read_csv(), for instance, to download the data. You can specify how long this temporary access link will be valid via the ExpiresIn argument. Here, we create a link valid for 1 hour (3600 seconds)."
},
{
"code": null,
"e": 3620,
"s": 3600,
"text": "Thanks for reading!"
},
{
"code": null,
"e": 3835,
"s": 3620,
"text": "If you liked this post, why don’t you subscribe for email updates on my new articles? And by becoming a Medium member, you can support my writing and get unlimited access to all stories by other authors and myself."
},
{
"code": null,
"e": 3903,
"s": 3835,
"text": "Need consulting? You can ask me anything or book me for a 1:1 here."
}
]
|
High Performance Distributed Deep Learning with multiple GPUs on Google Cloud Platform — Part 2 | by Sam Black | Towards Data Science | In this multipart article, I outline how to scale your deep learning to multiple GPUs and multiple machines using Horovod, Uber’s distributed deep learning framework.
Read part one here:
samsachedina.medium.com
Unsurprisingly, getting distributed training to work correctly isn’t as straightforward. You can follow along with my steps to get your experiment loaded and training on GCP.
Package/restructure your application (see github repo here for an example)Create a docker image and load that image to Google’s Cloud RegistryCreate an instance and run your training job
Package/restructure your application (see github repo here for an example)
Create a docker image and load that image to Google’s Cloud Registry
Create an instance and run your training job
If everything was configured correctly, you should now have an easy-to-follow recipe for parallelizing your deep learning on GCP.
Horovod essentially runs your training script on multiple processes, and then uses gradient averaging. If you’re interested on how Data Parallelism/Model Parallelism work for distributed deep learning — I suggest reading this article, which is a nice summary:
towardsdatascience.com
(Thanks to Google for upping my GPU quota)
It’s a good practice to structure your project so it’s simple to run and containerize. If you’re interested in examples for how to do this, check out this repo that contains the template I use for my research projects:
github.com
You’ll need to structure your application to run as a script. This means putting all downloading and preprocessing of your data in the script. When you use Torch’s distributed training sampler, your data will automatically be distributed to each process in a non-overlapping way.
Depending on how complex your data pipeline is, it’s nice to fit this all into the same script. However, that’ll depend on your project. Some nice examples for structuring your train script are here:
github.com
Horovod runs training like so:
horovodrun -np 4 -H localhost:4 python app/run_train.py
For more information on how to run Horovod — check the link here: https://horovod.readthedocs.io/en/stable/running_include.html
Now that you’ve tested your training script locally — you should do this, you can build your container. You’ll need to make sure the container has cuda installed. To make this simple, I’ve provided an example project here — feel free to use the attached Dockerfile which has been tested to work with this example.
The instance details that I’ve provided are below. In order to use GPUs, you’ll need to select a compatible instance type: N1
If you’re deploying to multiple machines, the main machine will need to be able to SSH into each worker without a prompt. I may cover this at a later date.
When launching your instance, specify the source image as the image you’ve uploaded. This will automatically download the image and run it, saving you precious time with a potentially expensive machine.
Total training time (1 GPU): ~29 minutes
Total training time (4 GPUs): ~6 minutes
Because Horovod uses data parallelism, the time per epoch remains roughly the same. See statistics for each device in the image above.
However, since the training data is distributed to each GPU and the gradients are averaged, the number of epochs needed to converge is roughly a function of the number of GPUs.
So, previously, if we needed 100 epochs to converge with 1 GPU, we can estimate that it’ll only take ~25 (100/4) epochs to converge with 4 GPUs to around the same accuracy.
It’s not a law, so there may be some unexpected variation here. The training dynamics are definitely different. In this case, I noticed a “steeper curve,” where the error was much higher initially, and converged much faster. You’ll need to monitor the training as always to ensure there aren’t any issues with convergence.
If you’re looking for a monitoring tool and haven’t used weights and biases yet — try them out.
Thanks for reading!
If you liked this article, check out: | [
{
"code": null,
"e": 338,
"s": 171,
"text": "In this multipart article, I outline how to scale your deep learning to multiple GPUs and multiple machines using Horovod, Uber’s distributed deep learning framework."
},
{
"code": null,
"e": 358,
"s": 338,
"text": "Read part one here:"
},
{
"code": null,
"e": 382,
"s": 358,
"text": "samsachedina.medium.com"
},
{
"code": null,
"e": 557,
"s": 382,
"text": "Unsurprisingly, getting distributed training to work correctly isn’t as straightforward. You can follow along with my steps to get your experiment loaded and training on GCP."
},
{
"code": null,
"e": 744,
"s": 557,
"text": "Package/restructure your application (see github repo here for an example)Create a docker image and load that image to Google’s Cloud RegistryCreate an instance and run your training job"
},
{
"code": null,
"e": 819,
"s": 744,
"text": "Package/restructure your application (see github repo here for an example)"
},
{
"code": null,
"e": 888,
"s": 819,
"text": "Create a docker image and load that image to Google’s Cloud Registry"
},
{
"code": null,
"e": 933,
"s": 888,
"text": "Create an instance and run your training job"
},
{
"code": null,
"e": 1063,
"s": 933,
"text": "If everything was configured correctly, you should now have an easy-to-follow recipe for parallelizing your deep learning on GCP."
},
{
"code": null,
"e": 1323,
"s": 1063,
"text": "Horovod essentially runs your training script on multiple processes, and then uses gradient averaging. If you’re interested on how Data Parallelism/Model Parallelism work for distributed deep learning — I suggest reading this article, which is a nice summary:"
},
{
"code": null,
"e": 1346,
"s": 1323,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1389,
"s": 1346,
"text": "(Thanks to Google for upping my GPU quota)"
},
{
"code": null,
"e": 1608,
"s": 1389,
"text": "It’s a good practice to structure your project so it’s simple to run and containerize. If you’re interested in examples for how to do this, check out this repo that contains the template I use for my research projects:"
},
{
"code": null,
"e": 1619,
"s": 1608,
"text": "github.com"
},
{
"code": null,
"e": 1899,
"s": 1619,
"text": "You’ll need to structure your application to run as a script. This means putting all downloading and preprocessing of your data in the script. When you use Torch’s distributed training sampler, your data will automatically be distributed to each process in a non-overlapping way."
},
{
"code": null,
"e": 2099,
"s": 1899,
"text": "Depending on how complex your data pipeline is, it’s nice to fit this all into the same script. However, that’ll depend on your project. Some nice examples for structuring your train script are here:"
},
{
"code": null,
"e": 2110,
"s": 2099,
"text": "github.com"
},
{
"code": null,
"e": 2141,
"s": 2110,
"text": "Horovod runs training like so:"
},
{
"code": null,
"e": 2197,
"s": 2141,
"text": "horovodrun -np 4 -H localhost:4 python app/run_train.py"
},
{
"code": null,
"e": 2325,
"s": 2197,
"text": "For more information on how to run Horovod — check the link here: https://horovod.readthedocs.io/en/stable/running_include.html"
},
{
"code": null,
"e": 2639,
"s": 2325,
"text": "Now that you’ve tested your training script locally — you should do this, you can build your container. You’ll need to make sure the container has cuda installed. To make this simple, I’ve provided an example project here — feel free to use the attached Dockerfile which has been tested to work with this example."
},
{
"code": null,
"e": 2765,
"s": 2639,
"text": "The instance details that I’ve provided are below. In order to use GPUs, you’ll need to select a compatible instance type: N1"
},
{
"code": null,
"e": 2921,
"s": 2765,
"text": "If you’re deploying to multiple machines, the main machine will need to be able to SSH into each worker without a prompt. I may cover this at a later date."
},
{
"code": null,
"e": 3124,
"s": 2921,
"text": "When launching your instance, specify the source image as the image you’ve uploaded. This will automatically download the image and run it, saving you precious time with a potentially expensive machine."
},
{
"code": null,
"e": 3165,
"s": 3124,
"text": "Total training time (1 GPU): ~29 minutes"
},
{
"code": null,
"e": 3206,
"s": 3165,
"text": "Total training time (4 GPUs): ~6 minutes"
},
{
"code": null,
"e": 3341,
"s": 3206,
"text": "Because Horovod uses data parallelism, the time per epoch remains roughly the same. See statistics for each device in the image above."
},
{
"code": null,
"e": 3518,
"s": 3341,
"text": "However, since the training data is distributed to each GPU and the gradients are averaged, the number of epochs needed to converge is roughly a function of the number of GPUs."
},
{
"code": null,
"e": 3691,
"s": 3518,
"text": "So, previously, if we needed 100 epochs to converge with 1 GPU, we can estimate that it’ll only take ~25 (100/4) epochs to converge with 4 GPUs to around the same accuracy."
},
{
"code": null,
"e": 4014,
"s": 3691,
"text": "It’s not a law, so there may be some unexpected variation here. The training dynamics are definitely different. In this case, I noticed a “steeper curve,” where the error was much higher initially, and converged much faster. You’ll need to monitor the training as always to ensure there aren’t any issues with convergence."
},
{
"code": null,
"e": 4110,
"s": 4014,
"text": "If you’re looking for a monitoring tool and haven’t used weights and biases yet — try them out."
},
{
"code": null,
"e": 4130,
"s": 4110,
"text": "Thanks for reading!"
}
]
|
How to disable Mobile Data on Android? | This example demonstrates how do I disable Mobile data in Android.
For your find Information, unless you have a rooted phone I don't think you can enable and disable data programmatically because in order to do so we have to include MODIFY_PHONE_STATE permission which is only given to system or signature apps.
setMobileDataEnabled() method is no longer callable via reflection. It was callable since Android 2.1 (API 7) to Android 4.4 (API 19) via reflection, but as of Android 5.0 and later, even with the rooted phones, the setMobileDataEnabled() method is not callable.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<Switch
android:id="@+id/switchData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Mobile Data" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.CompoundButton;
import android.widget.Switch;
import java.lang.reflect.Method;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
Switch mySwitch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySwitch = findViewById(R.id.switchData);
mySwitch.setChecked(getMobileDataState());
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
setMobileDataState(isChecked);
}
});
}
public void setMobileDataState(boolean mobileDataEnabled) {
try {
TelephonyManager telephonyService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
Method setMobileDataEnabledMethod = Objects.requireNonNull(telephonyService).getClass().getDeclaredMethod("setDataEnabled", boolean.class);
setMobileDataEnabledMethod.invoke(telephonyService, mobileDataEnabled);
} catch (Exception ex) {
Log.e("MainActivity", "Error setting mobile data state", ex);
}
}
public boolean getMobileDataState() {
try {
TelephonyManager telephonyService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
Method getMobileDataEnabledMethod = Objects.requireNonNull(telephonyService).getClass().getDeclaredMethod("getDataEnabled");
return (boolean) (Boolean) getMobileDataEnabledMethod.invoke(telephonyService);
} catch (Exception ex) {
Log.e("MainActivity", "Error getting mobile data state", ex);
}
return false;
}
}
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": 1129,
"s": 1062,
"text": "This example demonstrates how do I disable Mobile data in Android."
},
{
"code": null,
"e": 1374,
"s": 1129,
"text": "For your find Information, unless you have a rooted phone I don't think you can enable and disable data programmatically because in order to do so we have to include MODIFY_PHONE_STATE permission which is only given to system or signature apps."
},
{
"code": null,
"e": 1637,
"s": 1374,
"text": "setMobileDataEnabled() method is no longer callable via reflection. It was callable since Android 2.1 (API 7) to Android 4.4 (API 19) via reflection, but as of Android 5.0 and later, even with the rooted phones, the setMobileDataEnabled() method is not callable."
},
{
"code": null,
"e": 1766,
"s": 1637,
"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": 1831,
"s": 1766,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2346,
"s": 1831,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:padding=\"16dp\"\n tools:context=\".MainActivity\">\n <Switch\n android:id=\"@+id/switchData\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:text=\"Mobile Data\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2403,
"s": 2346,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4347,
"s": 2403,
"text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.content.Context;\nimport android.os.Bundle;\nimport android.telephony.TelephonyManager;\nimport android.util.Log;\nimport android.widget.CompoundButton;\nimport android.widget.Switch;\nimport java.lang.reflect.Method;\nimport java.util.Objects;\npublic class MainActivity extends AppCompatActivity {\n Switch mySwitch;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n mySwitch = findViewById(R.id.switchData);\n mySwitch.setChecked(getMobileDataState());\n mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {\n setMobileDataState(isChecked);\n }\n });\n }\n public void setMobileDataState(boolean mobileDataEnabled) {\n try {\n TelephonyManager telephonyService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);\n Method setMobileDataEnabledMethod = Objects.requireNonNull(telephonyService).getClass().getDeclaredMethod(\"setDataEnabled\", boolean.class);\n setMobileDataEnabledMethod.invoke(telephonyService, mobileDataEnabled);\n } catch (Exception ex) {\n Log.e(\"MainActivity\", \"Error setting mobile data state\", ex);\n }\n }\n public boolean getMobileDataState() {\n try {\n TelephonyManager telephonyService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);\n Method getMobileDataEnabledMethod = Objects.requireNonNull(telephonyService).getClass().getDeclaredMethod(\"getDataEnabled\");\n return (boolean) (Boolean) getMobileDataEnabledMethod.invoke(telephonyService);\n } catch (Exception ex) {\n Log.e(\"MainActivity\", \"Error getting mobile data state\", ex);\n }\n return false;\n }\n}"
},
{
"code": null,
"e": 4402,
"s": 4347,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5072,
"s": 4402,
"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": 5420,
"s": 5072,
"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": 5460,
"s": 5420,
"text": "Click here to download the project code"
}
]
|
Python List len() Method | Python list method len() returns the number of elements in the list.
Following is the syntax for len() method −
len(list)
list − This is a list for which number of elements to be counted.
list − This is a list for which number of elements to be counted.
This method returns the number of elements in the list.
The following example shows the usage of len() method.
#!/usr/bin/python
list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']
print "First list length : ", len(list1)
print "Second list length : ", len(list2)
When we run above program, it produces following result −
First list length : 3
Second list length : 2
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2313,
"s": 2244,
"text": "Python list method len() returns the number of elements in the list."
},
{
"code": null,
"e": 2356,
"s": 2313,
"text": "Following is the syntax for len() method −"
},
{
"code": null,
"e": 2367,
"s": 2356,
"text": "len(list)\n"
},
{
"code": null,
"e": 2433,
"s": 2367,
"text": "list − This is a list for which number of elements to be counted."
},
{
"code": null,
"e": 2499,
"s": 2433,
"text": "list − This is a list for which number of elements to be counted."
},
{
"code": null,
"e": 2555,
"s": 2499,
"text": "This method returns the number of elements in the list."
},
{
"code": null,
"e": 2610,
"s": 2555,
"text": "The following example shows the usage of len() method."
},
{
"code": null,
"e": 2762,
"s": 2610,
"text": "#!/usr/bin/python\n\nlist1, list2 = [123, 'xyz', 'zara'], [456, 'abc']\nprint \"First list length : \", len(list1)\nprint \"Second list length : \", len(list2)"
},
{
"code": null,
"e": 2820,
"s": 2762,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 2868,
"s": 2820,
"text": "First list length : 3\nSecond list length : 2\n"
},
{
"code": null,
"e": 2905,
"s": 2868,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 2921,
"s": 2905,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 2954,
"s": 2921,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 2973,
"s": 2954,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3008,
"s": 2973,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3030,
"s": 3008,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3064,
"s": 3030,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3092,
"s": 3064,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3127,
"s": 3092,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3141,
"s": 3127,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3174,
"s": 3141,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3191,
"s": 3174,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3198,
"s": 3191,
"text": " Print"
},
{
"code": null,
"e": 3209,
"s": 3198,
"text": " Add Notes"
}
]
|
TCS Placement Paper | MCQ 4 - GeeksforGeeks | 22 Sep, 2021
This is a TCS model placement paper for aptitude preparation. This placement paper will cover aptitude questions that are asked in TCS recruitment drives and also strictly follows the pattern of questions asked in TCS interviews. It is recommended to solve each one of the following questions to increase your chances of clearing the TCS interview.
A call centre agent has a list of 305 phone numbers of people in alphabetical order of names, but Anuj does not have any of the names. He needs to quickly contact Danish Mank to convey a message to him. If each call takes 2 minutes to complete, and every call is answered, what is the minimum amount of time during which he can guarantee to deliver the message to Danish? a) 206 minutes b) 610 minutes c) 18 minutes d) 34 minutes
A call centre agent has a list of 305 phone numbers of people in alphabetical order of names, but Anuj does not have any of the names. He needs to quickly contact Danish Mank to convey a message to him. If each call takes 2 minutes to complete, and every call is answered, what is the minimum amount of time during which he can guarantee to deliver the message to Danish? a) 206 minutes b) 610 minutes c) 18 minutes d) 34 minutes
Answer: c) 18 minutes
Solution: We need to search for a particular name in a phone book. So we need to apply a method in which we can easily search a number in a minimum count. So we divide the list into two equal halves, i.e., 305/2 = 152.5 or let’s take 152. Now we can decide whether to check for Danish in the upper or lower half of 152. This is decided by the starting letter of the name in a page. Proceeding in the similar manner we get, 152/2 = 76 76/2 = 38 38/2 = 19 19/2 = 9 9/2 = 4 4/2 = 2 2/2 = 0 So we get 0 at the 9th time, hence this is the minimum number of the count to find Danish. So total time taken = 9 * 2 = 18 minutes.
2. There is an office consisting of 38 people. 10 of them like to play golf, 15 like to play football and 20 neither play golf nor football. How many like both golf and football? a) 10 b) 7 c) 15 d) 18
Answer: b) 7
Solution: Let the number of people liking golf = ‘A’ Let the number of people liking football = ‘B’ Let the number of people liking either golf or football = A U B = 38 – 20 = 18 People liking both golf and football =
= A + B – AUB = 10 + 15 -18 = 7
3. If a dice is rolled 2 times, what is the probability of getting a pair of numbers with sum equal to 3 or 4? a) 6/36 b) 5/36 c) 1/9 d) 1/12
Answer: b) 5/36
Solution: Total probability = 36 We can get a sum of 3 or 4 in this many ways: => (2, 1), (1, 2), (1, 3), (3, 1), (2, 2) = 5 So probability = 5 / 36
4. A shopkeeper charges 12 rupees for a bunch of cakes. Anuj bargained to the shopkeeper and got two extra ones, and that made them cost one rupee for dozen less than first asking price. How many cakes did Anuj receive in 12 rupees? a) 10 b) 14 c) 18 d) 16
Answer: d) 16
Solution: Let the number of cakes = ‘x’ or ‘x/12’ dozen So, x/12 cost Anuj 12 rupees, or 1 dozen cost him = 144/x rupees Now, he gets two extra = 144/(x+2) in 1 rupees less, => 144/x – 144/(x+2) = 1 => On putting 16, the equation is satisfied, hence the answer.
5. Ram alone can do 1/4th of the work in 2 days. Shyam alone can do 2/3th of the work in 4 days. So what part of the work must be done by Anil in 2 days, for them to complete the work together in 3 days? a) 1/8 b) 1/20 c) 1/16 d) 1/12 Answer: d) 1/12
Solution: Ram alone can complete the work in 2*4 = 8 days. Shyam alone can complete the work in 4*(3/2) = 6 days. Taking the lcm of 8, 6, 3 = 24 Capacity of Ram = 24/8 = 3 Capacity of Shyam = 24/6 = 4 Capacity of Anil = 8 – (4+3) = 1 Now in 2 days Anil can do 2 unit of work = 2/24 = 1/12 part of the work
OR
Let C’s one day work be x.
Acc. to question
1/8 + 1/6 + x = 1/3
x = 1/24
Therefore C will complete 1/12th of the work in 2 days.
6. Mr Mehta chooses a number and keeps on doubling the number followed by subtracting one from it. If he chooses 3 as the initial number and he repeats the operation 30 times then what is the final result? a) (2^30) – 1 b) (2^30) – 2 c) (2^31) – 1 d) None of these
Answer: d) None of these
Solution: According to the question, 3 * 2 – 1 = 5 =
5 * 2 – 1 = 9 = 9 * 2 – 1 = 17 = Proceeding in the similar fashion, on 30 times we get
7. Ram alone can paint a wall in 7 days and his friend Roy alone paints the same wall in 9 days. In how many days they can paint the wall working together? (Round off your answer) a) 3 b) 5 c) 4 d) 7
Answer: c) 4
Solution: This can be solved by applying a simple formula = ab/(a+b) or, (9*7)/(9+7) or, 63/16 = 3.9375 = 4 (answer)
8. Two vertical walls of the length of 6 meters and 11 meters are at a distance of 12 meters apart. Find the top distance of both walls? a) 15 meters b) 13 meters c) 12 meters d) 10 meters
Answer: b) 13 meters
Solution: Let’s consider this figure,
We need to find the distance of AB, We know AC = 12 m and BC = 11-6 = 5 m So applying pythagoras theorem we get, AB =
= 13 meters
9. For f(m, n) =45*m + 36*n, where m and n are integers (either positive or negative). What is the minimum positive value for f(m, n) for all values of m, n (this may be achieved for various values of m and n)? a) 18 b) 12 c) 9 d) 16
Answer: c) 9
Solution: To get the minimum value of f(m, n), put m = 1 and n = -1, we get f(, n) = 9
10. A white cube(with six faces) is to be painted blue on two different faces. In how many different ways can this be achieved (two paintings are considered same if on a suitable rotation of the cube one painting can be carried to the other)? a) 30 ways b) 18 ways c) 4 ways d) 2 ways
Answer: d) 2
Solution:
This can be achiededv in the following different ways;: First, painting on opposite faces can be achieved in 1 way. Second, painting on adjacent faces can be achieved in 1 way. Therefore in 2 ways.
ajinkyavidwans18
cse4
saurabh1990aror
interview-preparation
placement preparation
TCS
Placements
TCS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 20 Puzzles Commonly Asked During SDE Interviews
Codenation Recruitment Process
Problem on HCF and LCM
C program to reverse the content of the file and print it
Progressions (AP, GP, HP)
Interview Preparation
Permutation and Combination
Time Speed Distance
Hashedin by Deloitte Interview Experience for SDET 2022
Puzzle | 50 red marbles and 50 blue marbles | [
{
"code": null,
"e": 23905,
"s": 23877,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 24255,
"s": 23905,
"text": "This is a TCS model placement paper for aptitude preparation. This placement paper will cover aptitude questions that are asked in TCS recruitment drives and also strictly follows the pattern of questions asked in TCS interviews. It is recommended to solve each one of the following questions to increase your chances of clearing the TCS interview. "
},
{
"code": null,
"e": 24686,
"s": 24255,
"text": "A call centre agent has a list of 305 phone numbers of people in alphabetical order of names, but Anuj does not have any of the names. He needs to quickly contact Danish Mank to convey a message to him. If each call takes 2 minutes to complete, and every call is answered, what is the minimum amount of time during which he can guarantee to deliver the message to Danish? a) 206 minutes b) 610 minutes c) 18 minutes d) 34 minutes "
},
{
"code": null,
"e": 25117,
"s": 24686,
"text": "A call centre agent has a list of 305 phone numbers of people in alphabetical order of names, but Anuj does not have any of the names. He needs to quickly contact Danish Mank to convey a message to him. If each call takes 2 minutes to complete, and every call is answered, what is the minimum amount of time during which he can guarantee to deliver the message to Danish? a) 206 minutes b) 610 minutes c) 18 minutes d) 34 minutes "
},
{
"code": null,
"e": 25139,
"s": 25117,
"text": "Answer: c) 18 minutes"
},
{
"code": null,
"e": 25759,
"s": 25139,
"text": "Solution: We need to search for a particular name in a phone book. So we need to apply a method in which we can easily search a number in a minimum count. So we divide the list into two equal halves, i.e., 305/2 = 152.5 or let’s take 152. Now we can decide whether to check for Danish in the upper or lower half of 152. This is decided by the starting letter of the name in a page. Proceeding in the similar manner we get, 152/2 = 76 76/2 = 38 38/2 = 19 19/2 = 9 9/2 = 4 4/2 = 2 2/2 = 0 So we get 0 at the 9th time, hence this is the minimum number of the count to find Danish. So total time taken = 9 * 2 = 18 minutes."
},
{
"code": null,
"e": 25982,
"s": 25759,
"text": "2. There is an office consisting of 38 people. 10 of them like to play golf, 15 like to play football and 20 neither play golf nor football. How many like both golf and football? a) 10 b) 7 c) 15 d) 18 "
},
{
"code": null,
"e": 25995,
"s": 25982,
"text": "Answer: b) 7"
},
{
"code": null,
"e": 26214,
"s": 25995,
"text": "Solution: Let the number of people liking golf = ‘A’ Let the number of people liking football = ‘B’ Let the number of people liking either golf or football = A U B = 38 – 20 = 18 People liking both golf and football = "
},
{
"code": null,
"e": 26246,
"s": 26214,
"text": "= A + B – AUB = 10 + 15 -18 = 7"
},
{
"code": null,
"e": 26409,
"s": 26246,
"text": "3. If a dice is rolled 2 times, what is the probability of getting a pair of numbers with sum equal to 3 or 4? a) 6/36 b) 5/36 c) 1/9 d) 1/12 "
},
{
"code": null,
"e": 26425,
"s": 26409,
"text": "Answer: b) 5/36"
},
{
"code": null,
"e": 26574,
"s": 26425,
"text": "Solution: Total probability = 36 We can get a sum of 3 or 4 in this many ways: => (2, 1), (1, 2), (1, 3), (3, 1), (2, 2) = 5 So probability = 5 / 36"
},
{
"code": null,
"e": 26848,
"s": 26574,
"text": "4. A shopkeeper charges 12 rupees for a bunch of cakes. Anuj bargained to the shopkeeper and got two extra ones, and that made them cost one rupee for dozen less than first asking price. How many cakes did Anuj receive in 12 rupees? a) 10 b) 14 c) 18 d) 16 "
},
{
"code": null,
"e": 26862,
"s": 26848,
"text": "Answer: d) 16"
},
{
"code": null,
"e": 27124,
"s": 26862,
"text": "Solution: Let the number of cakes = ‘x’ or ‘x/12’ dozen So, x/12 cost Anuj 12 rupees, or 1 dozen cost him = 144/x rupees Now, he gets two extra = 144/(x+2) in 1 rupees less, => 144/x – 144/(x+2) = 1 => On putting 16, the equation is satisfied, hence the answer."
},
{
"code": null,
"e": 27391,
"s": 27124,
"text": "5. Ram alone can do 1/4th of the work in 2 days. Shyam alone can do 2/3th of the work in 4 days. So what part of the work must be done by Anil in 2 days, for them to complete the work together in 3 days? a) 1/8 b) 1/20 c) 1/16 d) 1/12 Answer: d) 1/12 "
},
{
"code": null,
"e": 27698,
"s": 27391,
"text": "Solution: Ram alone can complete the work in 2*4 = 8 days. Shyam alone can complete the work in 4*(3/2) = 6 days. Taking the lcm of 8, 6, 3 = 24 Capacity of Ram = 24/8 = 3 Capacity of Shyam = 24/6 = 4 Capacity of Anil = 8 – (4+3) = 1 Now in 2 days Anil can do 2 unit of work = 2/24 = 1/12 part of the work "
},
{
"code": null,
"e": 27701,
"s": 27698,
"text": "OR"
},
{
"code": null,
"e": 27728,
"s": 27701,
"text": "Let C’s one day work be x."
},
{
"code": null,
"e": 27745,
"s": 27728,
"text": "Acc. to question"
},
{
"code": null,
"e": 27765,
"s": 27745,
"text": "1/8 + 1/6 + x = 1/3"
},
{
"code": null,
"e": 27774,
"s": 27765,
"text": "x = 1/24"
},
{
"code": null,
"e": 27830,
"s": 27774,
"text": "Therefore C will complete 1/12th of the work in 2 days."
},
{
"code": null,
"e": 28108,
"s": 27830,
"text": "6. Mr Mehta chooses a number and keeps on doubling the number followed by subtracting one from it. If he chooses 3 as the initial number and he repeats the operation 30 times then what is the final result? a) (2^30) – 1 b) (2^30) – 2 c) (2^31) – 1 d) None of these "
},
{
"code": null,
"e": 28133,
"s": 28108,
"text": "Answer: d) None of these"
},
{
"code": null,
"e": 28187,
"s": 28133,
"text": "Solution: According to the question, 3 * 2 – 1 = 5 = "
},
{
"code": null,
"e": 28275,
"s": 28187,
"text": "5 * 2 – 1 = 9 = 9 * 2 – 1 = 17 = Proceeding in the similar fashion, on 30 times we get "
},
{
"code": null,
"e": 28488,
"s": 28275,
"text": "7. Ram alone can paint a wall in 7 days and his friend Roy alone paints the same wall in 9 days. In how many days they can paint the wall working together? (Round off your answer) a) 3 b) 5 c) 4 d) 7 "
},
{
"code": null,
"e": 28501,
"s": 28488,
"text": "Answer: c) 4"
},
{
"code": null,
"e": 28618,
"s": 28501,
"text": "Solution: This can be solved by applying a simple formula = ab/(a+b) or, (9*7)/(9+7) or, 63/16 = 3.9375 = 4 (answer)"
},
{
"code": null,
"e": 28820,
"s": 28618,
"text": "8. Two vertical walls of the length of 6 meters and 11 meters are at a distance of 12 meters apart. Find the top distance of both walls? a) 15 meters b) 13 meters c) 12 meters d) 10 meters "
},
{
"code": null,
"e": 28841,
"s": 28820,
"text": "Answer: b) 13 meters"
},
{
"code": null,
"e": 28881,
"s": 28841,
"text": "Solution: Let’s consider this figure, "
},
{
"code": null,
"e": 29000,
"s": 28881,
"text": "We need to find the distance of AB, We know AC = 12 m and BC = 11-6 = 5 m So applying pythagoras theorem we get, AB = "
},
{
"code": null,
"e": 29014,
"s": 29002,
"text": "= 13 meters"
},
{
"code": null,
"e": 29263,
"s": 29016,
"text": "9. For f(m, n) =45*m + 36*n, where m and n are integers (either positive or negative). What is the minimum positive value for f(m, n) for all values of m, n (this may be achieved for various values of m and n)? a) 18 b) 12 c) 9 d) 16 "
},
{
"code": null,
"e": 29276,
"s": 29263,
"text": "Answer: c) 9"
},
{
"code": null,
"e": 29363,
"s": 29276,
"text": "Solution: To get the minimum value of f(m, n), put m = 1 and n = -1, we get f(, n) = 9"
},
{
"code": null,
"e": 29661,
"s": 29363,
"text": "10. A white cube(with six faces) is to be painted blue on two different faces. In how many different ways can this be achieved (two paintings are considered same if on a suitable rotation of the cube one painting can be carried to the other)? a) 30 ways b) 18 ways c) 4 ways d) 2 ways "
},
{
"code": null,
"e": 29674,
"s": 29661,
"text": "Answer: d) 2"
},
{
"code": null,
"e": 29685,
"s": 29674,
"text": "Solution: "
},
{
"code": null,
"e": 29883,
"s": 29685,
"text": "This can be achiededv in the following different ways;: First, painting on opposite faces can be achieved in 1 way. Second, painting on adjacent faces can be achieved in 1 way. Therefore in 2 ways."
},
{
"code": null,
"e": 29900,
"s": 29883,
"text": "ajinkyavidwans18"
},
{
"code": null,
"e": 29905,
"s": 29900,
"text": "cse4"
},
{
"code": null,
"e": 29921,
"s": 29905,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 29943,
"s": 29921,
"text": "interview-preparation"
},
{
"code": null,
"e": 29965,
"s": 29943,
"text": "placement preparation"
},
{
"code": null,
"e": 29969,
"s": 29965,
"text": "TCS"
},
{
"code": null,
"e": 29980,
"s": 29969,
"text": "Placements"
},
{
"code": null,
"e": 29984,
"s": 29980,
"text": "TCS"
},
{
"code": null,
"e": 30082,
"s": 29984,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30091,
"s": 30082,
"text": "Comments"
},
{
"code": null,
"e": 30104,
"s": 30091,
"text": "Old Comments"
},
{
"code": null,
"e": 30156,
"s": 30104,
"text": "Top 20 Puzzles Commonly Asked During SDE Interviews"
},
{
"code": null,
"e": 30187,
"s": 30156,
"text": "Codenation Recruitment Process"
},
{
"code": null,
"e": 30210,
"s": 30187,
"text": "Problem on HCF and LCM"
},
{
"code": null,
"e": 30268,
"s": 30210,
"text": "C program to reverse the content of the file and print it"
},
{
"code": null,
"e": 30294,
"s": 30268,
"text": "Progressions (AP, GP, HP)"
},
{
"code": null,
"e": 30316,
"s": 30294,
"text": "Interview Preparation"
},
{
"code": null,
"e": 30344,
"s": 30316,
"text": "Permutation and Combination"
},
{
"code": null,
"e": 30364,
"s": 30344,
"text": "Time Speed Distance"
},
{
"code": null,
"e": 30420,
"s": 30364,
"text": "Hashedin by Deloitte Interview Experience for SDET 2022"
}
]
|
How to Redirect 404 errors to a page in Express.js ? - GeeksforGeeks | 10 Oct, 2021
Express Js is a web application framework based on Node.js web server functionality that helps us to create web servers with lesser complexity and in a well-organized manner. Express provides routing services that help us in creating application endpoints that respond based on the HTTP request method (GET, POST, DELETE, etc) and the requested route.
In Express if we want to redirect the user to the 404 error page if a particular route does not exist then we can use the app.all() method as the last route handler method and * (asterisk) as the route name. Asterisk is a wildcard that matches any route name.
Syntax:
app.all('*', (req, res) => {
// code logic
})
The route mentioned above can handle all kinds of HTTP request methods and request to any route name.
Project Setup
Step 1: Install Node.js if you haven’t already.
Step 2: Create a folder for your project and cd (change directory) into it. Create a new file named app.js inside that folder. Now, initialize a new Node.js project with default configurations using the following command.
npm init -y
Step 3: Now install express inside your project using the following command on the command line.
npm install express
Project Structure: After following the steps your project structure will look like the following.
app.js
const express = require('express');const app = express(); app.get('/', (req, res) => { res.send('<h1>Home page</h1>');}); app.get('/products', (req, res) => { res.send('<h1>Products page</h1>');}); // This route will handle all the requests that are // not handled by any other route handler. In // this hanlder we will redirect the user to // an error page with NOT FOUND message and status// code as 404 (HTTP status code for NOT found)app.all('*', (req, res) => { res.status(404).send('<h1>404! Page not found</h1>');}); app.listen(3000, () => { console.log('Server is up on port 3000');});
Step to run the application: You can run your express server by using the following command on the command line.
node app.js
Output: Open the browser and go to http://localhost:3000, and manually switch to http://localhost:3000/some_invalid_route and you will be redirected to our error page with a message.
Express.js
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 25833,
"s": 25805,
"text": "\n10 Oct, 2021"
},
{
"code": null,
"e": 26185,
"s": 25833,
"text": "Express Js is a web application framework based on Node.js web server functionality that helps us to create web servers with lesser complexity and in a well-organized manner. Express provides routing services that help us in creating application endpoints that respond based on the HTTP request method (GET, POST, DELETE, etc) and the requested route."
},
{
"code": null,
"e": 26445,
"s": 26185,
"text": "In Express if we want to redirect the user to the 404 error page if a particular route does not exist then we can use the app.all() method as the last route handler method and * (asterisk) as the route name. Asterisk is a wildcard that matches any route name."
},
{
"code": null,
"e": 26453,
"s": 26445,
"text": "Syntax:"
},
{
"code": null,
"e": 26503,
"s": 26453,
"text": "app.all('*', (req, res) => {\n // code logic\n})"
},
{
"code": null,
"e": 26605,
"s": 26503,
"text": "The route mentioned above can handle all kinds of HTTP request methods and request to any route name."
},
{
"code": null,
"e": 26621,
"s": 26607,
"text": "Project Setup"
},
{
"code": null,
"e": 26669,
"s": 26621,
"text": "Step 1: Install Node.js if you haven’t already."
},
{
"code": null,
"e": 26891,
"s": 26669,
"text": "Step 2: Create a folder for your project and cd (change directory) into it. Create a new file named app.js inside that folder. Now, initialize a new Node.js project with default configurations using the following command."
},
{
"code": null,
"e": 26903,
"s": 26891,
"text": "npm init -y"
},
{
"code": null,
"e": 27000,
"s": 26903,
"text": "Step 3: Now install express inside your project using the following command on the command line."
},
{
"code": null,
"e": 27020,
"s": 27000,
"text": "npm install express"
},
{
"code": null,
"e": 27118,
"s": 27020,
"text": "Project Structure: After following the steps your project structure will look like the following."
},
{
"code": null,
"e": 27125,
"s": 27118,
"text": "app.js"
},
{
"code": "const express = require('express');const app = express(); app.get('/', (req, res) => { res.send('<h1>Home page</h1>');}); app.get('/products', (req, res) => { res.send('<h1>Products page</h1>');}); // This route will handle all the requests that are // not handled by any other route handler. In // this hanlder we will redirect the user to // an error page with NOT FOUND message and status// code as 404 (HTTP status code for NOT found)app.all('*', (req, res) => { res.status(404).send('<h1>404! Page not found</h1>');}); app.listen(3000, () => { console.log('Server is up on port 3000');});",
"e": 27727,
"s": 27125,
"text": null
},
{
"code": null,
"e": 27840,
"s": 27727,
"text": "Step to run the application: You can run your express server by using the following command on the command line."
},
{
"code": null,
"e": 27852,
"s": 27840,
"text": "node app.js"
},
{
"code": null,
"e": 28035,
"s": 27852,
"text": "Output: Open the browser and go to http://localhost:3000, and manually switch to http://localhost:3000/some_invalid_route and you will be redirected to our error page with a message."
},
{
"code": null,
"e": 28046,
"s": 28035,
"text": "Express.js"
},
{
"code": null,
"e": 28063,
"s": 28046,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 28070,
"s": 28063,
"text": "Picked"
},
{
"code": null,
"e": 28078,
"s": 28070,
"text": "Node.js"
},
{
"code": null,
"e": 28095,
"s": 28078,
"text": "Web Technologies"
},
{
"code": null,
"e": 28193,
"s": 28095,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28223,
"s": 28193,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 28252,
"s": 28223,
"text": "Node.js fs.readFile() Method"
},
{
"code": null,
"e": 28309,
"s": 28252,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 28363,
"s": 28309,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 28400,
"s": 28363,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 28440,
"s": 28400,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28485,
"s": 28440,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28528,
"s": 28485,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28578,
"s": 28528,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Can virtual functions be private in C++? - GeeksforGeeks | 23 Aug, 2021
In C++, virtual functions can be private and can be overridden by the derived class. For example, the following program compiles and runs fine.
C++
#include <iostream> class base{public: // default base constructor base() { std::cout << "base class constructor\n"; } // virtual base destructor // always use virtual base // destructors when you know you // will inherit this class virtual ~base() { std::cout << "base class destructor\n"; } // public method in base class void show() { std::cout << "show() called on base class\n"; } // public virtual function in base class, // contents of this function are printed when called // with base class object when called with base class // pointer contents of derived class are printed on // screen virtual void print() { std::cout << "print() called on base class\n"; }}; class derived : public base {public: // default derived constructor derived() : base() { std::cout << "derived class constructor\n"; } // virtual derived destructor // always use virtual destructors // when inheriting from a // base class virtual ~derived() { std::cout << "derived class destructor\n"; } private: // private virtual function in derived class overwrites // base class virtual method contents of this function // are printed when called with base class pointer or // when called with derived class object virtual void print() { std::cout << "print() called on derived class\n"; }}; int main(){ std::cout << "printing with base class pointer\n"; // construct base class pointer with derived class // memory base* b_ptr = new derived(); // call base class show() b_ptr->show(); // call virtual print in base class but it is overridden // in derived class also note that print() is private // member in derived class, still the contents of derived // class are printed this code works because base class // defines a public interface and drived class overrides // it in its implementation b_ptr->print(); delete b_ptr;}
printing with base class pointer
base class constructor
derived class constructor
show() called on base class
print() called on derived class
derived class destructor
base class destructor
There are few things to note in the above program. b_ptr is a pointer of Base type and points to a Derived class object. When ptr->print() is called, print() of Derived is executed.
This code works because base class defines a public interface and derived class overrides it in its implementation even though derived has a private virtual function.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
vipinkarampudi
deepak11808097
CPP-Functions
cpp-virtual
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
fork() in C
Function Pointer in C
TCP Server-Client implementation in C
std::string class in C++
Structures in C
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Socket Programming in C/C++ | [
{
"code": null,
"e": 24380,
"s": 24352,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 24524,
"s": 24380,
"text": "In C++, virtual functions can be private and can be overridden by the derived class. For example, the following program compiles and runs fine."
},
{
"code": null,
"e": 24528,
"s": 24524,
"text": "C++"
},
{
"code": "#include <iostream> class base{public: // default base constructor base() { std::cout << \"base class constructor\\n\"; } // virtual base destructor // always use virtual base // destructors when you know you // will inherit this class virtual ~base() { std::cout << \"base class destructor\\n\"; } // public method in base class void show() { std::cout << \"show() called on base class\\n\"; } // public virtual function in base class, // contents of this function are printed when called // with base class object when called with base class // pointer contents of derived class are printed on // screen virtual void print() { std::cout << \"print() called on base class\\n\"; }}; class derived : public base {public: // default derived constructor derived() : base() { std::cout << \"derived class constructor\\n\"; } // virtual derived destructor // always use virtual destructors // when inheriting from a // base class virtual ~derived() { std::cout << \"derived class destructor\\n\"; } private: // private virtual function in derived class overwrites // base class virtual method contents of this function // are printed when called with base class pointer or // when called with derived class object virtual void print() { std::cout << \"print() called on derived class\\n\"; }}; int main(){ std::cout << \"printing with base class pointer\\n\"; // construct base class pointer with derived class // memory base* b_ptr = new derived(); // call base class show() b_ptr->show(); // call virtual print in base class but it is overridden // in derived class also note that print() is private // member in derived class, still the contents of derived // class are printed this code works because base class // defines a public interface and drived class overrides // it in its implementation b_ptr->print(); delete b_ptr;}",
"e": 26568,
"s": 24528,
"text": null
},
{
"code": null,
"e": 26758,
"s": 26568,
"text": "printing with base class pointer\nbase class constructor\nderived class constructor\nshow() called on base class\nprint() called on derived class\nderived class destructor\nbase class destructor\n"
},
{
"code": null,
"e": 26940,
"s": 26758,
"text": "There are few things to note in the above program. b_ptr is a pointer of Base type and points to a Derived class object. When ptr->print() is called, print() of Derived is executed."
},
{
"code": null,
"e": 27230,
"s": 26940,
"text": "This code works because base class defines a public interface and derived class overrides it in its implementation even though derived has a private virtual function.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 27245,
"s": 27230,
"text": "vipinkarampudi"
},
{
"code": null,
"e": 27260,
"s": 27245,
"text": "deepak11808097"
},
{
"code": null,
"e": 27274,
"s": 27260,
"text": "CPP-Functions"
},
{
"code": null,
"e": 27286,
"s": 27274,
"text": "cpp-virtual"
},
{
"code": null,
"e": 27297,
"s": 27286,
"text": "C Language"
},
{
"code": null,
"e": 27301,
"s": 27297,
"text": "C++"
},
{
"code": null,
"e": 27305,
"s": 27301,
"text": "CPP"
},
{
"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": 27437,
"s": 27425,
"text": "fork() in C"
},
{
"code": null,
"e": 27459,
"s": 27437,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 27497,
"s": 27459,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27522,
"s": 27497,
"text": "std::string class in C++"
},
{
"code": null,
"e": 27538,
"s": 27522,
"text": "Structures in C"
},
{
"code": null,
"e": 27556,
"s": 27538,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 27575,
"s": 27556,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 27621,
"s": 27575,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 27664,
"s": 27621,
"text": "Map in C++ Standard Template Library (STL)"
}
]
|
Dorks Eye - Google Hacking Dork Scraping and Searching Script - GeeksforGeeks | 28 Nov, 2021
The Dorks Eye tool is developed in the Python3 language which h can easily find Vulnerable links using Google Dorks. Dorks Eye tool gathers links to web pages and applications from the Internet which reveals some information. Now this information can be sensitive data like SQL queries of web pages, usernames and passwords, bank details, and many more. Dorks Eye also supports saving the results onto a text formatted file. This tool is also available on the GitHub platform for free and is open source to use.
Google Dorking is the advanced search technique that shows the accurate results of our query rather than showing irrelevant stuff or some ad-containing sites. Google Dorking is so powerful that we can also get the username and passwords containing files, robot.txt files, sensitive files conf files, and many more. One of the sample dorking queries look like: /modules/vwar/admin/admin.php?vwar_root=
Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux
Step 1: Use the following command to install the tool in your Kali Linux operating system.
git clone https://github.com/BullsEye0/dorks-eye.git
Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool.
cd dorks-eye
Step 3: You are in the directory of the dorks-eye. Now you have to install a dependency of the dorks-eye using the following command.
sudo pip3 install -r requirements.txt
Step 4: All the dependencies have been installed in your Kali Linux operating system. Now run the tool.
python3 dorks-eye.py
Example/Usage: Finding config files by using dork query
Query used -> indexof:backup/web.config
We have specified the dork query through which we will get vulnerable site links.
We will be displaying the 10 vulnerable sites on the terminal. You can display more than 10 websites.
We have got the links of vulnerable sites which match the dork query.
We have visited the link and we have got the conf directory contents which include various .xml files.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
chown command in Linux with Examples
Docker - COPY Instruction
nohup Command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
Thread functions in C/C++
Array Basics in Shell Scripting | Set 1 | [
{
"code": null,
"e": 25761,
"s": 25733,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 26273,
"s": 25761,
"text": "The Dorks Eye tool is developed in the Python3 language which h can easily find Vulnerable links using Google Dorks. Dorks Eye tool gathers links to web pages and applications from the Internet which reveals some information. Now this information can be sensitive data like SQL queries of web pages, usernames and passwords, bank details, and many more. Dorks Eye also supports saving the results onto a text formatted file. This tool is also available on the GitHub platform for free and is open source to use."
},
{
"code": null,
"e": 26675,
"s": 26273,
"text": "Google Dorking is the advanced search technique that shows the accurate results of our query rather than showing irrelevant stuff or some ad-containing sites. Google Dorking is so powerful that we can also get the username and passwords containing files, robot.txt files, sensitive files conf files, and many more. One of the sample dorking queries look like: /modules/vwar/admin/admin.php?vwar_root= "
},
{
"code": null,
"e": 26841,
"s": 26675,
"text": "Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux"
},
{
"code": null,
"e": 26932,
"s": 26841,
"text": "Step 1: Use the following command to install the tool in your Kali Linux operating system."
},
{
"code": null,
"e": 26985,
"s": 26932,
"text": "git clone https://github.com/BullsEye0/dorks-eye.git"
},
{
"code": null,
"e": 27123,
"s": 26985,
"text": "Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool."
},
{
"code": null,
"e": 27136,
"s": 27123,
"text": "cd dorks-eye"
},
{
"code": null,
"e": 27270,
"s": 27136,
"text": "Step 3: You are in the directory of the dorks-eye. Now you have to install a dependency of the dorks-eye using the following command."
},
{
"code": null,
"e": 27308,
"s": 27270,
"text": "sudo pip3 install -r requirements.txt"
},
{
"code": null,
"e": 27412,
"s": 27308,
"text": "Step 4: All the dependencies have been installed in your Kali Linux operating system. Now run the tool."
},
{
"code": null,
"e": 27433,
"s": 27412,
"text": "python3 dorks-eye.py"
},
{
"code": null,
"e": 27489,
"s": 27433,
"text": "Example/Usage: Finding config files by using dork query"
},
{
"code": null,
"e": 27529,
"s": 27489,
"text": "Query used -> indexof:backup/web.config"
},
{
"code": null,
"e": 27611,
"s": 27529,
"text": "We have specified the dork query through which we will get vulnerable site links."
},
{
"code": null,
"e": 27713,
"s": 27611,
"text": "We will be displaying the 10 vulnerable sites on the terminal. You can display more than 10 websites."
},
{
"code": null,
"e": 27783,
"s": 27713,
"text": "We have got the links of vulnerable sites which match the dork query."
},
{
"code": null,
"e": 27886,
"s": 27783,
"text": "We have visited the link and we have got the conf directory contents which include various .xml files."
},
{
"code": null,
"e": 27897,
"s": 27886,
"text": "Kali-Linux"
},
{
"code": null,
"e": 27909,
"s": 27897,
"text": "Linux-Tools"
},
{
"code": null,
"e": 27920,
"s": 27909,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28018,
"s": 27920,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28053,
"s": 28018,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 28087,
"s": 28053,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 28124,
"s": 28087,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 28150,
"s": 28124,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 28187,
"s": 28150,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 28216,
"s": 28187,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 28258,
"s": 28216,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 28294,
"s": 28258,
"text": "uniq Command in LINUX with examples"
},
{
"code": null,
"e": 28320,
"s": 28294,
"text": "Thread functions in C/C++"
}
]
|
VBA - If-Else Statement | An If statement consists of a Boolean expression followed by one or more statements. If the condition is said to be True, the statements under If condition(s) are executed. If the condition is said to be False, the statements under Else Part is executed.
Following is the syntax of an If Else statement in VBScript.
If(boolean_expression) Then
Statement 1
.....
.....
Statement n
Else
Statement 1
.....
....
Statement n
End If
For demo purpose, let us find the biggest between the two numbers of an Excel with the help of a function.
Private Sub if_demo_Click()
Dim x As Integer
Dim y As Integer
x = 234
y = 324
If x > y Then
MsgBox "X is Greater than Y"
Else
Msgbox "Y is Greater than X"
End If
End Sub
When the above code is executed, it produces the following result.
Y is Greater than X
101 Lectures
6 hours
Pavan Lalwani
41 Lectures
3 hours
Arnold Higuit
80 Lectures
5.5 hours
Prashant Panchal
25 Lectures
2 hours
Prashant Panchal
26 Lectures
2 hours
Arnold Higuit
92 Lectures
10.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2190,
"s": 1935,
"text": "An If statement consists of a Boolean expression followed by one or more statements. If the condition is said to be True, the statements under If condition(s) are executed. If the condition is said to be False, the statements under Else Part is executed."
},
{
"code": null,
"e": 2251,
"s": 2190,
"text": "Following is the syntax of an If Else statement in VBScript."
},
{
"code": null,
"e": 2387,
"s": 2251,
"text": "If(boolean_expression) Then\n Statement 1\n .....\n .....\n Statement n\nElse\n Statement 1\n .....\n ....\n Statement n\nEnd If\n"
},
{
"code": null,
"e": 2494,
"s": 2387,
"text": "For demo purpose, let us find the biggest between the two numbers of an Excel with the help of a function."
},
{
"code": null,
"e": 2707,
"s": 2494,
"text": "Private Sub if_demo_Click()\n Dim x As Integer\n Dim y As Integer\n \n x = 234\n y = 324\n \n If x > y Then\n MsgBox \"X is Greater than Y\"\n Else\n Msgbox \"Y is Greater than X\"\n End If\nEnd Sub"
},
{
"code": null,
"e": 2774,
"s": 2707,
"text": "When the above code is executed, it produces the following result."
},
{
"code": null,
"e": 2795,
"s": 2774,
"text": "Y is Greater than X\n"
},
{
"code": null,
"e": 2829,
"s": 2795,
"text": "\n 101 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 2844,
"s": 2829,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 2877,
"s": 2844,
"text": "\n 41 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 2892,
"s": 2877,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 2927,
"s": 2892,
"text": "\n 80 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 2945,
"s": 2927,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 2978,
"s": 2945,
"text": "\n 25 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2996,
"s": 2978,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 3029,
"s": 2996,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3044,
"s": 3029,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3080,
"s": 3044,
"text": "\n 92 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 3108,
"s": 3080,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 3115,
"s": 3108,
"text": " Print"
},
{
"code": null,
"e": 3126,
"s": 3115,
"text": " Add Notes"
}
]
|
HTML5 - CORS | Cross-origin resource sharing (CORS) is a mechanism to allows the restricted resources from another domain in web browser.
For suppose, if you click on HTML5- video player in html5 demo sections. it will ask camera permission. if user allow the permission then only it will open the camera or else it doesn't open the camera for web applications.
Here Chrome, Firefox, Opera and Safari all use the XMLHttprequest2 object and Internet Explorer uses the similar XDomainRequest object, object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('GET', url);
if (!xhr) {
throw new Error('CORS not supported');
}
onloadstart
Starts the request
onprogress
Loads the data and send the data
onabort
Abort the request
onerror
request has failed
onload
request load successfully
ontimeout
time out has happened before request could complete
onloadend
When the request is complete either successful or failure
xhr.onload = function() {
var responseText = xhr.responseText;
// process the response.
console.log(responseText);
};
xhr.onerror = function() {
console.log('There was an error!');
};
Below example will show the example of makeCorsRequest() and onload handler
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
// Helper method to parse the title tag from the response.
function getTitle(text) {
return text.match('<title>(.*)?</title>')[1];
}
// Make the actual CORS request.
function makeCorsRequest() {
// All HTML5 Rocks properties support CORS.
var url = 'http://www.tutorialspoint.com';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
var title = getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
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": 2731,
"s": 2608,
"text": "Cross-origin resource sharing (CORS) is a mechanism to allows the restricted resources from another domain in web browser."
},
{
"code": null,
"e": 2955,
"s": 2731,
"text": "For suppose, if you click on HTML5- video player in html5 demo sections. it will ask camera permission. if user allow the permission then only it will open the camera or else it doesn't open the camera for web applications."
},
{
"code": null,
"e": 3099,
"s": 2955,
"text": "Here Chrome, Firefox, Opera and Safari all use the XMLHttprequest2 object and Internet Explorer uses the similar XDomainRequest object, object."
},
{
"code": null,
"e": 3871,
"s": 3099,
"text": "function createCORSRequest(method, url) {\n var xhr = new XMLHttpRequest();\n \n if (\"withCredentials\" in xhr) {\n \n // Check if the XMLHttpRequest object has a \"withCredentials\" property.\n // \"withCredentials\" only exists on XMLHTTPRequest2 objects.\n xhr.open(method, url, true);\n } else if (typeof XDomainRequest != \"undefined\") {\n \n // Otherwise, check if XDomainRequest.\n // XDomainRequest only exists in IE, and is IE's way of making CORS requests.\n xhr = new XDomainRequest();\n xhr.open(method, url);\n } else {\n \n // Otherwise, CORS is not supported by the browser.\n xhr = null;\n }\n return xhr;\n}\n\nvar xhr = createCORSRequest('GET', url);\n\nif (!xhr) {\n throw new Error('CORS not supported');\n}"
},
{
"code": null,
"e": 3883,
"s": 3871,
"text": "onloadstart"
},
{
"code": null,
"e": 3902,
"s": 3883,
"text": "Starts the request"
},
{
"code": null,
"e": 3913,
"s": 3902,
"text": "onprogress"
},
{
"code": null,
"e": 3946,
"s": 3913,
"text": "Loads the data and send the data"
},
{
"code": null,
"e": 3954,
"s": 3946,
"text": "onabort"
},
{
"code": null,
"e": 3972,
"s": 3954,
"text": "Abort the request"
},
{
"code": null,
"e": 3980,
"s": 3972,
"text": "onerror"
},
{
"code": null,
"e": 3999,
"s": 3980,
"text": "request has failed"
},
{
"code": null,
"e": 4006,
"s": 3999,
"text": "onload"
},
{
"code": null,
"e": 4032,
"s": 4006,
"text": "request load successfully"
},
{
"code": null,
"e": 4042,
"s": 4032,
"text": "ontimeout"
},
{
"code": null,
"e": 4094,
"s": 4042,
"text": "time out has happened before request could complete"
},
{
"code": null,
"e": 4104,
"s": 4094,
"text": "onloadend"
},
{
"code": null,
"e": 4162,
"s": 4104,
"text": "When the request is complete either successful or failure"
},
{
"code": null,
"e": 4363,
"s": 4162,
"text": "xhr.onload = function() {\n var responseText = xhr.responseText;\n \n // process the response.\n console.log(responseText);\n};\n\nxhr.onerror = function() {\n console.log('There was an error!');\n};"
},
{
"code": null,
"e": 4439,
"s": 4363,
"text": "Below example will show the example of makeCorsRequest() and onload handler"
},
{
"code": null,
"e": 5651,
"s": 4439,
"text": "// Create the XHR object.\nfunction createCORSRequest(method, url) {\n var xhr = new XMLHttpRequest();\n \n if (\"withCredentials\" in xhr) {\n \n // XHR for Chrome/Firefox/Opera/Safari.\n xhr.open(method, url, true);\n } else if (typeof XDomainRequest != \"undefined\") {\n \n // XDomainRequest for IE.\n xhr = new XDomainRequest();\n xhr.open(method, url);\n } else {\n \n // CORS not supported.\n xhr = null;\n }\n return xhr;\n}\n\n// Helper method to parse the title tag from the response.\nfunction getTitle(text) {\n return text.match('<title>(.*)?</title>')[1];\n}\n\n// Make the actual CORS request.\nfunction makeCorsRequest() {\n \n // All HTML5 Rocks properties support CORS.\n var url = 'http://www.tutorialspoint.com';\n \n var xhr = createCORSRequest('GET', url);\n \n if (!xhr) {\n alert('CORS not supported');\n return;\n }\n \n // Response handlers.\n xhr.onload = function() {\n var text = xhr.responseText;\n var title = getTitle(text);\n alert('Response from CORS request to ' + url + ': ' + title);\n };\n \n xhr.onerror = function() {\n alert('Woops, there was an error making the request.');\n };\n xhr.send();\n}"
},
{
"code": null,
"e": 5684,
"s": 5651,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5698,
"s": 5684,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5733,
"s": 5698,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5747,
"s": 5733,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5782,
"s": 5747,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5799,
"s": 5782,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5834,
"s": 5799,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5865,
"s": 5834,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5898,
"s": 5865,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5929,
"s": 5898,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5964,
"s": 5929,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5995,
"s": 5964,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 6002,
"s": 5995,
"text": " Print"
},
{
"code": null,
"e": 6013,
"s": 6002,
"text": " Add Notes"
}
]
|
Get the size of all the documents in a MongoDB query? | To get the size of all the documents in a query, you need to loop through documents. Let us first create a collection with documents −
> db.sizeOfAllDocumentsDemo.insertOne({"StudentFirstName":"John","StudentSubject":["MongoDB","Java"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd3c0c1edc6604c74817cd7")
}
> db.sizeOfAllDocumentsDemo.insertOne({"StudentFirstName":"Larry","StudentSubject":["MySQL","PHP"],"StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd3c0d9edc6604c74817cd8")
}
> db.sizeOfAllDocumentsDemo.insertOne({"StudentFirstName":"Chris","StudentSubject":["SQL Server","C#"],"StudentAge":23,"StudentCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd3c0fbedc6604c74817cd9")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.sizeOfAllDocumentsDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd3c0c1edc6604c74817cd7"),
"StudentFirstName" : "John",
"StudentSubject" : [
"MongoDB",
"Java"
]
}
{
"_id" : ObjectId("5cd3c0d9edc6604c74817cd8"),
"StudentFirstName" : "Larry",
"StudentSubject" : [
"MySQL",
"PHP"
],
"StudentAge" : 21
}
{
"_id" : ObjectId("5cd3c0fbedc6604c74817cd9"),
"StudentFirstName" : "Chris",
"StudentSubject" : [
"SQL Server",
"C#"
],
"StudentAge" : 23,
"StudentCountryName" : "US"
}
Following is the query to get the size of all the documents in a query −
> var allDocument = db.sizeOfAllDocumentsDemo.find();
> var counter = 0;
> allDocument.forEach(
... function(myDocument) {
... counter = counter+Object.bsonsize(myDocument)
... }
... );
> print(counter);
This will produce the following output −
358 | [
{
"code": null,
"e": 1197,
"s": 1062,
"text": "To get the size of all the documents in a query, you need to loop through documents. Let us first create a collection with documents −"
},
{
"code": null,
"e": 1822,
"s": 1197,
"text": "> db.sizeOfAllDocumentsDemo.insertOne({\"StudentFirstName\":\"John\",\"StudentSubject\":[\"MongoDB\",\"Java\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd3c0c1edc6604c74817cd7\")\n}\n> db.sizeOfAllDocumentsDemo.insertOne({\"StudentFirstName\":\"Larry\",\"StudentSubject\":[\"MySQL\",\"PHP\"],\"StudentAge\":21});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd3c0d9edc6604c74817cd8\")\n}\n> db.sizeOfAllDocumentsDemo.insertOne({\"StudentFirstName\":\"Chris\",\"StudentSubject\":[\"SQL Server\",\"C#\"],\"StudentAge\":23,\"StudentCountryName\":\"US\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd3c0fbedc6604c74817cd9\")\n}"
},
{
"code": null,
"e": 1921,
"s": 1822,
"text": "Following is the query to display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1966,
"s": 1921,
"text": "> db.sizeOfAllDocumentsDemo.find().pretty();"
},
{
"code": null,
"e": 2007,
"s": 1966,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2515,
"s": 2007,
"text": "{\n \"_id\" : ObjectId(\"5cd3c0c1edc6604c74817cd7\"),\n \"StudentFirstName\" : \"John\",\n \"StudentSubject\" : [\n \"MongoDB\",\n \"Java\"\n ]\n}\n{\n \"_id\" : ObjectId(\"5cd3c0d9edc6604c74817cd8\"),\n \"StudentFirstName\" : \"Larry\",\n \"StudentSubject\" : [\n \"MySQL\",\n \"PHP\"\n ],\n \"StudentAge\" : 21\n}\n{\n \"_id\" : ObjectId(\"5cd3c0fbedc6604c74817cd9\"),\n \"StudentFirstName\" : \"Chris\",\n \"StudentSubject\" : [\n \"SQL Server\",\n \"C#\"\n ],\n \"StudentAge\" : 23,\n \"StudentCountryName\" : \"US\"\n}"
},
{
"code": null,
"e": 2588,
"s": 2515,
"text": "Following is the query to get the size of all the documents in a query −"
},
{
"code": null,
"e": 2802,
"s": 2588,
"text": "> var allDocument = db.sizeOfAllDocumentsDemo.find();\n> var counter = 0;\n> allDocument.forEach(\n... function(myDocument) {\n... counter = counter+Object.bsonsize(myDocument)\n... }\n... );\n\n> print(counter);"
},
{
"code": null,
"e": 2843,
"s": 2802,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2847,
"s": 2843,
"text": "358"
}
]
|
Count number of triplets (a, b, c) such that a^2 + b^2 = c^2 and 1 <= a <= b <= c <= n - GeeksforGeeks | 22 Apr, 2021
Given an integer N, the task is to count the number of triplets (a, b, c) such that a2 + b2 = c2 and 1 ≤ a ≤ b ≤ c ≤ N.
Examples:
Input: N = 5 Output: 1 The only possible triplet pair is (3, 4, 5) 3^2 + 4^2 = 5^2 i.e. 9 + 16 = 25
Input: N = 10 Output: 2 (3, 4, 5) and (6, 8, 10) are the required triplet pairs.
Method-1: Run two loop one from i = 1 to N and second from j = i+1 to N. Consider each and every pair and find i*i + j*j and check if this is a perfect square and its square root is less than N. If yes then increment the count.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to Find number of// Triplets 1 <= a <= b<= c <= n,// Such that a^2 + b^2 = c^2#include <bits/stdc++.h>using namespace std; // function to ind number of// Triplets 1 <= a <= b<= c <= n,// Such that a^2 + b^2 = c^2int Triplets(int n){ // to store required answer int ans = 0; // run nested loops for first two numbers. for (int i = 1; i <= n; ++i) { for (int j = i; j <= n; ++j) { int x = i * i + j * j; // third number int y = sqrt(x); // check if third number is perfect // square and less than n if (y * y == x && y <= n) ++ans; } } return ans;} // Driver codeint main(){ int n = 10; // function call cout << Triplets(n); return 0;}
// Java program to Find number of// Triplets 1 <= a <= b<= c <= n,// Such that a^2 + b^2 = c^2class Solution{// function to ind number of// Triplets 1 <= a <= b<= c <= n,// Such that a^2 + b^2 = c^2static int Triplets(int n){ // to store required answer int ans = 0; // run nested loops for first two numbers. for (int i = 1; i <= n; ++i) { for (int j = i; j <= n; ++j) { int x = i * i + j * j; // third number int y =(int) Math.sqrt(x); // check if third number is perfect // square and less than n if (y * y == x && y <= n) ++ans; } } return ans;} // Driver codepublic static void main(String args[]){ int n = 10; // function call System.out.println(Triplets(n)); }}//contributed by Arnab Kundu
# Python3 program to Find number of# Triplets 1 <= a <= b<= c <= n,# Such that a^2 + b^2 = c^2import math # function to ind number of# Triplets 1 <= a <= b<= c <= n,# Such that a^2 + b^2 = c^2def Triplets(n): # to store required answer ans = 0 # run nested loops for first two numbers. for i in range(1, n + 1): for j in range(i, n + 1): x = i * i + j * j # third number y = int(math.sqrt(x)) # check if third number is perfect # square and less than n if (y * y == x and y <= n): ans += 1 return ans # Driver codeif __name__ == "__main__": n = 10 # function call print(Triplets(n)) # This code is contributed# by ChitraNayal
// C# program to Find number of// Triplets 1 <= a <= b<= c <= n,// Such that a^2 + b^2 = c^2using System; class GFG{// function to ind number of// Triplets 1 <= a <= b<= c <= n,// Such that a^2 + b^2 = c^2static int Triplets(int n){ // to store required answer int ans = 0; // run nested loops for first two numbers. for (int i = 1; i <= n; ++i) { for (int j = i; j <= n; ++j) { int x = i * i + j * j; // third number int y = (int)Math.Sqrt(x); // check if third number is perfect // square and less than n if (y * y == x && y <= n) ++ans; } } return ans;} // Driver codestatic void Main(){ int n = 10; Console.WriteLine(Triplets(n));}} // This code is contributed by ANKITRAI1
<?php// PHP program to Find number of// Triplets 1 <= a <= b<= c <= n,// Such that a^2 + b^2 = c^2 // Function to ind number of// Triplets 1 <= a <= b<= c <= n,// Such that a^2 + b^2 = c^2function Triplets($n){ // to store required answer $ans = 0; // run nested loops for first // two numbers. for ($i = 1; $i <= $n; ++$i) { for ($j =$i; $j <= $n; ++$j) { $x = $i * $i + $j * $j; // third number $y = (int)sqrt($x); // check if third number is perfect // square and less than n if ($y * $y == $x && $y <= $n) ++$ans; } } return $ans;} // Driver code$n = 10; // function callecho Triplets($n); // This code is contributed by mits?>
<script>// javascript program to Find number of// Triplets 1 <= a <= b<= c <= n,// Such that a^2 + b^2 = c^2 // function to ind number of // Triplets 1 <= a <= b<= c <= n, // Such that a^2 + b^2 = c^2 function Triplets(n) { // to store required answer var ans = 0; // run nested loops for first two numbers. for (let i = 1; i <= n; ++i) { for (let j = i; j <= n; ++j) { var x = i * i + j * j; // third number var y = parseInt( Math.sqrt(x)); // check if third number is perfect // square and less than n if (y * y == x && y <= n) ++ans; } } return ans; } // Driver code var n = 10; // function call document.write(Triplets(n)); // This code is contributed by shikhasingrajput</script>
2
Method-2:
Find all the perfect squares upto n2 and save it to an ArrayList.
Now for every a from 1 to n, do the following: Choose c2 from the list of perfect squares calculated earlier.Then b2 can be calculated as b2 = c2 – a2.Now check if a <= b <= c and b2 calculated in the previous step must be a perfect square.If the above conditions are satisfied then increment the count.
Choose c2 from the list of perfect squares calculated earlier.
Then b2 can be calculated as b2 = c2 – a2.
Now check if a <= b <= c and b2 calculated in the previous step must be a perfect square.
If the above conditions are satisfied then increment the count.
Print the count in the end.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return an Array containing// all the perfect squares upto nvector<int> getPerfectSquares(int n){ vector<int> perfectSquares; int current = 1, i = 1; // While current perfect square // is less than or equal to n while (current <= n) { perfectSquares.push_back(current); current = pow(++i, 2); } return perfectSquares;} // Function to return the count of// triplet (a, b, c) pairs such that// a^2 + b^2 = c^2 and// 1 <= a <= b <= c <= nint countTriplets(int n){ // Vector of perfect squares upto n^2 vector<int> perfectSquares = getPerfectSquares( pow(n, 2)); int count = 0; for(int a = 1; a <= n; a++) { int aSquare = pow(a, 2); for(int i = 0; i < perfectSquares.size(); i++) { int cSquare = perfectSquares[i]; // Since, a^2 + b^2 = c^2 int bSquare = abs(cSquare - aSquare); int b = sqrt(bSquare); int c = sqrt(cSquare); // If c < a or bSquare is not a // perfect square if (c < a || (find(perfectSquares.begin(), perfectSquares.end(), bSquare) == perfectSquares.end())) continue; // If triplet pair (a, b, c) satisfy // the given condition if ((b >= a) && (b <= c) && (aSquare + bSquare == cSquare)) count++; } } return count;} // Driver codeint main(){ int n = 10; cout << countTriplets(n); return 0;} // This code is contributed by himanshu77
// Java implementation of the approachimport java.util.*; public class GFG { // Function to return an ArrayList containing // all the perfect squares upto n public static ArrayList<Integer> getPerfectSquares(int n) { ArrayList<Integer> perfectSquares = new ArrayList<>(); int current = 1, i = 1; // while current perfect square is less than or equal to n while (current <= n) { perfectSquares.add(current); current = (int)Math.pow(++i, 2); } return perfectSquares; } // Function to return the count of triplet (a, b, c) pairs // such that a^2 + b^2 = c^2 and 1 <= a <= b <= c <= n public static int countTriplets(int n) { // List of perfect squares upto n^2 ArrayList<Integer> perfectSquares = getPerfectSquares((int)Math.pow(n, 2)); int count = 0; for (int a = 1; a <= n; a++) { int aSquare = (int)Math.pow(a, 2); for (int i = 0; i < perfectSquares.size(); i++) { int cSquare = perfectSquares.get(i); // Since, a^2 + b^2 = c^2 int bSquare = cSquare - aSquare; int b = (int)Math.sqrt(bSquare); int c = (int)Math.sqrt(cSquare); // If c < a or bSquare is not a perfect square if (c < a || !perfectSquares.contains(bSquare)) continue; // If triplet pair (a, b, c) satisfy the given condition if ((b >= a) && (b <= c) && (aSquare + bSquare == cSquare)) count++; } } return count; } // Driver code public static void main(String[] args) { int n = 10; System.out.println(countTriplets(n)); }}
# Python3 implementation of the approachimport math # Function to return an ArrayList containing# all the perfect squares upto ndef getPerfectSquares(n): perfectSquares = [] current = 1 i = 1 # while current perfect square is less than or equal to n while (current <= n) : perfectSquares.append(current) i += 1 current = i** 2 return perfectSquares # Function to return the count of triplet (a, b, c) pairs# such that a^2 + b^2 = c^2 and 1 <= a <= b <= c <= ndef countTriplets(n): # List of perfect squares upto n^2 perfectSquares= getPerfectSquares(n**2) count = 0 for a in range(1, n +1 ): aSquare = a**2 for i in range(len(perfectSquares)): cSquare = perfectSquares[i] # Since, a^2 + b^2 = c^2 bSquare = abs(cSquare - aSquare) b = math.sqrt(bSquare) b = int(b) c = math.sqrt(cSquare) c = int(c) # If c < a or bSquare is not a perfect square if (c < a or (bSquare not in perfectSquares)): continue # If triplet pair (a, b, c) satisfy the given condition if ((b >= a) and (b <= c) and (aSquare + bSquare == cSquare)): count += 1 return count # Driver codeif __name__ == "__main__": n = 10 print(countTriplets(n)) # This code is contributed by chitranayal
// C# implementation of the approachusing System.Collections;using System; class GFG{ // Function to return an ArrayList containing// all the perfect squares upto npublic static ArrayList getPerfectSquares(int n){ ArrayList perfectSquares = new ArrayList(); int current = 1, i = 1; // while current perfect square is less // than or equal to n while (current <= n) { perfectSquares.Add(current); current = (int)Math.Pow(++i, 2); } return perfectSquares;} // Function to return the count of triplet// (a, b, c) pairs such that a^2 + b^2 = c^2// and 1 <= a <= b <= c <= npublic static int countTriplets(int n){ // List of perfect squares upto n^2 ArrayList perfectSquares = getPerfectSquares((int)Math.Pow(n, 2)); int count = 0; for (int a = 1; a <= n; a++) { int aSquare = (int)Math.Pow(a, 2); for (int i = 0; i < perfectSquares.Count; i++) { int cSquare = (int)perfectSquares[i]; // Since, a^2 + b^2 = c^2 int bSquare = cSquare - aSquare; int b = (int)Math.Sqrt(bSquare); int c = (int)Math.Sqrt(cSquare); // If c < a or bSquare is not a perfect square if (c < a || !perfectSquares.Contains(bSquare)) continue; // If triplet pair (a, b, c) satisfy // the given condition if ((b >= a) && (b <= c) && (aSquare + bSquare == cSquare)) count++; } } return count;} // Driver codepublic static void Main(){ int n = 10; Console.WriteLine(countTriplets(n));}} // This code is contributed by mits.
<script> // Javascript implementation of the approach // Function to return an Array containing// all the perfect squares upto nfunction getPerfectSquares(n){ var perfectSquares = []; var current = 1, i = 1; // While current perfect square // is less than or equal to n while (current <= n) { perfectSquares.push(current); current = Math.pow(++i, 2); } return perfectSquares;} // Function to return the count of// triplet (a, b, c) pairs such that// a^2 + b^2 = c^2 and// 1 <= a <= b <= c <= nfunction countTriplets(n){ // Vector of perfect squares upto n^2 var perfectSquares = getPerfectSquares( Math.pow(n, 2)); var count = 0; for(var a = 1; a <= n; a++) { var aSquare = Math.pow(a, 2); for(var i = 0; i < perfectSquares.length; i++) { var cSquare = perfectSquares[i]; // Since, a^2 + b^2 = c^2 var bSquare = Math.abs(cSquare - aSquare); var b = Math.sqrt(bSquare); var c = Math.sqrt(cSquare); // If c < a or bSquare is not a // perfect square if (c < a || !perfectSquares.includes(bSquare)) continue; // If triplet pair (a, b, c) satisfy // the given condition if ((b >= a) && (b <= c) && (aSquare + bSquare == cSquare)) count++; } } return count;} // Driver codevar n = 10; document.write(countTriplets(n)); // This code is contributed by noob2000 </script>
2
andrew1234
ankthon
ukasp
Mithun Kumar
himanshu77
shikhasingrajput
noob2000
maths-perfect-square
Competitive Programming
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming
Bits manipulation (Important tactics)
Formatted output in Java
Shortest path in a directed graph by Dijkstra’s algorithm
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 25260,
"s": 25232,
"text": "\n22 Apr, 2021"
},
{
"code": null,
"e": 25380,
"s": 25260,
"text": "Given an integer N, the task is to count the number of triplets (a, b, c) such that a2 + b2 = c2 and 1 ≤ a ≤ b ≤ c ≤ N."
},
{
"code": null,
"e": 25391,
"s": 25380,
"text": "Examples: "
},
{
"code": null,
"e": 25491,
"s": 25391,
"text": "Input: N = 5 Output: 1 The only possible triplet pair is (3, 4, 5) 3^2 + 4^2 = 5^2 i.e. 9 + 16 = 25"
},
{
"code": null,
"e": 25574,
"s": 25491,
"text": "Input: N = 10 Output: 2 (3, 4, 5) and (6, 8, 10) are the required triplet pairs. "
},
{
"code": null,
"e": 25802,
"s": 25574,
"text": "Method-1: Run two loop one from i = 1 to N and second from j = i+1 to N. Consider each and every pair and find i*i + j*j and check if this is a perfect square and its square root is less than N. If yes then increment the count."
},
{
"code": null,
"e": 25855,
"s": 25802,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25859,
"s": 25855,
"text": "C++"
},
{
"code": null,
"e": 25864,
"s": 25859,
"text": "Java"
},
{
"code": null,
"e": 25872,
"s": 25864,
"text": "Python3"
},
{
"code": null,
"e": 25875,
"s": 25872,
"text": "C#"
},
{
"code": null,
"e": 25879,
"s": 25875,
"text": "PHP"
},
{
"code": null,
"e": 25890,
"s": 25879,
"text": "Javascript"
},
{
"code": "// C++ program to Find number of// Triplets 1 <= a <= b<= c <= n,// Such that a^2 + b^2 = c^2#include <bits/stdc++.h>using namespace std; // function to ind number of// Triplets 1 <= a <= b<= c <= n,// Such that a^2 + b^2 = c^2int Triplets(int n){ // to store required answer int ans = 0; // run nested loops for first two numbers. for (int i = 1; i <= n; ++i) { for (int j = i; j <= n; ++j) { int x = i * i + j * j; // third number int y = sqrt(x); // check if third number is perfect // square and less than n if (y * y == x && y <= n) ++ans; } } return ans;} // Driver codeint main(){ int n = 10; // function call cout << Triplets(n); return 0;}",
"e": 26671,
"s": 25890,
"text": null
},
{
"code": "// Java program to Find number of// Triplets 1 <= a <= b<= c <= n,// Such that a^2 + b^2 = c^2class Solution{// function to ind number of// Triplets 1 <= a <= b<= c <= n,// Such that a^2 + b^2 = c^2static int Triplets(int n){ // to store required answer int ans = 0; // run nested loops for first two numbers. for (int i = 1; i <= n; ++i) { for (int j = i; j <= n; ++j) { int x = i * i + j * j; // third number int y =(int) Math.sqrt(x); // check if third number is perfect // square and less than n if (y * y == x && y <= n) ++ans; } } return ans;} // Driver codepublic static void main(String args[]){ int n = 10; // function call System.out.println(Triplets(n)); }}//contributed by Arnab Kundu",
"e": 27496,
"s": 26671,
"text": null
},
{
"code": "# Python3 program to Find number of# Triplets 1 <= a <= b<= c <= n,# Such that a^2 + b^2 = c^2import math # function to ind number of# Triplets 1 <= a <= b<= c <= n,# Such that a^2 + b^2 = c^2def Triplets(n): # to store required answer ans = 0 # run nested loops for first two numbers. for i in range(1, n + 1): for j in range(i, n + 1): x = i * i + j * j # third number y = int(math.sqrt(x)) # check if third number is perfect # square and less than n if (y * y == x and y <= n): ans += 1 return ans # Driver codeif __name__ == \"__main__\": n = 10 # function call print(Triplets(n)) # This code is contributed# by ChitraNayal",
"e": 28239,
"s": 27496,
"text": null
},
{
"code": "// C# program to Find number of// Triplets 1 <= a <= b<= c <= n,// Such that a^2 + b^2 = c^2using System; class GFG{// function to ind number of// Triplets 1 <= a <= b<= c <= n,// Such that a^2 + b^2 = c^2static int Triplets(int n){ // to store required answer int ans = 0; // run nested loops for first two numbers. for (int i = 1; i <= n; ++i) { for (int j = i; j <= n; ++j) { int x = i * i + j * j; // third number int y = (int)Math.Sqrt(x); // check if third number is perfect // square and less than n if (y * y == x && y <= n) ++ans; } } return ans;} // Driver codestatic void Main(){ int n = 10; Console.WriteLine(Triplets(n));}} // This code is contributed by ANKITRAI1",
"e": 29050,
"s": 28239,
"text": null
},
{
"code": "<?php// PHP program to Find number of// Triplets 1 <= a <= b<= c <= n,// Such that a^2 + b^2 = c^2 // Function to ind number of// Triplets 1 <= a <= b<= c <= n,// Such that a^2 + b^2 = c^2function Triplets($n){ // to store required answer $ans = 0; // run nested loops for first // two numbers. for ($i = 1; $i <= $n; ++$i) { for ($j =$i; $j <= $n; ++$j) { $x = $i * $i + $j * $j; // third number $y = (int)sqrt($x); // check if third number is perfect // square and less than n if ($y * $y == $x && $y <= $n) ++$ans; } } return $ans;} // Driver code$n = 10; // function callecho Triplets($n); // This code is contributed by mits?>",
"e": 29812,
"s": 29050,
"text": null
},
{
"code": "<script>// javascript program to Find number of// Triplets 1 <= a <= b<= c <= n,// Such that a^2 + b^2 = c^2 // function to ind number of // Triplets 1 <= a <= b<= c <= n, // Such that a^2 + b^2 = c^2 function Triplets(n) { // to store required answer var ans = 0; // run nested loops for first two numbers. for (let i = 1; i <= n; ++i) { for (let j = i; j <= n; ++j) { var x = i * i + j * j; // third number var y = parseInt( Math.sqrt(x)); // check if third number is perfect // square and less than n if (y * y == x && y <= n) ++ans; } } return ans; } // Driver code var n = 10; // function call document.write(Triplets(n)); // This code is contributed by shikhasingrajput</script>",
"e": 30711,
"s": 29812,
"text": null
},
{
"code": null,
"e": 30713,
"s": 30711,
"text": "2"
},
{
"code": null,
"e": 30726,
"s": 30715,
"text": "Method-2: "
},
{
"code": null,
"e": 30792,
"s": 30726,
"text": "Find all the perfect squares upto n2 and save it to an ArrayList."
},
{
"code": null,
"e": 31096,
"s": 30792,
"text": "Now for every a from 1 to n, do the following: Choose c2 from the list of perfect squares calculated earlier.Then b2 can be calculated as b2 = c2 – a2.Now check if a <= b <= c and b2 calculated in the previous step must be a perfect square.If the above conditions are satisfied then increment the count."
},
{
"code": null,
"e": 31159,
"s": 31096,
"text": "Choose c2 from the list of perfect squares calculated earlier."
},
{
"code": null,
"e": 31202,
"s": 31159,
"text": "Then b2 can be calculated as b2 = c2 – a2."
},
{
"code": null,
"e": 31292,
"s": 31202,
"text": "Now check if a <= b <= c and b2 calculated in the previous step must be a perfect square."
},
{
"code": null,
"e": 31356,
"s": 31292,
"text": "If the above conditions are satisfied then increment the count."
},
{
"code": null,
"e": 31384,
"s": 31356,
"text": "Print the count in the end."
},
{
"code": null,
"e": 31437,
"s": 31384,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 31441,
"s": 31437,
"text": "C++"
},
{
"code": null,
"e": 31446,
"s": 31441,
"text": "Java"
},
{
"code": null,
"e": 31454,
"s": 31446,
"text": "Python3"
},
{
"code": null,
"e": 31457,
"s": 31454,
"text": "C#"
},
{
"code": null,
"e": 31468,
"s": 31457,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return an Array containing// all the perfect squares upto nvector<int> getPerfectSquares(int n){ vector<int> perfectSquares; int current = 1, i = 1; // While current perfect square // is less than or equal to n while (current <= n) { perfectSquares.push_back(current); current = pow(++i, 2); } return perfectSquares;} // Function to return the count of// triplet (a, b, c) pairs such that// a^2 + b^2 = c^2 and// 1 <= a <= b <= c <= nint countTriplets(int n){ // Vector of perfect squares upto n^2 vector<int> perfectSquares = getPerfectSquares( pow(n, 2)); int count = 0; for(int a = 1; a <= n; a++) { int aSquare = pow(a, 2); for(int i = 0; i < perfectSquares.size(); i++) { int cSquare = perfectSquares[i]; // Since, a^2 + b^2 = c^2 int bSquare = abs(cSquare - aSquare); int b = sqrt(bSquare); int c = sqrt(cSquare); // If c < a or bSquare is not a // perfect square if (c < a || (find(perfectSquares.begin(), perfectSquares.end(), bSquare) == perfectSquares.end())) continue; // If triplet pair (a, b, c) satisfy // the given condition if ((b >= a) && (b <= c) && (aSquare + bSquare == cSquare)) count++; } } return count;} // Driver codeint main(){ int n = 10; cout << countTriplets(n); return 0;} // This code is contributed by himanshu77",
"e": 33210,
"s": 31468,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; public class GFG { // Function to return an ArrayList containing // all the perfect squares upto n public static ArrayList<Integer> getPerfectSquares(int n) { ArrayList<Integer> perfectSquares = new ArrayList<>(); int current = 1, i = 1; // while current perfect square is less than or equal to n while (current <= n) { perfectSquares.add(current); current = (int)Math.pow(++i, 2); } return perfectSquares; } // Function to return the count of triplet (a, b, c) pairs // such that a^2 + b^2 = c^2 and 1 <= a <= b <= c <= n public static int countTriplets(int n) { // List of perfect squares upto n^2 ArrayList<Integer> perfectSquares = getPerfectSquares((int)Math.pow(n, 2)); int count = 0; for (int a = 1; a <= n; a++) { int aSquare = (int)Math.pow(a, 2); for (int i = 0; i < perfectSquares.size(); i++) { int cSquare = perfectSquares.get(i); // Since, a^2 + b^2 = c^2 int bSquare = cSquare - aSquare; int b = (int)Math.sqrt(bSquare); int c = (int)Math.sqrt(cSquare); // If c < a or bSquare is not a perfect square if (c < a || !perfectSquares.contains(bSquare)) continue; // If triplet pair (a, b, c) satisfy the given condition if ((b >= a) && (b <= c) && (aSquare + bSquare == cSquare)) count++; } } return count; } // Driver code public static void main(String[] args) { int n = 10; System.out.println(countTriplets(n)); }}",
"e": 34985,
"s": 33210,
"text": null
},
{
"code": "# Python3 implementation of the approachimport math # Function to return an ArrayList containing# all the perfect squares upto ndef getPerfectSquares(n): perfectSquares = [] current = 1 i = 1 # while current perfect square is less than or equal to n while (current <= n) : perfectSquares.append(current) i += 1 current = i** 2 return perfectSquares # Function to return the count of triplet (a, b, c) pairs# such that a^2 + b^2 = c^2 and 1 <= a <= b <= c <= ndef countTriplets(n): # List of perfect squares upto n^2 perfectSquares= getPerfectSquares(n**2) count = 0 for a in range(1, n +1 ): aSquare = a**2 for i in range(len(perfectSquares)): cSquare = perfectSquares[i] # Since, a^2 + b^2 = c^2 bSquare = abs(cSquare - aSquare) b = math.sqrt(bSquare) b = int(b) c = math.sqrt(cSquare) c = int(c) # If c < a or bSquare is not a perfect square if (c < a or (bSquare not in perfectSquares)): continue # If triplet pair (a, b, c) satisfy the given condition if ((b >= a) and (b <= c) and (aSquare + bSquare == cSquare)): count += 1 return count # Driver codeif __name__ == \"__main__\": n = 10 print(countTriplets(n)) # This code is contributed by chitranayal",
"e": 36410,
"s": 34985,
"text": null
},
{
"code": "// C# implementation of the approachusing System.Collections;using System; class GFG{ // Function to return an ArrayList containing// all the perfect squares upto npublic static ArrayList getPerfectSquares(int n){ ArrayList perfectSquares = new ArrayList(); int current = 1, i = 1; // while current perfect square is less // than or equal to n while (current <= n) { perfectSquares.Add(current); current = (int)Math.Pow(++i, 2); } return perfectSquares;} // Function to return the count of triplet// (a, b, c) pairs such that a^2 + b^2 = c^2// and 1 <= a <= b <= c <= npublic static int countTriplets(int n){ // List of perfect squares upto n^2 ArrayList perfectSquares = getPerfectSquares((int)Math.Pow(n, 2)); int count = 0; for (int a = 1; a <= n; a++) { int aSquare = (int)Math.Pow(a, 2); for (int i = 0; i < perfectSquares.Count; i++) { int cSquare = (int)perfectSquares[i]; // Since, a^2 + b^2 = c^2 int bSquare = cSquare - aSquare; int b = (int)Math.Sqrt(bSquare); int c = (int)Math.Sqrt(cSquare); // If c < a or bSquare is not a perfect square if (c < a || !perfectSquares.Contains(bSquare)) continue; // If triplet pair (a, b, c) satisfy // the given condition if ((b >= a) && (b <= c) && (aSquare + bSquare == cSquare)) count++; } } return count;} // Driver codepublic static void Main(){ int n = 10; Console.WriteLine(countTriplets(n));}} // This code is contributed by mits.",
"e": 38051,
"s": 36410,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return an Array containing// all the perfect squares upto nfunction getPerfectSquares(n){ var perfectSquares = []; var current = 1, i = 1; // While current perfect square // is less than or equal to n while (current <= n) { perfectSquares.push(current); current = Math.pow(++i, 2); } return perfectSquares;} // Function to return the count of// triplet (a, b, c) pairs such that// a^2 + b^2 = c^2 and// 1 <= a <= b <= c <= nfunction countTriplets(n){ // Vector of perfect squares upto n^2 var perfectSquares = getPerfectSquares( Math.pow(n, 2)); var count = 0; for(var a = 1; a <= n; a++) { var aSquare = Math.pow(a, 2); for(var i = 0; i < perfectSquares.length; i++) { var cSquare = perfectSquares[i]; // Since, a^2 + b^2 = c^2 var bSquare = Math.abs(cSquare - aSquare); var b = Math.sqrt(bSquare); var c = Math.sqrt(cSquare); // If c < a or bSquare is not a // perfect square if (c < a || !perfectSquares.includes(bSquare)) continue; // If triplet pair (a, b, c) satisfy // the given condition if ((b >= a) && (b <= c) && (aSquare + bSquare == cSquare)) count++; } } return count;} // Driver codevar n = 10; document.write(countTriplets(n)); // This code is contributed by noob2000 </script>",
"e": 39688,
"s": 38051,
"text": null
},
{
"code": null,
"e": 39690,
"s": 39688,
"text": "2"
},
{
"code": null,
"e": 39703,
"s": 39692,
"text": "andrew1234"
},
{
"code": null,
"e": 39711,
"s": 39703,
"text": "ankthon"
},
{
"code": null,
"e": 39717,
"s": 39711,
"text": "ukasp"
},
{
"code": null,
"e": 39730,
"s": 39717,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 39741,
"s": 39730,
"text": "himanshu77"
},
{
"code": null,
"e": 39758,
"s": 39741,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 39767,
"s": 39758,
"text": "noob2000"
},
{
"code": null,
"e": 39788,
"s": 39767,
"text": "maths-perfect-square"
},
{
"code": null,
"e": 39812,
"s": 39788,
"text": "Competitive Programming"
},
{
"code": null,
"e": 39825,
"s": 39812,
"text": "Mathematical"
},
{
"code": null,
"e": 39838,
"s": 39825,
"text": "Mathematical"
},
{
"code": null,
"e": 39936,
"s": 39838,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39945,
"s": 39936,
"text": "Comments"
},
{
"code": null,
"e": 39958,
"s": 39945,
"text": "Old Comments"
},
{
"code": null,
"e": 39985,
"s": 39958,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 40063,
"s": 39985,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
},
{
"code": null,
"e": 40101,
"s": 40063,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 40126,
"s": 40101,
"text": "Formatted output in Java"
},
{
"code": null,
"e": 40184,
"s": 40126,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 40214,
"s": 40184,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 40274,
"s": 40214,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 40289,
"s": 40274,
"text": "C++ Data Types"
},
{
"code": null,
"e": 40332,
"s": 40289,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
Find all divisors of first N natural numbers - GeeksforGeeks | 29 Apr, 2021
Given an integer N, the task is to find all the divisors of numbers from 1 to N.Note: 1 ? N ? 100000
Examples:
Input: N = 2 Output: 1 –>1 2 –>1, 2
Input: N = 5 Output: 1 –>1 2 –>1, 2 3 –>1, 3 4 –>1, 2, 4 5 –>1, 5
Naive Approach:
Iterate over first N natural numbers using a loop variable (say i)
Iterate over the natural numbers from 1 to i with a loop variable (say j) and check that i % j == 0. Then j is a divisor of the natural number i.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find all// the divisors of the first N// natural numbers #include <bits/stdc++.h> using namespace std; // Function to find the divisors// of the first N natural numbersvoid factors(int n){ int i, j; cout << "1 -->1\n"; // Loop to find the divisors for (i = 2; i <= n; i++) { cout << i << " -->"; for (j = 1; j <= i / 2; j++) { if (i % j == 0) cout << j << ", "; } cout << i << "\n"; }} // Driver Codeint main(){ int n = 5; factors(n);}
// Java implementation to find all// the divisors of the first N// natural numbersclass GFG{ // Function to find the divisors// of the first N natural numbersstatic void factors(int n){ int i, j; System.out.print("1 -->1\n"); // Loop to find the divisors for(i = 2; i <= n; i++) { System.out.print(i + " -->"); for(j = 1; j <= i / 2; j++) { if (i % j == 0) System.out.print(j + ", "); } System.out.print(i + "\n"); }} // Driver Codepublic static void main(String[] args){ int n = 5; factors(n);}} // This code is contributed by Rohit_ranjan
# Python3 implementation to find all# the divisors of the first N# natural numbers # Function to find the divisors# of the first N natural numbersdef factors(n): i = 0; j = 0; print("1 -->1"); # Loop to find the divisors for i in range(2, n + 1): print(i, "-->", end = ""); for j in range(1, (i // 2) + 1): if (i % j == 0): print(j, ",", end = ""); print(i, end = "\n"); # Driver Coden = 5;factors(n); # This code is contributed by Code_Mech
// C# implementation to find all// the divisors of the first N// natural numbersusing System;class GFG{ // Function to find the divisors// of the first N natural numbersstatic void factors(int n){ int i, j; Console.Write("1 -->1\n"); // Loop to find the divisors for(i = 2; i <= n; i++) { Console.Write(i + " -->"); for(j = 1; j <= i / 2; j++) { if (i % j == 0) Console.Write(j + ", "); } Console.Write(i + "\n"); }} // Driver Codepublic static void Main(){ int n = 5; factors(n);}} // This code is contributed by Nidhi_biet
<script> // JavaScript implementation to find all// the divisors of the first N// natural numbers // Function to find the divisors// of the first N natural numbersfunction factors(n){ let i, j; document.write("1 -->1<br>"); // Loop to find the divisors for (i = 2; i <= n; i++) { document.write(i + " -->"); for (j = 1; j <= parseInt(i / 2); j++) { if (i % j == 0) document.write(j + ", "); } document.write(i + "<br>"); }} // Driver Codelet n = 5;factors(n); </script>
1 -->1
2 -->1, 2
3 -->1, 3
4 -->1, 2, 4
5 -->1, 5
Time Complexity: O(N2)
Better Approach:
Iterate over the first N natural numbers using a loop variable.
For the number to find its divisors iterate from 2 to that number and check any one of them is a divisor of the given number.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find all// the divisors of the first// N natural numbers #include <bits/stdc++.h> using namespace std; // Function to find the factors of// the numbers from 1 to Nvoid factors(int n){ int i, j; cout << "1 -->1\n"; // Loop to find the factors // of the first N natural // numbers of the integer for (i = 2; i <= n; i++) { cout << i << " -->"; for (j = 1; j * j <= i; j++) { if (i % j == 0){ cout << j << ", "; if (i / j != j) cout << i/j << ", "; } } cout << "\n"; }} // Driver Codeint main(){ int n = 5; factors(n);}
// Java implementation to find all// the divisors of the first// N natural numbersimport java.util.*;class GFG{ // Function to find the factors of// the numbers from 1 to Nstatic void factors(int n){ int i, j; System.out.print("1 -->1\n"); // Loop to find the factors // of the first N natural // numbers of the integer for (i = 2; i <= n; i++) { System.out.print(i + " -->"); for (j = 1; j * j <= i; j++) { if (i % j == 0) { System.out.print(j + ", "); if (i / j != j) System.out.print(i / j + ", "); } } System.out.print("\n"); }} // Driver Codepublic static void main(String args[]){ int n = 5; factors(n);}} // This code is contributed by Code_Mech
# Python3 implementation to find all# the divisors of the first# N natural numbers # Function to find the factors of# the numbers from 1 to Ndef factors(n): print("1 -->1"); # Loop to find the factors # of the first N natural # numbers of the integer for i in range(2, n + 1): print(i, " -->", end = ""); for j in range(1, int(pow(i, 1))): if (i % j == 0): print(j, ", ", end = ""); if (i // j != j): print(i // j, ", ", end = ""); print(end = "\n"); # Driver Codeif __name__ == '__main__': n = 5; factors(n); # This code is contributed by gauravrajput1
// C# implementation to find all// the divisors of the first// N natural numbersusing System;class GFG{ // Function to find the factors of// the numbers from 1 to Nstatic void factors(int n){ int i, j; Console.Write("1 -->1\n"); // Loop to find the factors // of the first N natural // numbers of the integer for (i = 2; i <= n; i++) { Console.Write(i + " -->"); for (j = 1; j * j <= i; j++) { if (i % j == 0) { Console.Write(j + ", "); if (i / j != j) Console.Write(i / j + ", "); } } Console.Write("\n"); }} // Driver Codepublic static void Main(){ int n = 5; factors(n);}} // This code is contributed by Code_Mech
<script> // Javascript implementation to find all// the divisors of the first// N natural numbers // Function to find the factors of// the numbers from 1 to Nfunction factors(n){ let i, j; document.write("1 -->1<br>"); // Loop to find the factors // of the first N natural // numbers of the integer for(i = 2; i <= n; i++) { document.write(i + " -->"); for(j = 1; j * j <= i; j++) { if (i % j == 0) { document.write(j + ", "); if (parseInt(i / j) != j) document.write(parseInt(i/j) + ", "); } } document.write("<br>"); }} // Driver Codelet n = 5;factors(n); // This code is contributed by subhammahato348 </script>
1 -->1
2 -->1, 2,
3 -->1, 3,
4 -->1, 4, 2,
5 -->1, 5,
Time Complexity: O(N*sqrt(N))
Efficient Approach: The idea is to precompute the factors of the numbers with the help of the Sieve of Eratosthenes. Then finally iterate over the first N natural numbers to find the factors.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find the// factors of first N natural// numbers #include <bits/stdc++.h> using namespace std; const int MAX = 1e5; // Initialize global divisor vector// array of sequence containervector<int> divisor[MAX + 1]; // Calculate all// divisors of numbervoid sieve(){ for (int i = 1; i <= MAX; ++i) { for (int j = i; j <= MAX; j += i) divisor[j].push_back(i); }} // Function to find the// factors of first n// natural numbersvoid findNFactors(int n){ for(int i = 1; i <= n; i++){ cout << i << "-->"; for (auto &divi: divisor[i]){ cout << divi << ", "; } cout << "\n"; }} // Driver Codeint main(){ int n = 5; sieve(); // Function Call findNFactors(n);}
// Java implementation to find the// factors of first N natural// numbersimport java.util.*;class GFG{ static int MAX = (int) 1e5; // Initialize global divisor vector// array of sequence containerstatic Vector<Integer> []divisor = new Vector[MAX + 1]; // Calculate all// divisors of numberstatic void sieve(){ for (int i = 1; i <= MAX; ++i) { for (int j = i; j <= MAX; j += i) divisor[j].add(i); }} // Function to find the// factors of first n// natural numbersstatic void findNFactors(int n){ for(int i = 1; i <= n; i++) { System.out.print(i+ "-->"); for (int divi: divisor[i]) { System.out.print(divi+ ", "); } System.out.print("\n"); }} // Driver Codepublic static void main(String[] args){ int n = 5; for (int i = 0; i < divisor.length; i++) divisor[i] = new Vector<Integer>(); sieve(); // Function Call findNFactors(n);}} // This code is contributed by Princi Singh
# Python3 program to find the factors# of first N natural numbersMAX = 100001 # Initialize divisor list(array)# of sequence containerdivisor = [[] for x in range(MAX)] # Calculate all divisors of a numberdef sieve(): for i in range(1, MAX): for j in range(i, MAX, i): divisor[j].append(i) # Function to find the factors of# first n natural numbersdef findNFactors (n): for i in range(1, n + 1): print(i, " --> ", end = '') for divi in divisor[i]: print(divi, ", ", end = '') print() # Driver codeif __name__ == '__main__': n = 5 sieve() # Function call findNFactors(n) # This code is contributed by himanshu77
// C# implementation to find the// factors of first N natural// numbersusing System;using System.Collections.Generic; public class GFG{ static int MAX = (int) 1e5; // Initialize global divisor vector// array of sequence containerstatic List<int> []divisor = new List<int>[MAX + 1]; // Calculate all// divisors of numberstatic void sieve(){ for (int i = 1; i <= MAX; ++i) { for (int j = i; j <= MAX; j += i) divisor[j].Add(i); }} // Function to find the// factors of first n// natural numbersstatic void findNFactors(int n){ for(int i = 1; i <= n; i++) { Console.Write(i+ "-->"); foreach (int divi in divisor[i]) { Console.Write(divi+ ", "); } Console.Write("\n"); }} // Driver Codepublic static void Main(String[] args){ int n = 5; for (int i = 0; i < divisor.Length; i++) divisor[i] = new List<int>(); sieve(); // Function Call findNFactors(n);}} // This code is contributed by shikhasingrajput
<script> // Javascript implementation to find the// factors of first N natural// numbers var MAX = 100000; // Initialize global divisor vector// array of sequence containervar divisor = Array.from(Array(MAX+1),()=> Array(0)); // Calculate all// divisors of numberfunction sieve(){ for (var i = 1; i <= MAX; ++i) { for (var j = i; j <= MAX; j += i) divisor[j].push(i); }} // Function to find the// factors of first n// natural numbersfunction findNFactors(n){ for(var i = 1; i <= n; i++){ document.write( i + "-->"); for (var j =0; j< divisor[i].length;j++){ document.write( divisor[i][j] + ", "); } document.write( "<br>"); }} // Driver Codevar n = 5;sieve(); // Function CallfindNFactors(n); // This code is contributed by noob2000.</script>
1-->1,
2-->1, 2,
3-->1, 3,
4-->1, 2, 4,
5-->1, 5,
Rohit_ranjan
nidhi_biet
Code_Mech
himanshu77
princi singh
shikhasingrajput
GauravRajput1
subhammahato348
noob2000
factor
Natural Numbers
number-theory
sieve
Algorithms
Mathematical
number-theory
Mathematical
sieve
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
Quadratic Probing in Hashing
SCAN (Elevator) Disk Scheduling Algorithms
K means Clustering - Introduction
Difference between Informed and Uninformed Search in AI
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers | [
{
"code": null,
"e": 24666,
"s": 24638,
"text": "\n29 Apr, 2021"
},
{
"code": null,
"e": 24768,
"s": 24666,
"text": "Given an integer N, the task is to find all the divisors of numbers from 1 to N.Note: 1 ? N ? 100000 "
},
{
"code": null,
"e": 24778,
"s": 24768,
"text": "Examples:"
},
{
"code": null,
"e": 24814,
"s": 24778,
"text": "Input: N = 2 Output: 1 –>1 2 –>1, 2"
},
{
"code": null,
"e": 24880,
"s": 24814,
"text": "Input: N = 5 Output: 1 –>1 2 –>1, 2 3 –>1, 3 4 –>1, 2, 4 5 –>1, 5"
},
{
"code": null,
"e": 24896,
"s": 24880,
"text": "Naive Approach:"
},
{
"code": null,
"e": 24963,
"s": 24896,
"text": "Iterate over first N natural numbers using a loop variable (say i)"
},
{
"code": null,
"e": 25109,
"s": 24963,
"text": "Iterate over the natural numbers from 1 to i with a loop variable (say j) and check that i % j == 0. Then j is a divisor of the natural number i."
},
{
"code": null,
"e": 25160,
"s": 25109,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25164,
"s": 25160,
"text": "C++"
},
{
"code": null,
"e": 25169,
"s": 25164,
"text": "Java"
},
{
"code": null,
"e": 25177,
"s": 25169,
"text": "Python3"
},
{
"code": null,
"e": 25180,
"s": 25177,
"text": "C#"
},
{
"code": null,
"e": 25191,
"s": 25180,
"text": "Javascript"
},
{
"code": "// C++ implementation to find all// the divisors of the first N// natural numbers #include <bits/stdc++.h> using namespace std; // Function to find the divisors// of the first N natural numbersvoid factors(int n){ int i, j; cout << \"1 -->1\\n\"; // Loop to find the divisors for (i = 2; i <= n; i++) { cout << i << \" -->\"; for (j = 1; j <= i / 2; j++) { if (i % j == 0) cout << j << \", \"; } cout << i << \"\\n\"; }} // Driver Codeint main(){ int n = 5; factors(n);}",
"e": 25732,
"s": 25191,
"text": null
},
{
"code": "// Java implementation to find all// the divisors of the first N// natural numbersclass GFG{ // Function to find the divisors// of the first N natural numbersstatic void factors(int n){ int i, j; System.out.print(\"1 -->1\\n\"); // Loop to find the divisors for(i = 2; i <= n; i++) { System.out.print(i + \" -->\"); for(j = 1; j <= i / 2; j++) { if (i % j == 0) System.out.print(j + \", \"); } System.out.print(i + \"\\n\"); }} // Driver Codepublic static void main(String[] args){ int n = 5; factors(n);}} // This code is contributed by Rohit_ranjan",
"e": 26354,
"s": 25732,
"text": null
},
{
"code": "# Python3 implementation to find all# the divisors of the first N# natural numbers # Function to find the divisors# of the first N natural numbersdef factors(n): i = 0; j = 0; print(\"1 -->1\"); # Loop to find the divisors for i in range(2, n + 1): print(i, \"-->\", end = \"\"); for j in range(1, (i // 2) + 1): if (i % j == 0): print(j, \",\", end = \"\"); print(i, end = \"\\n\"); # Driver Coden = 5;factors(n); # This code is contributed by Code_Mech",
"e": 26874,
"s": 26354,
"text": null
},
{
"code": "// C# implementation to find all// the divisors of the first N// natural numbersusing System;class GFG{ // Function to find the divisors// of the first N natural numbersstatic void factors(int n){ int i, j; Console.Write(\"1 -->1\\n\"); // Loop to find the divisors for(i = 2; i <= n; i++) { Console.Write(i + \" -->\"); for(j = 1; j <= i / 2; j++) { if (i % j == 0) Console.Write(j + \", \"); } Console.Write(i + \"\\n\"); }} // Driver Codepublic static void Main(){ int n = 5; factors(n);}} // This code is contributed by Nidhi_biet",
"e": 27489,
"s": 26874,
"text": null
},
{
"code": "<script> // JavaScript implementation to find all// the divisors of the first N// natural numbers // Function to find the divisors// of the first N natural numbersfunction factors(n){ let i, j; document.write(\"1 -->1<br>\"); // Loop to find the divisors for (i = 2; i <= n; i++) { document.write(i + \" -->\"); for (j = 1; j <= parseInt(i / 2); j++) { if (i % j == 0) document.write(j + \", \"); } document.write(i + \"<br>\"); }} // Driver Codelet n = 5;factors(n); </script>",
"e": 28033,
"s": 27489,
"text": null
},
{
"code": null,
"e": 28083,
"s": 28033,
"text": "1 -->1\n2 -->1, 2\n3 -->1, 3\n4 -->1, 2, 4\n5 -->1, 5"
},
{
"code": null,
"e": 28106,
"s": 28083,
"text": "Time Complexity: O(N2)"
},
{
"code": null,
"e": 28123,
"s": 28106,
"text": "Better Approach:"
},
{
"code": null,
"e": 28187,
"s": 28123,
"text": "Iterate over the first N natural numbers using a loop variable."
},
{
"code": null,
"e": 28313,
"s": 28187,
"text": "For the number to find its divisors iterate from 2 to that number and check any one of them is a divisor of the given number."
},
{
"code": null,
"e": 28364,
"s": 28313,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28368,
"s": 28364,
"text": "C++"
},
{
"code": null,
"e": 28373,
"s": 28368,
"text": "Java"
},
{
"code": null,
"e": 28381,
"s": 28373,
"text": "Python3"
},
{
"code": null,
"e": 28384,
"s": 28381,
"text": "C#"
},
{
"code": null,
"e": 28395,
"s": 28384,
"text": "Javascript"
},
{
"code": "// C++ implementation to find all// the divisors of the first// N natural numbers #include <bits/stdc++.h> using namespace std; // Function to find the factors of// the numbers from 1 to Nvoid factors(int n){ int i, j; cout << \"1 -->1\\n\"; // Loop to find the factors // of the first N natural // numbers of the integer for (i = 2; i <= n; i++) { cout << i << \" -->\"; for (j = 1; j * j <= i; j++) { if (i % j == 0){ cout << j << \", \"; if (i / j != j) cout << i/j << \", \"; } } cout << \"\\n\"; }} // Driver Codeint main(){ int n = 5; factors(n);}",
"e": 29064,
"s": 28395,
"text": null
},
{
"code": "// Java implementation to find all// the divisors of the first// N natural numbersimport java.util.*;class GFG{ // Function to find the factors of// the numbers from 1 to Nstatic void factors(int n){ int i, j; System.out.print(\"1 -->1\\n\"); // Loop to find the factors // of the first N natural // numbers of the integer for (i = 2; i <= n; i++) { System.out.print(i + \" -->\"); for (j = 1; j * j <= i; j++) { if (i % j == 0) { System.out.print(j + \", \"); if (i / j != j) System.out.print(i / j + \", \"); } } System.out.print(\"\\n\"); }} // Driver Codepublic static void main(String args[]){ int n = 5; factors(n);}} // This code is contributed by Code_Mech",
"e": 29869,
"s": 29064,
"text": null
},
{
"code": "# Python3 implementation to find all# the divisors of the first# N natural numbers # Function to find the factors of# the numbers from 1 to Ndef factors(n): print(\"1 -->1\"); # Loop to find the factors # of the first N natural # numbers of the integer for i in range(2, n + 1): print(i, \" -->\", end = \"\"); for j in range(1, int(pow(i, 1))): if (i % j == 0): print(j, \", \", end = \"\"); if (i // j != j): print(i // j, \", \", end = \"\"); print(end = \"\\n\"); # Driver Codeif __name__ == '__main__': n = 5; factors(n); # This code is contributed by gauravrajput1",
"e": 30579,
"s": 29869,
"text": null
},
{
"code": "// C# implementation to find all// the divisors of the first// N natural numbersusing System;class GFG{ // Function to find the factors of// the numbers from 1 to Nstatic void factors(int n){ int i, j; Console.Write(\"1 -->1\\n\"); // Loop to find the factors // of the first N natural // numbers of the integer for (i = 2; i <= n; i++) { Console.Write(i + \" -->\"); for (j = 1; j * j <= i; j++) { if (i % j == 0) { Console.Write(j + \", \"); if (i / j != j) Console.Write(i / j + \", \"); } } Console.Write(\"\\n\"); }} // Driver Codepublic static void Main(){ int n = 5; factors(n);}} // This code is contributed by Code_Mech",
"e": 31348,
"s": 30579,
"text": null
},
{
"code": "<script> // Javascript implementation to find all// the divisors of the first// N natural numbers // Function to find the factors of// the numbers from 1 to Nfunction factors(n){ let i, j; document.write(\"1 -->1<br>\"); // Loop to find the factors // of the first N natural // numbers of the integer for(i = 2; i <= n; i++) { document.write(i + \" -->\"); for(j = 1; j * j <= i; j++) { if (i % j == 0) { document.write(j + \", \"); if (parseInt(i / j) != j) document.write(parseInt(i/j) + \", \"); } } document.write(\"<br>\"); }} // Driver Codelet n = 5;factors(n); // This code is contributed by subhammahato348 </script>",
"e": 32126,
"s": 31348,
"text": null
},
{
"code": null,
"e": 32184,
"s": 32126,
"text": "1 -->1\n2 -->1, 2, \n3 -->1, 3, \n4 -->1, 4, 2, \n5 -->1, 5, "
},
{
"code": null,
"e": 32217,
"s": 32186,
"text": "Time Complexity: O(N*sqrt(N)) "
},
{
"code": null,
"e": 32409,
"s": 32217,
"text": "Efficient Approach: The idea is to precompute the factors of the numbers with the help of the Sieve of Eratosthenes. Then finally iterate over the first N natural numbers to find the factors."
},
{
"code": null,
"e": 32460,
"s": 32409,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 32464,
"s": 32460,
"text": "C++"
},
{
"code": null,
"e": 32469,
"s": 32464,
"text": "Java"
},
{
"code": null,
"e": 32477,
"s": 32469,
"text": "Python3"
},
{
"code": null,
"e": 32480,
"s": 32477,
"text": "C#"
},
{
"code": null,
"e": 32491,
"s": 32480,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the// factors of first N natural// numbers #include <bits/stdc++.h> using namespace std; const int MAX = 1e5; // Initialize global divisor vector// array of sequence containervector<int> divisor[MAX + 1]; // Calculate all// divisors of numbervoid sieve(){ for (int i = 1; i <= MAX; ++i) { for (int j = i; j <= MAX; j += i) divisor[j].push_back(i); }} // Function to find the// factors of first n// natural numbersvoid findNFactors(int n){ for(int i = 1; i <= n; i++){ cout << i << \"-->\"; for (auto &divi: divisor[i]){ cout << divi << \", \"; } cout << \"\\n\"; }} // Driver Codeint main(){ int n = 5; sieve(); // Function Call findNFactors(n);}",
"e": 33249,
"s": 32491,
"text": null
},
{
"code": "// Java implementation to find the// factors of first N natural// numbersimport java.util.*;class GFG{ static int MAX = (int) 1e5; // Initialize global divisor vector// array of sequence containerstatic Vector<Integer> []divisor = new Vector[MAX + 1]; // Calculate all// divisors of numberstatic void sieve(){ for (int i = 1; i <= MAX; ++i) { for (int j = i; j <= MAX; j += i) divisor[j].add(i); }} // Function to find the// factors of first n// natural numbersstatic void findNFactors(int n){ for(int i = 1; i <= n; i++) { System.out.print(i+ \"-->\"); for (int divi: divisor[i]) { System.out.print(divi+ \", \"); } System.out.print(\"\\n\"); }} // Driver Codepublic static void main(String[] args){ int n = 5; for (int i = 0; i < divisor.length; i++) divisor[i] = new Vector<Integer>(); sieve(); // Function Call findNFactors(n);}} // This code is contributed by Princi Singh",
"e": 34231,
"s": 33249,
"text": null
},
{
"code": "# Python3 program to find the factors# of first N natural numbersMAX = 100001 # Initialize divisor list(array)# of sequence containerdivisor = [[] for x in range(MAX)] # Calculate all divisors of a numberdef sieve(): for i in range(1, MAX): for j in range(i, MAX, i): divisor[j].append(i) # Function to find the factors of# first n natural numbersdef findNFactors (n): for i in range(1, n + 1): print(i, \" --> \", end = '') for divi in divisor[i]: print(divi, \", \", end = '') print() # Driver codeif __name__ == '__main__': n = 5 sieve() # Function call findNFactors(n) # This code is contributed by himanshu77",
"e": 34922,
"s": 34231,
"text": null
},
{
"code": "// C# implementation to find the// factors of first N natural// numbersusing System;using System.Collections.Generic; public class GFG{ static int MAX = (int) 1e5; // Initialize global divisor vector// array of sequence containerstatic List<int> []divisor = new List<int>[MAX + 1]; // Calculate all// divisors of numberstatic void sieve(){ for (int i = 1; i <= MAX; ++i) { for (int j = i; j <= MAX; j += i) divisor[j].Add(i); }} // Function to find the// factors of first n// natural numbersstatic void findNFactors(int n){ for(int i = 1; i <= n; i++) { Console.Write(i+ \"-->\"); foreach (int divi in divisor[i]) { Console.Write(divi+ \", \"); } Console.Write(\"\\n\"); }} // Driver Codepublic static void Main(String[] args){ int n = 5; for (int i = 0; i < divisor.Length; i++) divisor[i] = new List<int>(); sieve(); // Function Call findNFactors(n);}} // This code is contributed by shikhasingrajput",
"e": 35937,
"s": 34922,
"text": null
},
{
"code": "<script> // Javascript implementation to find the// factors of first N natural// numbers var MAX = 100000; // Initialize global divisor vector// array of sequence containervar divisor = Array.from(Array(MAX+1),()=> Array(0)); // Calculate all// divisors of numberfunction sieve(){ for (var i = 1; i <= MAX; ++i) { for (var j = i; j <= MAX; j += i) divisor[j].push(i); }} // Function to find the// factors of first n// natural numbersfunction findNFactors(n){ for(var i = 1; i <= n; i++){ document.write( i + \"-->\"); for (var j =0; j< divisor[i].length;j++){ document.write( divisor[i][j] + \", \"); } document.write( \"<br>\"); }} // Driver Codevar n = 5;sieve(); // Function CallfindNFactors(n); // This code is contributed by noob2000.</script>",
"e": 36751,
"s": 35937,
"text": null
},
{
"code": null,
"e": 36805,
"s": 36751,
"text": "1-->1, \n2-->1, 2, \n3-->1, 3, \n4-->1, 2, 4, \n5-->1, 5,"
},
{
"code": null,
"e": 36822,
"s": 36809,
"text": "Rohit_ranjan"
},
{
"code": null,
"e": 36833,
"s": 36822,
"text": "nidhi_biet"
},
{
"code": null,
"e": 36843,
"s": 36833,
"text": "Code_Mech"
},
{
"code": null,
"e": 36854,
"s": 36843,
"text": "himanshu77"
},
{
"code": null,
"e": 36867,
"s": 36854,
"text": "princi singh"
},
{
"code": null,
"e": 36884,
"s": 36867,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 36898,
"s": 36884,
"text": "GauravRajput1"
},
{
"code": null,
"e": 36914,
"s": 36898,
"text": "subhammahato348"
},
{
"code": null,
"e": 36923,
"s": 36914,
"text": "noob2000"
},
{
"code": null,
"e": 36930,
"s": 36923,
"text": "factor"
},
{
"code": null,
"e": 36946,
"s": 36930,
"text": "Natural Numbers"
},
{
"code": null,
"e": 36960,
"s": 36946,
"text": "number-theory"
},
{
"code": null,
"e": 36966,
"s": 36960,
"text": "sieve"
},
{
"code": null,
"e": 36977,
"s": 36966,
"text": "Algorithms"
},
{
"code": null,
"e": 36990,
"s": 36977,
"text": "Mathematical"
},
{
"code": null,
"e": 37004,
"s": 36990,
"text": "number-theory"
},
{
"code": null,
"e": 37017,
"s": 37004,
"text": "Mathematical"
},
{
"code": null,
"e": 37023,
"s": 37017,
"text": "sieve"
},
{
"code": null,
"e": 37034,
"s": 37023,
"text": "Algorithms"
},
{
"code": null,
"e": 37132,
"s": 37034,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37141,
"s": 37132,
"text": "Comments"
},
{
"code": null,
"e": 37154,
"s": 37141,
"text": "Old Comments"
},
{
"code": null,
"e": 37179,
"s": 37154,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 37208,
"s": 37179,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 37251,
"s": 37208,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 37285,
"s": 37251,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 37341,
"s": 37285,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 37371,
"s": 37341,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 37431,
"s": 37371,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 37446,
"s": 37431,
"text": "C++ Data Types"
},
{
"code": null,
"e": 37489,
"s": 37446,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
Data Science Methodology 101. How can a Data Scientist organize his... | by Nunzio Logallo | Towards Data Science | Every Data Scientist needs a methodology to solve data science’s problems. For example, let’s suppose that you are a Data Scientist and your first job is to increase sales for a company, they want to know what product they should sell on what period. You will need the correct methodology to organize your work, analyze different types of data, and solve their problem. Your customer doesn’t care about how you do your job; they only care if you will manage to do it in time.
Methodology in Data Science is the best way to organize your work, doing it better, and without losing time. Data Science Methodology is composed of 10 parts:
In this article, there are five parts, each of which contains more steps:
From Problem to ApproachFrom Requirements to CollectionFrom Understanding to PreparationFrom Modeling to EvaluationFrom Deployment to Feedback
From Problem to Approach
From Requirements to Collection
From Understanding to Preparation
From Modeling to Evaluation
From Deployment to Feedback
If we look at the chart in the last image, we see that it is highly iterative and never ends; that’s because in a real case study, we have to repeat some steps to improve the model.
Every customer’s request starts with a problem, and Data Scientists’ job is first to understand it and approach this problem with statistical and machine learning techniques.
The Business Understanding stage is crucial because it helps to clarify the goal of the customer. In this stage, we have to ask a lot of questions to the customer about every single aspect of the problem; in this manner, we are sure that we will study data related, and at the end of this stage, we will have a list of business requirements.
The next step is the Analytic Approach, where, once the business problem has been clearly stated, the data scientist can define the analytic approach to solve the problem. This step entails expressing the problem in the context of statistical and machine-learning techniques, and it is essential because it helps identify what type of patterns will be needed to address the question most effectively. If the issue is to determine the probabilities of something, then a predictive model might be used; if the question is to show relationships, a descriptive approach may be required, and if our problem requires counts, then statistical analysis is the best way to solve it. For each type of approach, we can use different algorithms.
Once we have found a way to solve our problem, we will need to discover the correct data for our model.
Data Requirements is the stage where we identify the necessary data content, formats, and sources for initial data collection, and we use this data inside the algorithm of the approach we chose.
In the Data Collection Stage, data scientists identify the available data resources relevant to the problem domain. To retrieve data, we can do web scraping on a related website, or we can use repository with premade datasets ready to use. Usually, premade datasets are CSV files or Excel; anyway, if we want to collect data from any website or repository, we should use Pandas, a useful tool to download, convert, and modify datasets. Here is an example of the data collection stage with pandas.
import pandas as pd # download library to read data into dataframepd.set_option('display.max_column', None)dataframe = pd.read_csv("csv_file_url")print("Data read into dataframe!")dataframe.head() # show the first few rowsdataframe.shape # get the dimensions of the dataframe
Now that the data collection stage is complete, data scientists use descriptive statistics and visualization techniques to understand data better. Data scientists, explore the dataset to understand its content, determine if additional data is necessary to fill any gaps but also to verify the quality of the data.
In the Data Understanding stage, data scientists try to understand more about the data collected before. We have to check the type of each data and to learn more about the attributes and their names.
# get all columns from a dataframe and put them into a listattributes = list(dataframe.columns.values)# then we check if a column exist and what is its name.print([match.group(0) for attributes in attributes for match in [(re.compile(".*(column_name_keyword).*")).search(attributes)] if match])
In the Data Preparation stage, data scientists prepare data for modeling, which is one of the most crucial steps because the model has to be clean and without errors. In this stage, we have to be sure that the data are in the correct format for the machine learning algorithm we chose in the analytic approach stage. The dataframe has to have appropriate columns name, unified boolean value (yes, no or 1, 0). We have to pay attention to the name of each data because sometimes they might be written in different characters, but they are the same thing; for example (WaTeR, water), we can fix this making all the value of a column lowercase. Another improvement can be made by deleting data exceptions from the dataframe because of their irrelevance.
# replacing all 'yes' values with '1' and 'no' with '0'dataframe = dataframe.replace(to_replace="Yes", value=1)dataframe = dataframe.replace(to_replace="No", value=0)# making all the value of a column lowercasedataframe["column"] = dataframe["column"].str.lower()
Once data are prepared for the chosen machine learning algorithm, we are ready for modeling.
In the Modeling stage, the data scientist has the chance to understand if his work is ready to go or if it needs review. Modeling focuses on developing models that are either descriptive or predictive, and these models are based on the analytic approach that was taken statistically or through machine learning. Descriptive modeling is a mathematical process that describes real-world events and the relationships between factors responsible for them, for example, a descriptive model might examine things like: if a person did this, then they’re likely to prefer that. Predictive modeling is a process that uses data mining and probability to forecast outcomes; for example, a predictive model might be used to determine whether an email is a spam or not. For predictive modeling, data scientists use a training set that is a set of historical data in which the outcomes are already known. This step can be repeated more times until the model understands the question and answer to it.
In the Model Evaluation stage, data scientists can evaluate the model in two ways: Hold-Out and Cross-Validation. In the Hold-Out method, the dataset is divided into three subsets: a training set as we said in the modeling stage; a validation set that is a subset used to assess the performance of the model built in the training phase; a test set is a subset to evaluate the likely future performance of a model.
Here is an example of modeling and evaluation:
# select dataset and training fielddata = pd.read_csv("student-mat.csv", sep=";")data = data[["G1", "G2", "G3", "studytime", "failures", "absences"]]predict = "G3" # select field to predictx = np.array(data.drop([predict], 1))y = np.array(data[predict])# split the dataset into training and test subsetsx_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size = 0.1)linear = linear_model.LinearRegression() # create linear regression modellinear.fit(x_train, y_train) # perform the training of the modelacc = linear.score(x_test, y_test) # calculate the accuracyprint("Accuracy: ", acc) # print the accuracy of the model
Data scientists have to make the stakeholders familiar with the tool produced in different scenarios, so once the model is evaluated and the data scientist is confident it will work, it is deployed and put to the ultimate test.
The Deployment stage depends on the purpose of the model, and it may be rolled out to a limited group of users or in a test environment. A real case study example can be for a model destined for the healthcare system; the model can be deployed for some patients with low-risk and after for high-risk patients too.
The Feedback stage is usually made the most from the customer. Customers after the deployment stage can say if the model works for their purposes or not. Data scientists take this feedback and decide if they should improve the model; that’s because the process from modeling to feedback is highly iterative.
When the model meets all the requirements of the customer, our data science project is complete.
To learn more, you can visit my GitHub repository where you can find a real use case example and more.
Source: IBM Data Science Methodology from CourseraBook source: A Model to Forecast Future Paradigms: Volume 1 | [
{
"code": null,
"e": 648,
"s": 172,
"text": "Every Data Scientist needs a methodology to solve data science’s problems. For example, let’s suppose that you are a Data Scientist and your first job is to increase sales for a company, they want to know what product they should sell on what period. You will need the correct methodology to organize your work, analyze different types of data, and solve their problem. Your customer doesn’t care about how you do your job; they only care if you will manage to do it in time."
},
{
"code": null,
"e": 807,
"s": 648,
"text": "Methodology in Data Science is the best way to organize your work, doing it better, and without losing time. Data Science Methodology is composed of 10 parts:"
},
{
"code": null,
"e": 881,
"s": 807,
"text": "In this article, there are five parts, each of which contains more steps:"
},
{
"code": null,
"e": 1024,
"s": 881,
"text": "From Problem to ApproachFrom Requirements to CollectionFrom Understanding to PreparationFrom Modeling to EvaluationFrom Deployment to Feedback"
},
{
"code": null,
"e": 1049,
"s": 1024,
"text": "From Problem to Approach"
},
{
"code": null,
"e": 1081,
"s": 1049,
"text": "From Requirements to Collection"
},
{
"code": null,
"e": 1115,
"s": 1081,
"text": "From Understanding to Preparation"
},
{
"code": null,
"e": 1143,
"s": 1115,
"text": "From Modeling to Evaluation"
},
{
"code": null,
"e": 1171,
"s": 1143,
"text": "From Deployment to Feedback"
},
{
"code": null,
"e": 1353,
"s": 1171,
"text": "If we look at the chart in the last image, we see that it is highly iterative and never ends; that’s because in a real case study, we have to repeat some steps to improve the model."
},
{
"code": null,
"e": 1528,
"s": 1353,
"text": "Every customer’s request starts with a problem, and Data Scientists’ job is first to understand it and approach this problem with statistical and machine learning techniques."
},
{
"code": null,
"e": 1870,
"s": 1528,
"text": "The Business Understanding stage is crucial because it helps to clarify the goal of the customer. In this stage, we have to ask a lot of questions to the customer about every single aspect of the problem; in this manner, we are sure that we will study data related, and at the end of this stage, we will have a list of business requirements."
},
{
"code": null,
"e": 2604,
"s": 1870,
"text": "The next step is the Analytic Approach, where, once the business problem has been clearly stated, the data scientist can define the analytic approach to solve the problem. This step entails expressing the problem in the context of statistical and machine-learning techniques, and it is essential because it helps identify what type of patterns will be needed to address the question most effectively. If the issue is to determine the probabilities of something, then a predictive model might be used; if the question is to show relationships, a descriptive approach may be required, and if our problem requires counts, then statistical analysis is the best way to solve it. For each type of approach, we can use different algorithms."
},
{
"code": null,
"e": 2708,
"s": 2604,
"text": "Once we have found a way to solve our problem, we will need to discover the correct data for our model."
},
{
"code": null,
"e": 2903,
"s": 2708,
"text": "Data Requirements is the stage where we identify the necessary data content, formats, and sources for initial data collection, and we use this data inside the algorithm of the approach we chose."
},
{
"code": null,
"e": 3400,
"s": 2903,
"text": "In the Data Collection Stage, data scientists identify the available data resources relevant to the problem domain. To retrieve data, we can do web scraping on a related website, or we can use repository with premade datasets ready to use. Usually, premade datasets are CSV files or Excel; anyway, if we want to collect data from any website or repository, we should use Pandas, a useful tool to download, convert, and modify datasets. Here is an example of the data collection stage with pandas."
},
{
"code": null,
"e": 3676,
"s": 3400,
"text": "import pandas as pd # download library to read data into dataframepd.set_option('display.max_column', None)dataframe = pd.read_csv(\"csv_file_url\")print(\"Data read into dataframe!\")dataframe.head() # show the first few rowsdataframe.shape # get the dimensions of the dataframe"
},
{
"code": null,
"e": 3990,
"s": 3676,
"text": "Now that the data collection stage is complete, data scientists use descriptive statistics and visualization techniques to understand data better. Data scientists, explore the dataset to understand its content, determine if additional data is necessary to fill any gaps but also to verify the quality of the data."
},
{
"code": null,
"e": 4190,
"s": 3990,
"text": "In the Data Understanding stage, data scientists try to understand more about the data collected before. We have to check the type of each data and to learn more about the attributes and their names."
},
{
"code": null,
"e": 4485,
"s": 4190,
"text": "# get all columns from a dataframe and put them into a listattributes = list(dataframe.columns.values)# then we check if a column exist and what is its name.print([match.group(0) for attributes in attributes for match in [(re.compile(\".*(column_name_keyword).*\")).search(attributes)] if match])"
},
{
"code": null,
"e": 5236,
"s": 4485,
"text": "In the Data Preparation stage, data scientists prepare data for modeling, which is one of the most crucial steps because the model has to be clean and without errors. In this stage, we have to be sure that the data are in the correct format for the machine learning algorithm we chose in the analytic approach stage. The dataframe has to have appropriate columns name, unified boolean value (yes, no or 1, 0). We have to pay attention to the name of each data because sometimes they might be written in different characters, but they are the same thing; for example (WaTeR, water), we can fix this making all the value of a column lowercase. Another improvement can be made by deleting data exceptions from the dataframe because of their irrelevance."
},
{
"code": null,
"e": 5500,
"s": 5236,
"text": "# replacing all 'yes' values with '1' and 'no' with '0'dataframe = dataframe.replace(to_replace=\"Yes\", value=1)dataframe = dataframe.replace(to_replace=\"No\", value=0)# making all the value of a column lowercasedataframe[\"column\"] = dataframe[\"column\"].str.lower()"
},
{
"code": null,
"e": 5593,
"s": 5500,
"text": "Once data are prepared for the chosen machine learning algorithm, we are ready for modeling."
},
{
"code": null,
"e": 6580,
"s": 5593,
"text": "In the Modeling stage, the data scientist has the chance to understand if his work is ready to go or if it needs review. Modeling focuses on developing models that are either descriptive or predictive, and these models are based on the analytic approach that was taken statistically or through machine learning. Descriptive modeling is a mathematical process that describes real-world events and the relationships between factors responsible for them, for example, a descriptive model might examine things like: if a person did this, then they’re likely to prefer that. Predictive modeling is a process that uses data mining and probability to forecast outcomes; for example, a predictive model might be used to determine whether an email is a spam or not. For predictive modeling, data scientists use a training set that is a set of historical data in which the outcomes are already known. This step can be repeated more times until the model understands the question and answer to it."
},
{
"code": null,
"e": 6994,
"s": 6580,
"text": "In the Model Evaluation stage, data scientists can evaluate the model in two ways: Hold-Out and Cross-Validation. In the Hold-Out method, the dataset is divided into three subsets: a training set as we said in the modeling stage; a validation set that is a subset used to assess the performance of the model built in the training phase; a test set is a subset to evaluate the likely future performance of a model."
},
{
"code": null,
"e": 7041,
"s": 6994,
"text": "Here is an example of modeling and evaluation:"
},
{
"code": null,
"e": 7697,
"s": 7041,
"text": "# select dataset and training fielddata = pd.read_csv(\"student-mat.csv\", sep=\";\")data = data[[\"G1\", \"G2\", \"G3\", \"studytime\", \"failures\", \"absences\"]]predict = \"G3\" # select field to predictx = np.array(data.drop([predict], 1))y = np.array(data[predict])# split the dataset into training and test subsetsx_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size = 0.1)linear = linear_model.LinearRegression() # create linear regression modellinear.fit(x_train, y_train) # perform the training of the modelacc = linear.score(x_test, y_test) # calculate the accuracyprint(\"Accuracy: \", acc) # print the accuracy of the model"
},
{
"code": null,
"e": 7925,
"s": 7697,
"text": "Data scientists have to make the stakeholders familiar with the tool produced in different scenarios, so once the model is evaluated and the data scientist is confident it will work, it is deployed and put to the ultimate test."
},
{
"code": null,
"e": 8239,
"s": 7925,
"text": "The Deployment stage depends on the purpose of the model, and it may be rolled out to a limited group of users or in a test environment. A real case study example can be for a model destined for the healthcare system; the model can be deployed for some patients with low-risk and after for high-risk patients too."
},
{
"code": null,
"e": 8547,
"s": 8239,
"text": "The Feedback stage is usually made the most from the customer. Customers after the deployment stage can say if the model works for their purposes or not. Data scientists take this feedback and decide if they should improve the model; that’s because the process from modeling to feedback is highly iterative."
},
{
"code": null,
"e": 8644,
"s": 8547,
"text": "When the model meets all the requirements of the customer, our data science project is complete."
},
{
"code": null,
"e": 8747,
"s": 8644,
"text": "To learn more, you can visit my GitHub repository where you can find a real use case example and more."
}
]
|
How to Successfully Install Anaconda on a Mac (and Actually Get it to Work) | by Anne Bonner | Towards Data Science | You know you need it.
As you’re getting started in data science, machine learning, or artificial intelligence, you’re quickly going to realize that you need to be able to use Anaconda. You might want to use Jupyter Notebooks, Spyder, or another awesome program, but one way or another, you’re going to need this thing to work.
While setting up a computer recently, I remembered how hard it was to get Anaconda to work the first time. The installation itself was no problem! The official guide is clear and comprehensive when it comes to the installation itself. You work through it, follow a few simple steps, and you’re good to go!
At the end, it tells you to verify that your installation was successful by typing a command like “conda list” and you’re done!
Nope.
“Conda” didn’t work the first time I installed it. There’s no handy link sitting there that will tell you what to do. You verify it and then you’re done.
You’re on your own.
There’s nothing more frustrating than not even being able to open the program that you need.
It’s not an easy thing to get started in machine learning and artificial intelligence, and being unable to get the necessary tools correctly installed is just crippling. As you start to understand more of the language and commands that you need to make things work, you’ll find that there are plenty of simple answers out there. But none of them make any sense when it’s all new! Just Googling your questions can be challenging.
I had actually done this to myself.
I work on a MacOS (Mojave, if you’re interested). After spending some time working in the terminal, I had turned it into something that was fast, efficient, and also very nice to look at. You can see everything that I did to make my terminal awesome here, but essentially, it’s running
iTerm2
Homebrew
Zsh
Oh My Zsh
a few Oh My Zsh plugins
Z
Syntax Highlighting
towardsdatascience.com
Little did I know that this would make my Anaconda installation a tiny bit more difficult. One single line of code more difficult, as it turns out, but a million times more challenging for a newbie.
This is the step-by-step installation process with a simple one-line fix that will allow you to “conda” anything you want. Even if you’re using the lovely and amazing Zsh.
So here’s the thing: the installation was successful, but there was a tiny problem between Zsh and the way my terminal wanted to talk to Anaconda. This can happen for any number of reasons, but Zsh was the culprit here.
It was incredibly easy to fix! But because I had no idea what I was doing, it took forever to figure out.
No one else should have to go through that.
The official installation guide is here if you feel like checking it out.
The first time I decided to download Anaconda, I went through the normal graphical Mac installation. It worked fine as an application, but it just wouldn’t work with my terminal.
Unwilling to give up, I uninstalled Anaconda and then tried the command-line installation. That one is great because you can decide during installation that you want your terminal to communicate with Anaconda. You’ll get a prompt during installation that asks, “Do you wish the installer to initialize Anaconda3 by running conda init?”
I’d recommend giving that one a big yes.
Of course, it still didn’t work. It probably would, though, if you didn’t have a tricked out terminal! If you aren’t using Zsh and Oh My Zsh, you might be set.
So how do you get this to work the way it’s supposed to if you’ve made changes to your terminal?
It’s simple!
These are the simple steps for a successful Anaconda installation, even in the face of the dreaded “conda command not found” error message.
You can go here to download Anaconda. Then scroll down a little to the part that says “Anaconda 2019.03 for macOS Installer.”
You’ll need to know which version of Python you have, so go to your terminal and type
python
You have a couple of choices for your download. You can choose the graphical installer, which means that you’ll install Anaconda the same exact way that you’d install any other program. Or you can choose the command line installer, which means that you’ll go to your terminal and type out (or copy and paste) the commands.
We’re going to do the command line installer, so click that link under your version of Python and your download should start.
After your download is complete, head on over to your terminal.
If you have Python 3.7, you’ll run
bash ~/Downloads/Anaconda3-2019.03-MacOSX-x86_64.sh
For Python 2.7, run
bash ~/Downloads/Anaconda2-2019.03-MacOSX-x86_64.sh
Keep in mind that if you didn’t download Anaconda to your downloads folder, you’ll need to change that path.
Review the license agreement and accept it by hitting “Enter” about a million times until you get to the end. At the end, type “yes” if you want to agree.
(It will prompt you. It will prompt you repeatedly if you miss it.)
If you’re happy with the location it suggests, hit “Enter.” You can change locations or cancel the installation by entering CTRL-C. Pay attention to this location! It will come in handy if you get the error message.
Now hold still. Be patient. This can take a few minutes and you won’t know if anything is happening at first. You could go and grab a beverage if you want, but be quick because the installer will ask, “Do you wish the installer to initialize Anaconda3 by running conda init?” and you almost certainly want to be there to type “yes” when you’re asked.
“Thank you for installing Anaconda!”
When your installation is complete, close your terminal window and open a new one for the changes to take effect. Want to see if it worked? In your terminal, type a command like
conda list
and see what happens. If it works, you’ll see something like this
This is a very useful command if you want to know which packages and versions you have installed in your environment!
If that worked, congratulations!!! You are now ready to start using Anaconda, Jupyter Notebooks, Spyder, and all of the other good stuff. Time to celebrate!
On the other hand, you might be seeing this:
The solution to this problem is actually very simple.
(I know I already said that, but the Anaconda team reached out and let me know that not refreshing your terminal is the most common reason that people have problems at this point.)
You’ll need to know where your Anaconda binary directory is and what your username is. If you were paying attention during your installation, you already have this information! You want the location that you specified during installation.
If not, there’s a very, very good chance that if you simply followed the installation instructions, your directory is /Users/ if you’re on a macOS. (Or /home/ on Linux or \Users\ on Windows10.)
If you don’t know your username, run
echo $USER
I recommended modifying PATH to fix the problem (you can see the original fix below), but the Anaconda team reached out with some incredibly helpful information!
They don’t recommend modifying PATH!
You can read the full comment below, but here is a condensed version of the information that you can find in the comments section from the amazing Michael Sarahan:
“Modifying PATH can cause problems if there are any other programs on your system that have the same names, that Anaconda then hides (shadows) by being found first. What “conda init” does is to set up a conda “shell function” and keep the other stuff off PATH. Nothing but conda is on PATH. It then defaults to activating your base environment at startup. The net effect is very much like your PATH addition, but has some subtle, but critically important differences:
activation ensures that anaconda’s PATH stuff is right up front. Putting anaconda at the front of PATH permanently is good in that it prevents confusion, but bad in that it shadows other stuff and can break things. Activation is a less permanent way to do this. You can turn off the automatic activation of the base environment using the “auto_activate_base” condarc setting.
activation does a bit more than just modifying PATH. It also sources any activate.d scripts, which may set additional environment variables. Some things, such as GDAL, require these. These packages will not work without activation.
So, rather than your tip on modifying PATH, what we recommend is following the directions at the end of the installer, should you choose not to run conda init:
...
that will look like 2 commands:
1. eval “$(/home/msarahan/mc3_dummy/bin/conda shell.bash hook)”
2. conda init
Note that in step 1, I changed the shell name from YOUR_SHELL_NAME to bash. You may need to adjust that yourself to your shell.”
Long story short, it’s entirely possible that modifying PATH might cause you some problems down the road. It’s smarter to go with activation because it isn’t permanent and will allow some packages to run that might not otherwise.
So, at the end of the installer, instead of running the original solution:
export PATH="/Users/myname/anaconda2/bin:$PATH"
You want to run
eval "$(/home/msarahan/mc3_dummy/bin/conda shell.bash hook)”conda init
(But make sure you change the directory location and shell to your own!)
***End of update***
All you need to do to make things work is run
export PATH="/Users/myname/anaconda3/bin:$PATH"
and you’re good to go!!!
(Definitely make sure you replace “myname” with your username and change the path to the directory if you need to. If you look at the line above, /Users/myname/anaconda3 would be replaced by /Users/anneb/anaconda3 from the installation location earlier. Keep everything else the same.)
If you didn’t install Anaconda3, you would need to run
export PATH="/Users/myname/anaconda2/bin:$PATH"
for Anaconda2 or
export PATH="/Users/myname/anaconda/bin:$PATH"
making sure to change “myname” and the directory location if necessary.
Now try conda list!
You did it!!!
You successfully installed Anaconda and are now able to run it from your command line!
Try typing
jupyter notebook
and see what happens!
Thanks for reading! If you want to reach out or find more cool articles, please come and join me at Content Simplicity!
Want to learn about the easiest way to create, run, publish, and even share Jupyter Notebooks?
towardsdatascience.com
Thanks for reading! | [
{
"code": null,
"e": 194,
"s": 172,
"text": "You know you need it."
},
{
"code": null,
"e": 499,
"s": 194,
"text": "As you’re getting started in data science, machine learning, or artificial intelligence, you’re quickly going to realize that you need to be able to use Anaconda. You might want to use Jupyter Notebooks, Spyder, or another awesome program, but one way or another, you’re going to need this thing to work."
},
{
"code": null,
"e": 805,
"s": 499,
"text": "While setting up a computer recently, I remembered how hard it was to get Anaconda to work the first time. The installation itself was no problem! The official guide is clear and comprehensive when it comes to the installation itself. You work through it, follow a few simple steps, and you’re good to go!"
},
{
"code": null,
"e": 933,
"s": 805,
"text": "At the end, it tells you to verify that your installation was successful by typing a command like “conda list” and you’re done!"
},
{
"code": null,
"e": 939,
"s": 933,
"text": "Nope."
},
{
"code": null,
"e": 1093,
"s": 939,
"text": "“Conda” didn’t work the first time I installed it. There’s no handy link sitting there that will tell you what to do. You verify it and then you’re done."
},
{
"code": null,
"e": 1113,
"s": 1093,
"text": "You’re on your own."
},
{
"code": null,
"e": 1206,
"s": 1113,
"text": "There’s nothing more frustrating than not even being able to open the program that you need."
},
{
"code": null,
"e": 1635,
"s": 1206,
"text": "It’s not an easy thing to get started in machine learning and artificial intelligence, and being unable to get the necessary tools correctly installed is just crippling. As you start to understand more of the language and commands that you need to make things work, you’ll find that there are plenty of simple answers out there. But none of them make any sense when it’s all new! Just Googling your questions can be challenging."
},
{
"code": null,
"e": 1671,
"s": 1635,
"text": "I had actually done this to myself."
},
{
"code": null,
"e": 1957,
"s": 1671,
"text": "I work on a MacOS (Mojave, if you’re interested). After spending some time working in the terminal, I had turned it into something that was fast, efficient, and also very nice to look at. You can see everything that I did to make my terminal awesome here, but essentially, it’s running"
},
{
"code": null,
"e": 1964,
"s": 1957,
"text": "iTerm2"
},
{
"code": null,
"e": 1973,
"s": 1964,
"text": "Homebrew"
},
{
"code": null,
"e": 1977,
"s": 1973,
"text": "Zsh"
},
{
"code": null,
"e": 1987,
"s": 1977,
"text": "Oh My Zsh"
},
{
"code": null,
"e": 2011,
"s": 1987,
"text": "a few Oh My Zsh plugins"
},
{
"code": null,
"e": 2013,
"s": 2011,
"text": "Z"
},
{
"code": null,
"e": 2033,
"s": 2013,
"text": "Syntax Highlighting"
},
{
"code": null,
"e": 2056,
"s": 2033,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2255,
"s": 2056,
"text": "Little did I know that this would make my Anaconda installation a tiny bit more difficult. One single line of code more difficult, as it turns out, but a million times more challenging for a newbie."
},
{
"code": null,
"e": 2427,
"s": 2255,
"text": "This is the step-by-step installation process with a simple one-line fix that will allow you to “conda” anything you want. Even if you’re using the lovely and amazing Zsh."
},
{
"code": null,
"e": 2647,
"s": 2427,
"text": "So here’s the thing: the installation was successful, but there was a tiny problem between Zsh and the way my terminal wanted to talk to Anaconda. This can happen for any number of reasons, but Zsh was the culprit here."
},
{
"code": null,
"e": 2753,
"s": 2647,
"text": "It was incredibly easy to fix! But because I had no idea what I was doing, it took forever to figure out."
},
{
"code": null,
"e": 2797,
"s": 2753,
"text": "No one else should have to go through that."
},
{
"code": null,
"e": 2871,
"s": 2797,
"text": "The official installation guide is here if you feel like checking it out."
},
{
"code": null,
"e": 3050,
"s": 2871,
"text": "The first time I decided to download Anaconda, I went through the normal graphical Mac installation. It worked fine as an application, but it just wouldn’t work with my terminal."
},
{
"code": null,
"e": 3386,
"s": 3050,
"text": "Unwilling to give up, I uninstalled Anaconda and then tried the command-line installation. That one is great because you can decide during installation that you want your terminal to communicate with Anaconda. You’ll get a prompt during installation that asks, “Do you wish the installer to initialize Anaconda3 by running conda init?”"
},
{
"code": null,
"e": 3427,
"s": 3386,
"text": "I’d recommend giving that one a big yes."
},
{
"code": null,
"e": 3587,
"s": 3427,
"text": "Of course, it still didn’t work. It probably would, though, if you didn’t have a tricked out terminal! If you aren’t using Zsh and Oh My Zsh, you might be set."
},
{
"code": null,
"e": 3684,
"s": 3587,
"text": "So how do you get this to work the way it’s supposed to if you’ve made changes to your terminal?"
},
{
"code": null,
"e": 3697,
"s": 3684,
"text": "It’s simple!"
},
{
"code": null,
"e": 3837,
"s": 3697,
"text": "These are the simple steps for a successful Anaconda installation, even in the face of the dreaded “conda command not found” error message."
},
{
"code": null,
"e": 3963,
"s": 3837,
"text": "You can go here to download Anaconda. Then scroll down a little to the part that says “Anaconda 2019.03 for macOS Installer.”"
},
{
"code": null,
"e": 4049,
"s": 3963,
"text": "You’ll need to know which version of Python you have, so go to your terminal and type"
},
{
"code": null,
"e": 4056,
"s": 4049,
"text": "python"
},
{
"code": null,
"e": 4379,
"s": 4056,
"text": "You have a couple of choices for your download. You can choose the graphical installer, which means that you’ll install Anaconda the same exact way that you’d install any other program. Or you can choose the command line installer, which means that you’ll go to your terminal and type out (or copy and paste) the commands."
},
{
"code": null,
"e": 4505,
"s": 4379,
"text": "We’re going to do the command line installer, so click that link under your version of Python and your download should start."
},
{
"code": null,
"e": 4569,
"s": 4505,
"text": "After your download is complete, head on over to your terminal."
},
{
"code": null,
"e": 4604,
"s": 4569,
"text": "If you have Python 3.7, you’ll run"
},
{
"code": null,
"e": 4656,
"s": 4604,
"text": "bash ~/Downloads/Anaconda3-2019.03-MacOSX-x86_64.sh"
},
{
"code": null,
"e": 4676,
"s": 4656,
"text": "For Python 2.7, run"
},
{
"code": null,
"e": 4728,
"s": 4676,
"text": "bash ~/Downloads/Anaconda2-2019.03-MacOSX-x86_64.sh"
},
{
"code": null,
"e": 4837,
"s": 4728,
"text": "Keep in mind that if you didn’t download Anaconda to your downloads folder, you’ll need to change that path."
},
{
"code": null,
"e": 4992,
"s": 4837,
"text": "Review the license agreement and accept it by hitting “Enter” about a million times until you get to the end. At the end, type “yes” if you want to agree."
},
{
"code": null,
"e": 5060,
"s": 4992,
"text": "(It will prompt you. It will prompt you repeatedly if you miss it.)"
},
{
"code": null,
"e": 5276,
"s": 5060,
"text": "If you’re happy with the location it suggests, hit “Enter.” You can change locations or cancel the installation by entering CTRL-C. Pay attention to this location! It will come in handy if you get the error message."
},
{
"code": null,
"e": 5627,
"s": 5276,
"text": "Now hold still. Be patient. This can take a few minutes and you won’t know if anything is happening at first. You could go and grab a beverage if you want, but be quick because the installer will ask, “Do you wish the installer to initialize Anaconda3 by running conda init?” and you almost certainly want to be there to type “yes” when you’re asked."
},
{
"code": null,
"e": 5664,
"s": 5627,
"text": "“Thank you for installing Anaconda!”"
},
{
"code": null,
"e": 5842,
"s": 5664,
"text": "When your installation is complete, close your terminal window and open a new one for the changes to take effect. Want to see if it worked? In your terminal, type a command like"
},
{
"code": null,
"e": 5853,
"s": 5842,
"text": "conda list"
},
{
"code": null,
"e": 5919,
"s": 5853,
"text": "and see what happens. If it works, you’ll see something like this"
},
{
"code": null,
"e": 6037,
"s": 5919,
"text": "This is a very useful command if you want to know which packages and versions you have installed in your environment!"
},
{
"code": null,
"e": 6194,
"s": 6037,
"text": "If that worked, congratulations!!! You are now ready to start using Anaconda, Jupyter Notebooks, Spyder, and all of the other good stuff. Time to celebrate!"
},
{
"code": null,
"e": 6239,
"s": 6194,
"text": "On the other hand, you might be seeing this:"
},
{
"code": null,
"e": 6293,
"s": 6239,
"text": "The solution to this problem is actually very simple."
},
{
"code": null,
"e": 6474,
"s": 6293,
"text": "(I know I already said that, but the Anaconda team reached out and let me know that not refreshing your terminal is the most common reason that people have problems at this point.)"
},
{
"code": null,
"e": 6713,
"s": 6474,
"text": "You’ll need to know where your Anaconda binary directory is and what your username is. If you were paying attention during your installation, you already have this information! You want the location that you specified during installation."
},
{
"code": null,
"e": 6907,
"s": 6713,
"text": "If not, there’s a very, very good chance that if you simply followed the installation instructions, your directory is /Users/ if you’re on a macOS. (Or /home/ on Linux or \\Users\\ on Windows10.)"
},
{
"code": null,
"e": 6944,
"s": 6907,
"text": "If you don’t know your username, run"
},
{
"code": null,
"e": 6955,
"s": 6944,
"text": "echo $USER"
},
{
"code": null,
"e": 7117,
"s": 6955,
"text": "I recommended modifying PATH to fix the problem (you can see the original fix below), but the Anaconda team reached out with some incredibly helpful information!"
},
{
"code": null,
"e": 7154,
"s": 7117,
"text": "They don’t recommend modifying PATH!"
},
{
"code": null,
"e": 7318,
"s": 7154,
"text": "You can read the full comment below, but here is a condensed version of the information that you can find in the comments section from the amazing Michael Sarahan:"
},
{
"code": null,
"e": 7786,
"s": 7318,
"text": "“Modifying PATH can cause problems if there are any other programs on your system that have the same names, that Anaconda then hides (shadows) by being found first. What “conda init” does is to set up a conda “shell function” and keep the other stuff off PATH. Nothing but conda is on PATH. It then defaults to activating your base environment at startup. The net effect is very much like your PATH addition, but has some subtle, but critically important differences:"
},
{
"code": null,
"e": 8162,
"s": 7786,
"text": "activation ensures that anaconda’s PATH stuff is right up front. Putting anaconda at the front of PATH permanently is good in that it prevents confusion, but bad in that it shadows other stuff and can break things. Activation is a less permanent way to do this. You can turn off the automatic activation of the base environment using the “auto_activate_base” condarc setting."
},
{
"code": null,
"e": 8394,
"s": 8162,
"text": "activation does a bit more than just modifying PATH. It also sources any activate.d scripts, which may set additional environment variables. Some things, such as GDAL, require these. These packages will not work without activation."
},
{
"code": null,
"e": 8554,
"s": 8394,
"text": "So, rather than your tip on modifying PATH, what we recommend is following the directions at the end of the installer, should you choose not to run conda init:"
},
{
"code": null,
"e": 8558,
"s": 8554,
"text": "..."
},
{
"code": null,
"e": 8590,
"s": 8558,
"text": "that will look like 2 commands:"
},
{
"code": null,
"e": 8654,
"s": 8590,
"text": "1. eval “$(/home/msarahan/mc3_dummy/bin/conda shell.bash hook)”"
},
{
"code": null,
"e": 8668,
"s": 8654,
"text": "2. conda init"
},
{
"code": null,
"e": 8797,
"s": 8668,
"text": "Note that in step 1, I changed the shell name from YOUR_SHELL_NAME to bash. You may need to adjust that yourself to your shell.”"
},
{
"code": null,
"e": 9027,
"s": 8797,
"text": "Long story short, it’s entirely possible that modifying PATH might cause you some problems down the road. It’s smarter to go with activation because it isn’t permanent and will allow some packages to run that might not otherwise."
},
{
"code": null,
"e": 9102,
"s": 9027,
"text": "So, at the end of the installer, instead of running the original solution:"
},
{
"code": null,
"e": 9150,
"s": 9102,
"text": "export PATH=\"/Users/myname/anaconda2/bin:$PATH\""
},
{
"code": null,
"e": 9166,
"s": 9150,
"text": "You want to run"
},
{
"code": null,
"e": 9237,
"s": 9166,
"text": "eval \"$(/home/msarahan/mc3_dummy/bin/conda shell.bash hook)”conda init"
},
{
"code": null,
"e": 9310,
"s": 9237,
"text": "(But make sure you change the directory location and shell to your own!)"
},
{
"code": null,
"e": 9330,
"s": 9310,
"text": "***End of update***"
},
{
"code": null,
"e": 9376,
"s": 9330,
"text": "All you need to do to make things work is run"
},
{
"code": null,
"e": 9424,
"s": 9376,
"text": "export PATH=\"/Users/myname/anaconda3/bin:$PATH\""
},
{
"code": null,
"e": 9449,
"s": 9424,
"text": "and you’re good to go!!!"
},
{
"code": null,
"e": 9735,
"s": 9449,
"text": "(Definitely make sure you replace “myname” with your username and change the path to the directory if you need to. If you look at the line above, /Users/myname/anaconda3 would be replaced by /Users/anneb/anaconda3 from the installation location earlier. Keep everything else the same.)"
},
{
"code": null,
"e": 9790,
"s": 9735,
"text": "If you didn’t install Anaconda3, you would need to run"
},
{
"code": null,
"e": 9838,
"s": 9790,
"text": "export PATH=\"/Users/myname/anaconda2/bin:$PATH\""
},
{
"code": null,
"e": 9855,
"s": 9838,
"text": "for Anaconda2 or"
},
{
"code": null,
"e": 9902,
"s": 9855,
"text": "export PATH=\"/Users/myname/anaconda/bin:$PATH\""
},
{
"code": null,
"e": 9974,
"s": 9902,
"text": "making sure to change “myname” and the directory location if necessary."
},
{
"code": null,
"e": 9994,
"s": 9974,
"text": "Now try conda list!"
},
{
"code": null,
"e": 10008,
"s": 9994,
"text": "You did it!!!"
},
{
"code": null,
"e": 10095,
"s": 10008,
"text": "You successfully installed Anaconda and are now able to run it from your command line!"
},
{
"code": null,
"e": 10106,
"s": 10095,
"text": "Try typing"
},
{
"code": null,
"e": 10123,
"s": 10106,
"text": "jupyter notebook"
},
{
"code": null,
"e": 10145,
"s": 10123,
"text": "and see what happens!"
},
{
"code": null,
"e": 10265,
"s": 10145,
"text": "Thanks for reading! If you want to reach out or find more cool articles, please come and join me at Content Simplicity!"
},
{
"code": null,
"e": 10360,
"s": 10265,
"text": "Want to learn about the easiest way to create, run, publish, and even share Jupyter Notebooks?"
},
{
"code": null,
"e": 10383,
"s": 10360,
"text": "towardsdatascience.com"
}
]
|
What is binding in Java? | Association of method call with the method body is known as binding in Java. There are two kinds of binding.
In static binding the method call is bonded with the method body at compile time. This is also known as early binding. This is done using static, private and, final methods.
class Super{
public static void sample(){
System.out.println("This is the method of super class");
}
}
Public class Sub extends Super{
Public static void sample(){
System.out.println("This is the method of sub class");
}
Public static void main(String args[]){
Sub.sample()
}
}
This is the method of sub class
In dynamic binding the method call is bonded with the method body at run time. This is also known as late binding. This is done using instance methods.
class Super{
public void sample(){
System.out.println("This is the method of super class");
}
}
Public class extends Super{
Public static void sample(){
System.out.println("This is the method of sub class");
}
Public static void main(String args[]){
new Sub().sample()
}
}
This is the method of sub class | [
{
"code": null,
"e": 1171,
"s": 1062,
"text": "Association of method call with the method body is known as binding in Java. There are two kinds of binding."
},
{
"code": null,
"e": 1345,
"s": 1171,
"text": "In static binding the method call is bonded with the method body at compile time. This is also known as early binding. This is done using static, private and, final methods."
},
{
"code": null,
"e": 1659,
"s": 1345,
"text": "class Super{\n public static void sample(){\n System.out.println(\"This is the method of super class\");\n }\n}\nPublic class Sub extends Super{\n Public static void sample(){\n System.out.println(\"This is the method of sub class\");\n }\n Public static void main(String args[]){\n Sub.sample()\n }\n}"
},
{
"code": null,
"e": 1692,
"s": 1659,
"text": "This is the method of sub class\n"
},
{
"code": null,
"e": 1844,
"s": 1692,
"text": "In dynamic binding the method call is bonded with the method body at run time. This is also known as late binding. This is done using instance methods."
},
{
"code": null,
"e": 2153,
"s": 1844,
"text": "class Super{\n public void sample(){\n System.out.println(\"This is the method of super class\");\n }\n}\nPublic class extends Super{\n Public static void sample(){\n System.out.println(\"This is the method of sub class\");\n }\n Public static void main(String args[]){\n new Sub().sample()\n }\n}"
},
{
"code": null,
"e": 2186,
"s": 2153,
"text": "This is the method of sub class\n"
}
]
|
Python | Create a GUI Marksheet using Tkinter | 29 May, 2021
Create a python GUI mark sheet. Where credits of each subject are given, enter the grades obtained in each subject and click on Submit. The credits per subject, the total credits as well as the SGPA are displayed after being calculated automatically. Use Tkinter to create the GUI interface.
Refer the below articles to get the idea about basics of tkinter and Python.
Tkinter introduction
Basics of Python
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.
To create a Tkinter:
Importing the module – Tkinter
Create the main window (container)
Add any number of widgets to the main window
Apply the event Trigger on the widgets.
This is how the GUI would look:
Let’s create a GUI-based simple mark sheet using the Python Tkinter module, which can create a mark sheet based on the marks entered per subject.
Below is the implementation :
Python3
# Python program to create a# GUI mark sheet using tkinter # Import tkinter as tkimport tkinter as tk # creating a new tkinter windowmaster = tk.Tk() # assigning a titlemaster.title("MARKSHEET") # specifying geometry for window sizemaster.geometry("700x250") # declaring objects for entering datae1 = tk.Entry(master)e2 = tk.Entry(master)e3 = tk.Entry(master)e4 = tk.Entry(master)e5 = tk.Entry(master)e6 = tk.Entry(master)e7 = tk.Entry(master) # function to display the total subject# credits total credits and SGPA according# to grades entereddef display(): # Variable to store total marks tot=0 # 10*number of subject credits # give total credits for grade A if e4.get() == "A": # grid method is used for placing # the widgets at respective positions # in table like structure . tk.Label(master, text ="40").grid(row=3, column=4) tot += 40 # 9*number of subject credits give # total credits for grade B if e4.get() == "B": tk.Label(master, text ="36").grid(row=3, column=4) tot += 36 # 8*number of subject credits give # total credits for grade C if e4.get() == "C": tk.Label(master, text ="32").grid(row=3, column=4) tot += 32 # 7*number of subject credits # give total credits for grade D if e4.get() == "D": tk.Label(master, text ="28").grid(row=3, column=4) tot += 28 # 6*number of subject credits give # total credits for grade P if e4.get() == "P": tk.Label(master, text ="24").grid(row=3, column=4) tot += 24 # 0*number of subject credits give # total credits for grade F if e4.get() == "F": tk.Label(master, text ="0").grid(row=3, column=4) tot += 0 # Similarly doing with other objects if e5.get() == "A": tk.Label(master, text ="40").grid(row=4, column=4) tot += 40 if e5.get() == "B": tk.Label(master, text ="36").grid(row=4, column=4) tot += 36 if e5.get() == "C": tk.Label(master, text ="32").grid(row=4, column=4) tot += 32 if e5.get() == "D": tk.Label(master, text ="28").grid(row=4, column=4) tot += 28 if e5.get() == "P": tk.Label(master, text ="28").grid(row=4, column=4) tot += 24 if e5.get() == "F": tk.Label(master, text ="0").grid(row=4, column=4) tot += 0 if e6.get() == "A": tk.Label(master, text ="30").grid(row=5, column=4) tot += 30 if e6.get() == "B": tk.Label(master, text ="27").grid(row=5, column=4) tot += 27 if e6.get() == "C": tk.Label(master, text ="24").grid(row=5, column=4) tot += 24 if e6.get() == "D": tk.Label(master, text ="21").grid(row=5, column=4) tot += 21 if e6.get() == "P": tk.Label(master, text ="28").grid(row=5, column=4) tot += 24 if e6.get() == "F": tk.Label(master, text ="0").grid(row=5, column=4) tot += 0 if e7.get() == "A": tk.Label(master, text ="40").grid(row=6, column=4) tot += 40 if e7.get() == "B": tk.Label(master, text ="36").grid(row=6, column=4) tot += 36 if e7.get() == "C": tk.Label(master, text ="32").grid(row=6, column=4) tot += 32 if e7.get() == "D": tk.Label(master, text ="28").grid(row=6, column=4) tot += 28 if e7.get() == "P": tk.Label(master, text ="28").grid(row=6, column=4) tot += 24 if e7.get() == "F": tk.Label(master, text ="0").grid(row=6, column=4) tot += 0 # to display total credits tk.Label(master, text=str(tot)).grid(row=7, column=4) # to display SGPA tk.Label(master, text=str(tot/15)).grid(row=8, column=4) # end of display function # label to enter nametk.Label(master, text="Name").grid(row=0, column=0) # label for registration numbertk.Label(master, text="Reg.No").grid(row=0, column=3) # label for roll Numbertk.Label(master, text="Roll.No").grid(row=1, column=0) # labels for serial numberstk.Label(master, text="Srl.No").grid(row=2, column=0)tk.Label(master, text="1").grid(row=3, column=0)tk.Label(master, text="2").grid(row=4, column=0)tk.Label(master, text="3").grid(row=5, column=0)tk.Label(master, text="4").grid(row=6, column=0) # labels for subject codestk.Label(master, text="Subject").grid(row=2, column=1)tk.Label(master, text="CS 201").grid(row=3, column=1)tk.Label(master, text="CS 202").grid(row=4, column=1)tk.Label(master, text="MA 201").grid(row=5, column=1)tk.Label(master, text="EC 201").grid(row=6, column=1) # label for gradestk.Label(master, text="Grade").grid(row=2, column=2)e4.grid(row=3, column=2)e5.grid(row=4, column=2)e6.grid(row=5, column=2)e7.grid(row=6, column=2) # labels for subject creditstk.Label(master, text="Sub Credit").grid(row=2, column=3)tk.Label(master, text="4").grid(row=3, column=3)tk.Label(master, text="4").grid(row=4, column=3)tk.Label(master, text="3").grid(row=5, column=3)tk.Label(master, text="4").grid(row=6, column=3) tk.Label(master, text="Credit obtained").grid(row=2, column=4) # taking entries of name, reg, roll number respectivelye1=tk.Entry(master)e2=tk.Entry(master)e3=tk.Entry(master) # organizing them in th e gride1.grid(row=0, column=1)e2.grid(row=0, column=4)e3.grid(row=1, column=1) # button to display all the calculated credit scores and sgpabutton1=tk.Button(master, text="submit", bg="green", command=display)button1.grid(row=8, column=1) tk.Label(master, text="Total credit").grid(row=7, column=3)tk.Label(master, text="SGPA").grid(row=8, column=3) master.mainloop() #This Marksheet can be snapshotted and printed out# as a report card for the semester #This code has been contributed by Soumi Bardhan
Output:
abhigoya
saurabh1990aror
Python Tkinter-exercises
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Introduction To PYTHON | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 May, 2021"
},
{
"code": null,
"e": 347,
"s": 54,
"text": "Create a python GUI mark sheet. Where credits of each subject are given, enter the grades obtained in each subject and click on Submit. The credits per subject, the total credits as well as the SGPA are displayed after being calculated automatically. Use Tkinter to create the GUI interface. "
},
{
"code": null,
"e": 425,
"s": 347,
"text": "Refer the below articles to get the idea about basics of tkinter and Python. "
},
{
"code": null,
"e": 446,
"s": 425,
"text": "Tkinter introduction"
},
{
"code": null,
"e": 463,
"s": 446,
"text": "Basics of Python"
},
{
"code": null,
"e": 821,
"s": 463,
"text": "Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task. "
},
{
"code": null,
"e": 842,
"s": 821,
"text": "To create a Tkinter:"
},
{
"code": null,
"e": 873,
"s": 842,
"text": "Importing the module – Tkinter"
},
{
"code": null,
"e": 908,
"s": 873,
"text": "Create the main window (container)"
},
{
"code": null,
"e": 953,
"s": 908,
"text": "Add any number of widgets to the main window"
},
{
"code": null,
"e": 993,
"s": 953,
"text": "Apply the event Trigger on the widgets."
},
{
"code": null,
"e": 1025,
"s": 993,
"text": "This is how the GUI would look:"
},
{
"code": null,
"e": 1172,
"s": 1025,
"text": "Let’s create a GUI-based simple mark sheet using the Python Tkinter module, which can create a mark sheet based on the marks entered per subject. "
},
{
"code": null,
"e": 1203,
"s": 1172,
"text": "Below is the implementation : "
},
{
"code": null,
"e": 1211,
"s": 1203,
"text": "Python3"
},
{
"code": "# Python program to create a# GUI mark sheet using tkinter # Import tkinter as tkimport tkinter as tk # creating a new tkinter windowmaster = tk.Tk() # assigning a titlemaster.title(\"MARKSHEET\") # specifying geometry for window sizemaster.geometry(\"700x250\") # declaring objects for entering datae1 = tk.Entry(master)e2 = tk.Entry(master)e3 = tk.Entry(master)e4 = tk.Entry(master)e5 = tk.Entry(master)e6 = tk.Entry(master)e7 = tk.Entry(master) # function to display the total subject# credits total credits and SGPA according# to grades entereddef display(): # Variable to store total marks tot=0 # 10*number of subject credits # give total credits for grade A if e4.get() == \"A\": # grid method is used for placing # the widgets at respective positions # in table like structure . tk.Label(master, text =\"40\").grid(row=3, column=4) tot += 40 # 9*number of subject credits give # total credits for grade B if e4.get() == \"B\": tk.Label(master, text =\"36\").grid(row=3, column=4) tot += 36 # 8*number of subject credits give # total credits for grade C if e4.get() == \"C\": tk.Label(master, text =\"32\").grid(row=3, column=4) tot += 32 # 7*number of subject credits # give total credits for grade D if e4.get() == \"D\": tk.Label(master, text =\"28\").grid(row=3, column=4) tot += 28 # 6*number of subject credits give # total credits for grade P if e4.get() == \"P\": tk.Label(master, text =\"24\").grid(row=3, column=4) tot += 24 # 0*number of subject credits give # total credits for grade F if e4.get() == \"F\": tk.Label(master, text =\"0\").grid(row=3, column=4) tot += 0 # Similarly doing with other objects if e5.get() == \"A\": tk.Label(master, text =\"40\").grid(row=4, column=4) tot += 40 if e5.get() == \"B\": tk.Label(master, text =\"36\").grid(row=4, column=4) tot += 36 if e5.get() == \"C\": tk.Label(master, text =\"32\").grid(row=4, column=4) tot += 32 if e5.get() == \"D\": tk.Label(master, text =\"28\").grid(row=4, column=4) tot += 28 if e5.get() == \"P\": tk.Label(master, text =\"28\").grid(row=4, column=4) tot += 24 if e5.get() == \"F\": tk.Label(master, text =\"0\").grid(row=4, column=4) tot += 0 if e6.get() == \"A\": tk.Label(master, text =\"30\").grid(row=5, column=4) tot += 30 if e6.get() == \"B\": tk.Label(master, text =\"27\").grid(row=5, column=4) tot += 27 if e6.get() == \"C\": tk.Label(master, text =\"24\").grid(row=5, column=4) tot += 24 if e6.get() == \"D\": tk.Label(master, text =\"21\").grid(row=5, column=4) tot += 21 if e6.get() == \"P\": tk.Label(master, text =\"28\").grid(row=5, column=4) tot += 24 if e6.get() == \"F\": tk.Label(master, text =\"0\").grid(row=5, column=4) tot += 0 if e7.get() == \"A\": tk.Label(master, text =\"40\").grid(row=6, column=4) tot += 40 if e7.get() == \"B\": tk.Label(master, text =\"36\").grid(row=6, column=4) tot += 36 if e7.get() == \"C\": tk.Label(master, text =\"32\").grid(row=6, column=4) tot += 32 if e7.get() == \"D\": tk.Label(master, text =\"28\").grid(row=6, column=4) tot += 28 if e7.get() == \"P\": tk.Label(master, text =\"28\").grid(row=6, column=4) tot += 24 if e7.get() == \"F\": tk.Label(master, text =\"0\").grid(row=6, column=4) tot += 0 # to display total credits tk.Label(master, text=str(tot)).grid(row=7, column=4) # to display SGPA tk.Label(master, text=str(tot/15)).grid(row=8, column=4) # end of display function # label to enter nametk.Label(master, text=\"Name\").grid(row=0, column=0) # label for registration numbertk.Label(master, text=\"Reg.No\").grid(row=0, column=3) # label for roll Numbertk.Label(master, text=\"Roll.No\").grid(row=1, column=0) # labels for serial numberstk.Label(master, text=\"Srl.No\").grid(row=2, column=0)tk.Label(master, text=\"1\").grid(row=3, column=0)tk.Label(master, text=\"2\").grid(row=4, column=0)tk.Label(master, text=\"3\").grid(row=5, column=0)tk.Label(master, text=\"4\").grid(row=6, column=0) # labels for subject codestk.Label(master, text=\"Subject\").grid(row=2, column=1)tk.Label(master, text=\"CS 201\").grid(row=3, column=1)tk.Label(master, text=\"CS 202\").grid(row=4, column=1)tk.Label(master, text=\"MA 201\").grid(row=5, column=1)tk.Label(master, text=\"EC 201\").grid(row=6, column=1) # label for gradestk.Label(master, text=\"Grade\").grid(row=2, column=2)e4.grid(row=3, column=2)e5.grid(row=4, column=2)e6.grid(row=5, column=2)e7.grid(row=6, column=2) # labels for subject creditstk.Label(master, text=\"Sub Credit\").grid(row=2, column=3)tk.Label(master, text=\"4\").grid(row=3, column=3)tk.Label(master, text=\"4\").grid(row=4, column=3)tk.Label(master, text=\"3\").grid(row=5, column=3)tk.Label(master, text=\"4\").grid(row=6, column=3) tk.Label(master, text=\"Credit obtained\").grid(row=2, column=4) # taking entries of name, reg, roll number respectivelye1=tk.Entry(master)e2=tk.Entry(master)e3=tk.Entry(master) # organizing them in th e gride1.grid(row=0, column=1)e2.grid(row=0, column=4)e3.grid(row=1, column=1) # button to display all the calculated credit scores and sgpabutton1=tk.Button(master, text=\"submit\", bg=\"green\", command=display)button1.grid(row=8, column=1) tk.Label(master, text=\"Total credit\").grid(row=7, column=3)tk.Label(master, text=\"SGPA\").grid(row=8, column=3) master.mainloop() #This Marksheet can be snapshotted and printed out# as a report card for the semester #This code has been contributed by Soumi Bardhan",
"e": 7027,
"s": 1211,
"text": null
},
{
"code": null,
"e": 7035,
"s": 7027,
"text": "Output:"
},
{
"code": null,
"e": 7044,
"s": 7035,
"text": "abhigoya"
},
{
"code": null,
"e": 7060,
"s": 7044,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 7085,
"s": 7060,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 7100,
"s": 7085,
"text": "Python-tkinter"
},
{
"code": null,
"e": 7107,
"s": 7100,
"text": "Python"
},
{
"code": null,
"e": 7205,
"s": 7107,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7223,
"s": 7205,
"text": "Python Dictionary"
},
{
"code": null,
"e": 7265,
"s": 7223,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 7287,
"s": 7265,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 7322,
"s": 7287,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 7348,
"s": 7322,
"text": "Python String | replace()"
},
{
"code": null,
"e": 7380,
"s": 7348,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 7409,
"s": 7380,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 7439,
"s": 7409,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 7466,
"s": 7439,
"text": "Python Classes and Objects"
}
]
|
PyQt5 – Set maximum size for width or height of window | 26 Mar, 2020
When we create a window, by default the window size is resizable, although we can use setMaximumSize() method to set the maximum size of the window. But what if we want to set maximum length only for width or height only. In order to do so we use setMaximumWidth() and setMaximumHeight() method to set maximum width / height. When we use these method other length will be variable i.e there will be no maximum length to it, it can be stretched to the size of screen.
Syntax :
self.setMaximumWidth(width)
self.setMaximumHeight(height)
Argument : Both takes integer as argument.
Action performed :setMaximumWidth() sets the maximum width.setMaximumHeight() sets the maximum height.
Code for maximum width –
# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Python") width = 200 # setting the maximum width self.setMaximumWidth(width) # creating a label widget self.label_1 = QLabel("Maximum width", self) # moving position self.label_1.move(0, 0) # setting up the border self.label_1.setStyleSheet("border :3px solid black;") # resizing label self.label_1.resize(120, 80) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output : Code for maximum height –
# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Python") height = 200 # setting the maximum height self.setMaximumHeight(height) # creating a label widget self.label_1 = QLabel("Maximum height", self) # moving position self.label_1.move(0, 0) # setting up the border self.label_1.setStyleSheet("border :3px solid black;") # resizing label self.label_1.resize(120, 80) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 495,
"s": 28,
"text": "When we create a window, by default the window size is resizable, although we can use setMaximumSize() method to set the maximum size of the window. But what if we want to set maximum length only for width or height only. In order to do so we use setMaximumWidth() and setMaximumHeight() method to set maximum width / height. When we use these method other length will be variable i.e there will be no maximum length to it, it can be stretched to the size of screen."
},
{
"code": null,
"e": 504,
"s": 495,
"text": "Syntax :"
},
{
"code": null,
"e": 563,
"s": 504,
"text": "self.setMaximumWidth(width)\nself.setMaximumHeight(height)\n"
},
{
"code": null,
"e": 606,
"s": 563,
"text": "Argument : Both takes integer as argument."
},
{
"code": null,
"e": 709,
"s": 606,
"text": "Action performed :setMaximumWidth() sets the maximum width.setMaximumHeight() sets the maximum height."
},
{
"code": null,
"e": 734,
"s": 709,
"text": "Code for maximum width –"
},
{
"code": "# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Python\") width = 200 # setting the maximum width self.setMaximumWidth(width) # creating a label widget self.label_1 = QLabel(\"Maximum width\", self) # moving position self.label_1.move(0, 0) # setting up the border self.label_1.setStyleSheet(\"border :3px solid black;\") # resizing label self.label_1.resize(120, 80) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 1592,
"s": 734,
"text": null
},
{
"code": null,
"e": 1627,
"s": 1592,
"text": "Output : Code for maximum height –"
},
{
"code": "# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Python\") height = 200 # setting the maximum height self.setMaximumHeight(height) # creating a label widget self.label_1 = QLabel(\"Maximum height\", self) # moving position self.label_1.move(0, 0) # setting up the border self.label_1.setStyleSheet(\"border :3px solid black;\") # resizing label self.label_1.resize(120, 80) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 2494,
"s": 1627,
"text": null
},
{
"code": null,
"e": 2503,
"s": 2494,
"text": "Output :"
},
{
"code": null,
"e": 2514,
"s": 2503,
"text": "Python-gui"
},
{
"code": null,
"e": 2526,
"s": 2514,
"text": "Python-PyQt"
},
{
"code": null,
"e": 2533,
"s": 2526,
"text": "Python"
}
]
|
MongoDB insertOne() Method – db.Collection.insertOne() | 28 Jan, 2021
In MongoDB, insertOne() method inserts a document into the collection. This method inserts only one document at a time.
Using this method you can also create a collection by inserting documents.
You can insert documents with or without _id field. If you insert a document in the collection without _id field, then MongoDB will automatically add an _id field and assign it with a unique ObjectId. And if you insert a document with _id field, then the value of the _id field must be unique to avoid the duplicate key error.
This method can also throw either writeError or writeConcernError exception.
This method can also be used inside multi-document transactions.
Syntax:
db.Collection_name.insertOne(
<document>,
{
writeConcern: <document>
})
Parameters:
The first parameter is the document. Documents are a structure created of file and value pairs, similar to JSON objects.
The second parameter is optional.
Optional Parameter:
writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document.
Return:
This method returns :
Boolean acknowledged as true if write concern was enabled or false if write concern was disabled.
The insertedId field with the _id value of the inserted document.
Examples:
In the following examples, we are working with:
Database: gfg
Collection: student
Document: No document but, we want to insert in the form of the student name and student marks.
Insert a single document without specifying the _id field
Here, we are inserting the document whose name is Akshay and marks is 500 in the student collection.
db.student.insertOne({Name: "Akshay", Marks: 500})
Insert a single document with _id field
Here, we are inserting a document whose unique id is Stu102, name is Vishal, and marks is 230 in the student collection
db.student.insertOne({_id: "Stu102", Name: "Vishal", Marks: 230})
MongoDB-method
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jan, 2021"
},
{
"code": null,
"e": 149,
"s": 28,
"text": "In MongoDB, insertOne() method inserts a document into the collection. This method inserts only one document at a time. "
},
{
"code": null,
"e": 224,
"s": 149,
"text": "Using this method you can also create a collection by inserting documents."
},
{
"code": null,
"e": 551,
"s": 224,
"text": "You can insert documents with or without _id field. If you insert a document in the collection without _id field, then MongoDB will automatically add an _id field and assign it with a unique ObjectId. And if you insert a document with _id field, then the value of the _id field must be unique to avoid the duplicate key error."
},
{
"code": null,
"e": 628,
"s": 551,
"text": "This method can also throw either writeError or writeConcernError exception."
},
{
"code": null,
"e": 693,
"s": 628,
"text": "This method can also be used inside multi-document transactions."
},
{
"code": null,
"e": 703,
"s": 693,
"text": " Syntax: "
},
{
"code": null,
"e": 733,
"s": 703,
"text": "db.Collection_name.insertOne("
},
{
"code": null,
"e": 745,
"s": 733,
"text": "<document>,"
},
{
"code": null,
"e": 747,
"s": 745,
"text": "{"
},
{
"code": null,
"e": 776,
"s": 747,
"text": " writeConcern: <document>"
},
{
"code": null,
"e": 779,
"s": 776,
"text": "})"
},
{
"code": null,
"e": 791,
"s": 779,
"text": "Parameters:"
},
{
"code": null,
"e": 912,
"s": 791,
"text": "The first parameter is the document. Documents are a structure created of file and value pairs, similar to JSON objects."
},
{
"code": null,
"e": 946,
"s": 912,
"text": "The second parameter is optional."
},
{
"code": null,
"e": 966,
"s": 946,
"text": "Optional Parameter:"
},
{
"code": null,
"e": 1093,
"s": 966,
"text": "writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document."
},
{
"code": null,
"e": 1101,
"s": 1093,
"text": "Return:"
},
{
"code": null,
"e": 1123,
"s": 1101,
"text": "This method returns :"
},
{
"code": null,
"e": 1221,
"s": 1123,
"text": "Boolean acknowledged as true if write concern was enabled or false if write concern was disabled."
},
{
"code": null,
"e": 1287,
"s": 1221,
"text": "The insertedId field with the _id value of the inserted document."
},
{
"code": null,
"e": 1297,
"s": 1287,
"text": "Examples:"
},
{
"code": null,
"e": 1345,
"s": 1297,
"text": "In the following examples, we are working with:"
},
{
"code": null,
"e": 1359,
"s": 1345,
"text": "Database: gfg"
},
{
"code": null,
"e": 1379,
"s": 1359,
"text": "Collection: student"
},
{
"code": null,
"e": 1475,
"s": 1379,
"text": "Document: No document but, we want to insert in the form of the student name and student marks."
},
{
"code": null,
"e": 1533,
"s": 1475,
"text": "Insert a single document without specifying the _id field"
},
{
"code": null,
"e": 1635,
"s": 1533,
"text": " Here, we are inserting the document whose name is Akshay and marks is 500 in the student collection."
},
{
"code": null,
"e": 1686,
"s": 1635,
"text": "db.student.insertOne({Name: \"Akshay\", Marks: 500})"
},
{
"code": null,
"e": 1726,
"s": 1686,
"text": "Insert a single document with _id field"
},
{
"code": null,
"e": 1846,
"s": 1726,
"text": "Here, we are inserting a document whose unique id is Stu102, name is Vishal, and marks is 230 in the student collection"
},
{
"code": null,
"e": 1912,
"s": 1846,
"text": "db.student.insertOne({_id: \"Stu102\", Name: \"Vishal\", Marks: 230})"
},
{
"code": null,
"e": 1927,
"s": 1912,
"text": "MongoDB-method"
},
{
"code": null,
"e": 1934,
"s": 1927,
"text": "Picked"
},
{
"code": null,
"e": 1942,
"s": 1934,
"text": "MongoDB"
}
]
|
strings.SplitN() Function in Golang with Examples | 19 Apr, 2020
strings.SplitN() Function() is a string manipulation function in Go language. It is used to split a given string into substrings separated by a separator. This function returns the slices of all substrings between those separators.
Syntax:
func SplitN(s, sep string, n int) []string
Here, s is the string and sep is the separator. If s does not contain the given sep and sep is non-empty, then it will return a slice of length 1 which contains only s. Or if the sep is empty, then it will split after each UTF-8 sequence. Or if both s and sep are empty, then it will return an empty slice.
Here, the last parameter determines the number of strings to be returned by the function. It can be any of the following:
n is equal to zero (n == 0) : The result is nil, i.e, zero sub strings. An empty list is returned.
n is greater than zero (n > 0) : At most n sub strings will be returned and the last string will be the unsplit remainder.
n is less than zero (n < 0) : All possible substring will be returned.
Example 1:
// Golang program to illustrate the// strings.SplitN() Functionpackage main import ( "fmt" "strings") func main() { // String s a is comma serparated string // The separater used is "," // This will split the string into 6 parts s := strings.SplitN("a,b,c,d,e,f", ",",6) fmt.Println(s)}
Output:
[a b c d e f]
Example 2:
// Golang program to illustrate the// strings.SplitN() Functionpackage main import ( "fmt" "strings") func main() { // String s will be separated by spaces // -1 implies all the possible sub strings // that can be generated s := strings.SplitN("I love GeeksforGeeks portal!", " ", -1) // This will print all the sub strings // of string s in a new line for _, v := range s { fmt.Println(v) }}
Output:
I
love
GeeksforGeeks
portal!
Example 3:
// Golang program to illustrate the// strings.SplitN() Functionpackage main import ( "fmt" "strings") func main() { // This will give empty sub string // as 0 is provided as the last parameter s := strings.SplitN("a,b,c", ",", 0) fmt.Println(s) // This will give only 3 sub strings // a and b will be the first 2 sub strings s = strings.SplitN("a:b:c:d:e:f", ":", 3) fmt.Println(s) // Delimiter can be anything // a -ve number specifies all sub strings s = strings.SplitN("1234x5678x1234x5678", "x", -1) fmt.Println(s) // When the separator is not present in // given list, original string is returned s = strings.SplitN("qwerty", ",", 6) fmt.Println(s)}
Output:
[]
[a b c:d:e:f]
[1234 5678 1234 5678]
[qwerty]
Golang-String
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 260,
"s": 28,
"text": "strings.SplitN() Function() is a string manipulation function in Go language. It is used to split a given string into substrings separated by a separator. This function returns the slices of all substrings between those separators."
},
{
"code": null,
"e": 268,
"s": 260,
"text": "Syntax:"
},
{
"code": null,
"e": 311,
"s": 268,
"text": "func SplitN(s, sep string, n int) []string"
},
{
"code": null,
"e": 618,
"s": 311,
"text": "Here, s is the string and sep is the separator. If s does not contain the given sep and sep is non-empty, then it will return a slice of length 1 which contains only s. Or if the sep is empty, then it will split after each UTF-8 sequence. Or if both s and sep are empty, then it will return an empty slice."
},
{
"code": null,
"e": 740,
"s": 618,
"text": "Here, the last parameter determines the number of strings to be returned by the function. It can be any of the following:"
},
{
"code": null,
"e": 839,
"s": 740,
"text": "n is equal to zero (n == 0) : The result is nil, i.e, zero sub strings. An empty list is returned."
},
{
"code": null,
"e": 962,
"s": 839,
"text": "n is greater than zero (n > 0) : At most n sub strings will be returned and the last string will be the unsplit remainder."
},
{
"code": null,
"e": 1033,
"s": 962,
"text": "n is less than zero (n < 0) : All possible substring will be returned."
},
{
"code": null,
"e": 1044,
"s": 1033,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate the// strings.SplitN() Functionpackage main import ( \"fmt\" \"strings\") func main() { // String s a is comma serparated string // The separater used is \",\" // This will split the string into 6 parts s := strings.SplitN(\"a,b,c,d,e,f\", \",\",6) fmt.Println(s)}",
"e": 1359,
"s": 1044,
"text": null
},
{
"code": null,
"e": 1367,
"s": 1359,
"text": "Output:"
},
{
"code": null,
"e": 1382,
"s": 1367,
"text": "[a b c d e f]\n"
},
{
"code": null,
"e": 1393,
"s": 1382,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate the// strings.SplitN() Functionpackage main import ( \"fmt\" \"strings\") func main() { // String s will be separated by spaces // -1 implies all the possible sub strings // that can be generated s := strings.SplitN(\"I love GeeksforGeeks portal!\", \" \", -1) // This will print all the sub strings // of string s in a new line for _, v := range s { fmt.Println(v) }}",
"e": 1829,
"s": 1393,
"text": null
},
{
"code": null,
"e": 1837,
"s": 1829,
"text": "Output:"
},
{
"code": null,
"e": 1867,
"s": 1837,
"text": "I\nlove\nGeeksforGeeks\nportal!\n"
},
{
"code": null,
"e": 1878,
"s": 1867,
"text": "Example 3:"
},
{
"code": "// Golang program to illustrate the// strings.SplitN() Functionpackage main import ( \"fmt\" \"strings\") func main() { // This will give empty sub string // as 0 is provided as the last parameter s := strings.SplitN(\"a,b,c\", \",\", 0) fmt.Println(s) // This will give only 3 sub strings // a and b will be the first 2 sub strings s = strings.SplitN(\"a:b:c:d:e:f\", \":\", 3) fmt.Println(s) // Delimiter can be anything // a -ve number specifies all sub strings s = strings.SplitN(\"1234x5678x1234x5678\", \"x\", -1) fmt.Println(s) // When the separator is not present in // given list, original string is returned s = strings.SplitN(\"qwerty\", \",\", 6) fmt.Println(s)}",
"e": 2597,
"s": 1878,
"text": null
},
{
"code": null,
"e": 2605,
"s": 2597,
"text": "Output:"
},
{
"code": null,
"e": 2654,
"s": 2605,
"text": "[]\n[a b c:d:e:f]\n[1234 5678 1234 5678]\n[qwerty]\n"
},
{
"code": null,
"e": 2668,
"s": 2654,
"text": "Golang-String"
},
{
"code": null,
"e": 2675,
"s": 2668,
"text": "Picked"
},
{
"code": null,
"e": 2687,
"s": 2675,
"text": "Go Language"
}
]
|
How to uncompress a “.tar.gz” file using Python ? | 17 Dec, 2020
.tar.gz files are made by the combination of TAR packaging followed by a GNU zip (gzip) compression. These files are commonly used in Unix/Linux based system as packages or installers. In order to read or extract these files, we have to first decompress these files and after that expand them with the TAR utilities as these files contain both .tar and .gz files.
In order to extract or un-compress “.tar.gz” files using python, we have to use the tarfile module in python. This module can read and write .tar files including .gz, .bz compression methods.
Import module
Open .tar.gz file
Extract file in a specific folder
Close file
Name: gfg.tar.gz
Link to download this file: Click here
Contents:
“gfg.tar.gz” file
Example:
Python3
# importing the "tarfile" moduleimport tarfile # open filefile = tarfile.open('gfg.tar.gz') # extracting filefile.extractall('./Destination_FolderName') file.close()
Output:
A folder named “Destination_Folder” is created.
Files are uncompressed inside the “Destination_Folder”
Example: Printing file names before extracting
Python3
# importing the "tarfile" moduleimport tarfile # open filefile = tarfile.open('gfg.tar.gz') # print file namesprint(file.getnames()) # extract filesfile.extractall('./Destination_FolderName') # close filefile.close()
Output:
Example : Extract a specific file
Python3
# importing the "tarfile" moduleimport tarfile # open filefile = tarfile.open('gfg.tar.gz') # extracting a specific filefile.extract('sample.txt', './Destination_FolderName') file.close()
Output:
A new folder named “Destination_FolderName” is created
‘sample.txt’ is uncompressed inside the “Destination_FolderName”
Picked
python-utility
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Dec, 2020"
},
{
"code": null,
"e": 416,
"s": 52,
"text": ".tar.gz files are made by the combination of TAR packaging followed by a GNU zip (gzip) compression. These files are commonly used in Unix/Linux based system as packages or installers. In order to read or extract these files, we have to first decompress these files and after that expand them with the TAR utilities as these files contain both .tar and .gz files."
},
{
"code": null,
"e": 608,
"s": 416,
"text": "In order to extract or un-compress “.tar.gz” files using python, we have to use the tarfile module in python. This module can read and write .tar files including .gz, .bz compression methods."
},
{
"code": null,
"e": 622,
"s": 608,
"text": "Import module"
},
{
"code": null,
"e": 640,
"s": 622,
"text": "Open .tar.gz file"
},
{
"code": null,
"e": 674,
"s": 640,
"text": "Extract file in a specific folder"
},
{
"code": null,
"e": 685,
"s": 674,
"text": "Close file"
},
{
"code": null,
"e": 703,
"s": 685,
"text": "Name: gfg.tar.gz "
},
{
"code": null,
"e": 742,
"s": 703,
"text": "Link to download this file: Click here"
},
{
"code": null,
"e": 752,
"s": 742,
"text": "Contents:"
},
{
"code": null,
"e": 770,
"s": 752,
"text": "“gfg.tar.gz” file"
},
{
"code": null,
"e": 779,
"s": 770,
"text": "Example:"
},
{
"code": null,
"e": 787,
"s": 779,
"text": "Python3"
},
{
"code": "# importing the \"tarfile\" moduleimport tarfile # open filefile = tarfile.open('gfg.tar.gz') # extracting filefile.extractall('./Destination_FolderName') file.close()",
"e": 956,
"s": 787,
"text": null
},
{
"code": null,
"e": 964,
"s": 956,
"text": "Output:"
},
{
"code": null,
"e": 1012,
"s": 964,
"text": "A folder named “Destination_Folder” is created."
},
{
"code": null,
"e": 1067,
"s": 1012,
"text": "Files are uncompressed inside the “Destination_Folder”"
},
{
"code": null,
"e": 1114,
"s": 1067,
"text": "Example: Printing file names before extracting"
},
{
"code": null,
"e": 1122,
"s": 1114,
"text": "Python3"
},
{
"code": "# importing the \"tarfile\" moduleimport tarfile # open filefile = tarfile.open('gfg.tar.gz') # print file namesprint(file.getnames()) # extract filesfile.extractall('./Destination_FolderName') # close filefile.close()",
"e": 1343,
"s": 1122,
"text": null
},
{
"code": null,
"e": 1351,
"s": 1343,
"text": "Output:"
},
{
"code": null,
"e": 1385,
"s": 1351,
"text": "Example : Extract a specific file"
},
{
"code": null,
"e": 1393,
"s": 1385,
"text": "Python3"
},
{
"code": "# importing the \"tarfile\" moduleimport tarfile # open filefile = tarfile.open('gfg.tar.gz') # extracting a specific filefile.extract('sample.txt', './Destination_FolderName') file.close()",
"e": 1584,
"s": 1393,
"text": null
},
{
"code": null,
"e": 1592,
"s": 1584,
"text": "Output:"
},
{
"code": null,
"e": 1647,
"s": 1592,
"text": "A new folder named “Destination_FolderName” is created"
},
{
"code": null,
"e": 1712,
"s": 1647,
"text": "‘sample.txt’ is uncompressed inside the “Destination_FolderName”"
},
{
"code": null,
"e": 1719,
"s": 1712,
"text": "Picked"
},
{
"code": null,
"e": 1734,
"s": 1719,
"text": "python-utility"
},
{
"code": null,
"e": 1758,
"s": 1734,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1765,
"s": 1758,
"text": "Python"
},
{
"code": null,
"e": 1784,
"s": 1765,
"text": "Technical Scripter"
}
]
|
Add two numbers represented by linked lists | Set 2 | 11 Jul, 2022
Given two numbers represented by two linked lists, write a function that returns the sum list. The sum list is linked list representation of the addition of two input numbers. It is not allowed to modify the lists. Also, not allowed to use explicit extra space (Hint: Use Recursion).
Example :
Input:
First List: 5->6->3
Second List: 8->4->2
Output
Resultant list: 1->4->0->5
We have discussed a solution here which is for linked lists where a least significant digit is the first node of lists and the most significant digit is the last node. In this problem, the most significant node is the first node and the least significant digit is the last node and we are not allowed to modify the lists. Recursion is used here to calculate sum from right to left.
Following are the steps. 1) Calculate sizes of given two linked lists. 2) If sizes are same, then calculate sum using recursion. Hold all nodes in recursion call stack till the rightmost node, calculate the sum of rightmost nodes and forward carry to the left side. 3) If size is not same, then follow below steps: ....a) Calculate difference of sizes of two linked lists. Let the difference be diff ....b) Move diff nodes ahead in the bigger linked list. Now use step 2 to calculate the sum of the smaller list and right sub-list (of the same size) of a larger list. Also, store the carry of this sum. ....c) Calculate the sum of the carry (calculated in the previous step) with the remaining left sub-list of a larger list. Nodes of this sum are added at the beginning of the sum list obtained the previous step.
Below is a dry run of the above approach:
Below image is the implementation of the above approach.
C++
C
Java
C#
Javascript
// A C++ recursive program to add two linked lists#include <bits/stdc++.h>using namespace std; // A linked List Nodeclass Node {public: int data; Node* next;}; typedef Node node; /* A utility function to inserta node at the beginning of linked list */void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = new Node[(sizeof(Node))]; /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* A utility function to print linked list */void printList(Node* node){ while (node != NULL) { cout << node->data << " "; node = node->next; } cout << endl;} // A utility function to swap two pointersvoid swapPointer(Node** a, Node** b){ node* t = *a; *a = *b; *b = t;} /* A utility function to get size of linked list */int getSize(Node* node){ int size = 0; while (node != NULL) { node = node->next; size++; } return size;} // Adds two linked lists of same size// represented by head1 and head2 and returns// head of the resultant linked list. Carry// is propagated while returning from the recursionnode* addSameSize(Node* head1, Node* head2, int* carry){ // Since the function assumes linked lists are of same // size, check any of the two head pointers if (head1 == NULL) return NULL; int sum; // Allocate memory for sum node of current two nodes Node* result = new Node[(sizeof(Node))]; // Recursively add remaining nodes and get the carry result->next = addSameSize(head1->next, head2->next, carry); // add digits of current nodes and propagated carry sum = head1->data + head2->data + *carry; *carry = sum / 10; sum = sum % 10; // Assign the sum to current node of resultant list result->data = sum; return result;} // This function is called after the// smaller list is added to the bigger// lists's sublist of same size. Once the// right sublist is added, the carry// must be added toe left side of larger// list to get the final result.void addCarryToRemaining(Node* head1, Node* cur, int* carry, Node** result){ int sum; // If diff. number of nodes are not traversed, add carry if (head1 != cur) { addCarryToRemaining(head1->next, cur, carry, result); sum = head1->data + *carry; *carry = sum / 10; sum %= 10; // add this node to the front of the result push(result, sum); }} // The main function that adds two linked lists// represented by head1 and head2. The sum of// two lists is stored in a list referred by resultvoid addList(Node* head1, Node* head2, Node** result){ Node* cur; // first list is empty if (head1 == NULL) { *result = head2; return; } // second list is empty else if (head2 == NULL) { *result = head1; return; } int size1 = getSize(head1); int size2 = getSize(head2); int carry = 0; // Add same size lists if (size1 == size2) *result = addSameSize(head1, head2, &carry); else { int diff = abs(size1 - size2); // First list should always be larger than second // list. If not, swap pointers if (size1 < size2) swapPointer(&head1, &head2); // move diff. number of nodes in first list for (cur = head1; diff--; cur = cur->next) ; // get addition of same size lists *result = addSameSize(cur, head2, &carry); // get addition of remaining first list and carry addCarryToRemaining(head1, cur, &carry, result); } // if some carry is still there, add a new node to the // front of the result list. e.g. 999 and 87 if (carry) push(result, carry);} // Driver codeint main(){ Node *head1 = NULL, *head2 = NULL, *result = NULL; int arr1[] = { 9, 9, 9 }; int arr2[] = { 1, 8 }; int size1 = sizeof(arr1) / sizeof(arr1[0]); int size2 = sizeof(arr2) / sizeof(arr2[0]); // Create first list as 9->9->9 int i; for (i = size1 - 1; i >= 0; --i) push(&head1, arr1[i]); // Create second list as 1->8 for (i = size2 - 1; i >= 0; --i) push(&head2, arr2[i]); addList(head1, head2, &result); printList(result); return 0;} // This code is contributed by rathbhupendra
// A C recursive program to add two linked lists #include <stdio.h>#include <stdlib.h> // A linked List Nodestruct Node { int data; struct Node* next;}; typedef struct Node node; /* A utility function to insert a node at the beginning of * linked list */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* A utility function to print linked list */void printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; } printf("n");} // A utility function to swap two pointersvoid swapPointer(Node** a, Node** b){ node* t = *a; *a = *b; *b = t;} /* A utility function to get size of linked list */int getSize(struct Node* node){ int size = 0; while (node != NULL) { node = node->next; size++; } return size;} // Adds two linked lists of same// size represented by head1// and head2 and returns head of// the resultant linked list.// Carry is propagated while// returning from the recursionnode* addSameSize(Node* head1, Node* head2, int* carry){ // Since the function assumes // linked lists are of same // size, check any of the two // head pointers if (head1 == NULL) return NULL; int sum; // Allocate memory for sum // node of current two nodes Node* result = (Node*)malloc(sizeof(Node)); // Recursively add remaining nodes // and get the carry result->next = addSameSize(head1->next, head2->next, carry); // add digits of current nodes // and propagated carry sum = head1->data + head2->data + *carry; *carry = sum / 10; sum = sum % 10; // Assigne the sum to current // node of resultant list result->data = sum; return result;} // This function is called after// the smaller list is added// to the bigger lists's sublist// of same size. Once the// right sublist is added, the// carry must be added toe left// side of larger list to get// the final result.void addCarryToRemaining(Node* head1, Node* cur, int* carry, Node** result){ int sum; // If diff. number of nodes are // not traversed, add carry if (head1 != cur) { addCarryToRemaining(head1->next, cur, carry, result); sum = head1->data + *carry; *carry = sum / 10; sum %= 10; // add this node to the front of the result push(result, sum); }} // The main function that adds two// linked lists represented// by head1 and head2. The sum of// two lists is stored in a// list referred by resultvoid addList(Node* head1, Node* head2, Node** result){ Node* cur; // first list is empty if (head1 == NULL) { *result = head2; return; } // second list is empty else if (head2 == NULL) { *result = head1; return; } int size1 = getSize(head1); int size2 = getSize(head2); int carry = 0; // Add same size lists if (size1 == size2) *result = addSameSize(head1, head2, &carry); else { int diff = abs(size1 - size2); // First list should always be // larger than second // list. If not, swap pointers if (size1 < size2) swapPointer(&head1, &head2); // move diff. number of nodes in first list for (cur = head1; diff--; cur = cur->next) ; // get addition of same size lists *result = addSameSize(cur, head2, &carry); // get addition of remaining first list and carry addCarryToRemaining(head1, cur, &carry, result); } // if some carry is still there, add a new node to the // front of the result list. e.g. 999 and 87 if (carry) push(result, carry);} // Driver codeint main(){ Node *head1 = NULL, *head2 = NULL, *result = NULL; int arr1[] = { 9, 9, 9 }; int arr2[] = { 1, 8 }; int size1 = sizeof(arr1) / sizeof(arr1[0]); int size2 = sizeof(arr2) / sizeof(arr2[0]); // Create first list as 9->9->9 int i; for (i = size1 - 1; i >= 0; --i) push(&head1, arr1[i]); // Create second list as 1->8 for (i = size2 - 1; i >= 0; --i) push(&head2, arr2[i]); addList(head1, head2, &result); printList(result); return 0;}
// A Java recursive program to add two linked lists public class linkedlistATN{ class node { int val; node next; public node(int val) { this.val = val; } } // Function to print linked list void printlist(node head) { while (head != null) { System.out.print(head.val + " "); head = head.next; } } node head1, head2, result; int carry; /* A utility function to push a value to linked list */ void push(int val, int list) { node newnode = new node(val); if (list == 1) { newnode.next = head1; head1 = newnode; } else if (list == 2) { newnode.next = head2; head2 = newnode; } else { newnode.next = result; result = newnode; } } // Adds two linked lists of same size represented by // head1 and head2 and returns head of the resultant // linked list. Carry is propagated while returning // from the recursion void addsamesize(node n, node m) { // Since the function assumes linked lists are of // same size, check any of the two head pointers if (n == null) return; // Recursively add remaining nodes and get the carry addsamesize(n.next, m.next); // add digits of current nodes and propagated carry int sum = n.val + m.val + carry; carry = sum / 10; sum = sum % 10; // Push this to result list push(sum, 3); } node cur; // This function is called after the smaller list is // added to the bigger lists's sublist of same size. // Once the right sublist is added, the carry must be // added to the left side of larger list to get the // final result. void propogatecarry(node head1) { // If diff. number of nodes are not traversed, add carry if (head1 != cur) { propogatecarry(head1.next); int sum = carry + head1.val; carry = sum / 10; sum %= 10; // add this node to the front of the result push(sum, 3); } } int getsize(node head) { int count = 0; while (head != null) { count++; head = head.next; } return count; } // The main function that adds two linked lists // represented by head1 and head2. The sum of two // lists is stored in a list referred by result void addlists() { // first list is empty if (head1 == null) { result = head2; return; } // first list is empty if (head2 == null) { result = head1; return; } int size1 = getsize(head1); int size2 = getsize(head2); // Add same size lists if (size1 == size2) { addsamesize(head1, head2); } else { // First list should always be larger than second list. // If not, swap pointers if (size1 < size2) { node temp = head1; head1 = head2; head2 = temp; } int diff = Math.abs(size1 - size2); // move diff. number of nodes in first list node temp = head1; while (diff-- >= 0) { cur = temp; temp = temp.next; } // get addition of same size lists addsamesize(cur, head2); // get addition of remaining first list and carry propogatecarry(head1); } // if some carry is still there, add a new node to // the front of the result list. e.g. 999 and 87 if (carry > 0) push(carry, 3); } // Driver program to test above functions public static void main(String args[]) { linkedlistATN list = new linkedlistATN(); list.head1 = null; list.head2 = null; list.result = null; list.carry = 0; int arr1[] = { 9, 9, 9 }; int arr2[] = { 1, 8 }; // Create first list as 9->9->9 for (int i = arr1.length - 1; i >= 0; --i) list.push(arr1[i], 1); // Create second list as 1->8 for (int i = arr2.length - 1; i >= 0; --i) list.push(arr2[i], 2); list.addlists(); list.printlist(list.result); }} // This code is contributed by Rishabh Mahrsee
// A C# recursive program to add two linked listsusing System; public class linkedlistATN{ class node{ public int val; public node next; public node(int val) { this.val = val; }} // Function to print linked listvoid printlist(node head){ while (head != null) { Console.Write(head.val + " "); head = head.next; }} node head1, head2, result;int carry; // A utility function to push a// value to linked listvoid push(int val, int list){ node newnode = new node(val); if (list == 1) { newnode.next = head1; head1 = newnode; } else if (list == 2) { newnode.next = head2; head2 = newnode; } else { newnode.next = result; result = newnode; } } // Adds two linked lists of same size represented by// head1 and head2 and returns head of the resultant// linked list. Carry is propagated while returning// from the recursionvoid addsamesize(node n, node m){ // Since the function assumes linked // lists are of same size, check any // of the two head pointers if (n == null) return; // Recursively add remaining nodes // and get the carry addsamesize(n.next, m.next); // Add digits of current nodes // and propagated carry int sum = n.val + m.val + carry; carry = sum / 10; sum = sum % 10; // Push this to result list push(sum, 3);} node cur; // This function is called after the smaller// list is added to the bigger lists's sublist// of same size. Once the right sublist is added,// the carry must be added to the left side of// larger list to get the final result.void propogatecarry(node head1){ // If diff. number of nodes are // not traversed, add carry if (head1 != cur) { propogatecarry(head1.next); int sum = carry + head1.val; carry = sum / 10; sum %= 10; // Add this node to the front // of the result push(sum, 3); }} int getsize(node head){ int count = 0; while (head != null) { count++; head = head.next; } return count;} // The main function that adds two linked// lists represented by head1 and head2.// The sum of two lists is stored in a// list referred by resultvoid addlists(){ // First list is empty if (head1 == null) { result = head2; return; } // Second list is empty if (head2 == null) { result = head1; return; } int size1 = getsize(head1); int size2 = getsize(head2); // Add same size lists if (size1 == size2) { addsamesize(head1, head2); } else { // First list should always be // larger than second list. // If not, swap pointers if (size1 < size2) { node temp = head1; head1 = head2; head2 = temp; } int diff = Math.Abs(size1 - size2); // Move diff. number of nodes in // first list node tmp = head1; while (diff-- >= 0) { cur = tmp; tmp = tmp.next; } // Get addition of same size lists addsamesize(cur, head2); // Get addition of remaining // first list and carry propogatecarry(head1); } // If some carry is still there, // add a new node to the front of // the result list. e.g. 999 and 87 if (carry > 0) push(carry, 3);} // Driver codepublic static void Main(string []args){ linkedlistATN list = new linkedlistATN(); list.head1 = null; list.head2 = null; list.result = null; list.carry = 0; int []arr1 = { 9, 9, 9 }; int []arr2 = { 1, 8 }; // Create first list as 9->9->9 for(int i = arr1.Length - 1; i >= 0; --i) list.push(arr1[i], 1); // Create second list as 1->8 for(int i = arr2.Length - 1; i >= 0; --i) list.push(arr2[i], 2); list.addlists(); list.printlist(list.result);}} // This code is contributed by rutvik_56
<script>// A javascript recursive program to add two linked lists class node { constructor(val) { this.val = val; this.next = null; } } // Function to print linked list function printlist( head) { while (head != null) { document.write(head.val + " "); head = head.next; } } var head1, head2, result; var carry; /* A utility function to push a value to linked list */ function push(val , list) { var newnode = new node(val); if (list == 1) { newnode.next = head1; head1 = newnode; } else if (list == 2) { newnode.next = head2; head2 = newnode; } else { newnode.next = result; result = newnode; } } // Adds two linked lists of same size represented by // head1 and head2 and returns head of the resultant // linked list. Carry is propagated while returning // from the recursion function addsamesize( n, m) { // Since the function assumes linked lists are of // same size, check any of the two head pointers if (n == null) return; // Recursively add remaining nodes and get the carry addsamesize(n.next, m.next); // add digits of current nodes and propagated carry var sum = n.val + m.val + carry; carry = parseInt(sum / 10); sum = sum % 10; // Push this to result list push(sum, 3); } var cur; // This function is called after the smaller list is // added to the bigger lists's sublist of same size. // Once the right sublist is added, the carry must be // added to the left side of larger list to get the // final result. function propogatecarry( head1) { // If diff. number of nodes are not traversed, add carry if (head1 != cur) { propogatecarry(head1.next); var sum = carry + head1.val; carry = parseInt(sum / 10); sum %= 10; // add this node to the front of the result push(sum, 3); } } function getsize( head) { var count = 0; while (head != null) { count++; head = head.next; } return count; } // The main function that adds two linked lists // represented by head1 and head2. The sum of two // lists is stored in a list referred by result function addlists() { // first list is empty if (head1 == null) { result = head2; return; } // first list is empty if (head2 == null) { result = head1; return; } var size1 = getsize(head1); var size2 = getsize(head2); // Add same size lists if (size1 == size2) { addsamesize(head1, head2); } else { // First list should always be larger than second list. // If not, swap pointers if (size1 < size2) { var temp = head1; head1 = head2; head2 = temp; } var diff = Math.abs(size1 - size2); // move diff. number of nodes in first list var temp = head1; while (diff-- >= 0) { cur = temp; temp = temp.next; } // get addition of same size lists addsamesize(cur, head2); // get addition of remaining first list and carry propogatecarry(head1); } // if some carry is still there, add a new node to // the front of the result list. e.g. 999 and 87 if (carry > 0) push(carry, 3); } // Driver program to test above functions head1 = null; head2 = null; result = null; carry = 0; var arr1 = [ 9, 9, 9 ]; var arr2 = [ 1, 8 ]; // Create first list as 9->9->9 for (i = arr1.length - 1; i >= 0; --i) push(arr1[i], 1); // Create second list as 1->8 for (i = arr2.length - 1; i >= 0; --i) push(arr2[i], 2); addlists(); printlist(result); // This code is contributed by todaysgaurav</script>
1 0 1 7
Time Complexity: O(m+n) where m and n are the sizes of given two linked lists.
Space Complexity: O(m+n) for call stack
Iterative Approach:
This implementation does not have any recursion call overhead, which means it is an iterative solution.
Since we need to start adding numbers from the last of the two linked lists. So, here we will use the stack data structure to implement this.
We will firstly make two stacks from the given two linked lists.
Then, we will run a loop till both the stack become empty.
in every iteration, we keep the track of the carry.
In the end, if carry>0, that means we need extra node at the start of the resultant list to accommodate this carry.
C++
Java
Python3
C#
Javascript
// C++ Iterative program to add two linked lists #include <bits/stdc++.h>using namespace std; // A linked List Node class Node { public: int data; Node* next; }; // to push a new node to linked listvoid push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node[(sizeof(Node))]; /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } // to add two new numbersNode* addTwoNumList(Node* l1, Node* l2) { stack<int> s1,s2; while(l1!=NULL){ s1.push(l1->data); l1=l1->next; } while(l2!=NULL){ s2.push(l2->data); l2=l2->next; } int carry=0; Node* result=NULL; while(s1.empty()==false || s2.empty()==false){ int a=0,b=0; if(s1.empty()==false){ a=s1.top();s1.pop(); } if(s2.empty()==false){ b=s2.top();s2.pop(); } int total=a+b+carry; Node* temp=new Node(); temp->data=total%10; carry=total/10; if(result==NULL){ result=temp; }else{ temp->next=result; result=temp; } } if(carry!=0){ Node* temp=new Node(); temp->data=carry; temp->next=result; result=temp; } return result;} // to print a linked listvoid printList(Node *node) { while (node != NULL) { cout<<node->data<<" "; node = node->next; } cout<<endl; } // Driver Codeint main() { Node *head1 = NULL, *head2 = NULL; int arr1[] = {5, 6, 7}; int arr2[] = {1, 8}; int size1 = sizeof(arr1) / sizeof(arr1[0]); int size2 = sizeof(arr2) / sizeof(arr2[0]); // Create first list as 5->6->7 int i; for (i = size1-1; i >= 0; --i) push(&head1, arr1[i]); // Create second list as 1->8 for (i = size2-1; i >= 0; --i) push(&head2, arr2[i]); Node* result=addTwoNumList(head1, head2); printList(result); return 0; }
// Java Iterative program to add// two linked lists import java.io.*;import java.util.*; class GFG{ static class Node{ int data; Node next; public Node(int data) { this.data = data; }} static Node l1, l2, result; // To push a new node to linked listpublic static void push(int new_data){ // Allocate node Node new_node = new Node(0); // Put in the data new_node.data = new_data; // Link the old list off the new node new_node.next = l1; // Move the head to point to the new node l1 = new_node;} public static void push1(int new_data){ // Allocate node Node new_node = new Node(0); // Put in the data new_node.data = new_data; // Link the old list off the new node new_node.next = l2; // Move the head to point to // the new node l2 = new_node;} // To add two new numberspublic static Node addTwoNumbers(){ Stack<Integer> stack1 = new Stack<>(); Stack<Integer> stack2 = new Stack<>(); while (l1 != null) { stack1.add(l1.data); l1 = l1.next; } while (l2 != null) { stack2.add(l2.data); l2 = l2.next; } int carry = 0; Node result = null; while (!stack1.isEmpty() || !stack2.isEmpty()) { int a = 0, b = 0; if (!stack1.isEmpty()) { a = stack1.pop(); } if (!stack2.isEmpty()) { b = stack2.pop(); } int total = a + b + carry; Node temp = new Node(total % 10); carry = total / 10; if (result == null) { result = temp; } else { temp.next = result; result = temp; } } if (carry != 0) { Node temp = new Node(carry); temp.next = result; result = temp; } return result;} // To print a linked listpublic static void printList(){ while (result != null) { System.out.print(result.data + " "); result = result.next; } System.out.println();} // Driver codepublic static void main(String[] args){ int arr1[] = { 5, 6, 7 }; int arr2[] = { 1, 8 }; int size1 = 3; int size2 = 2; // Create first list as 5->6->7 int i; for(i = size1 - 1; i >= 0; --i) push(arr1[i]); // Create second list as 1->8 for(i = size2 - 1; i >= 0; --i) push1(arr2[i]); result = addTwoNumbers(); printList();}} // This code is contributed by RohitOberoi
# Python Iterative program to add# two linked lists class Node: def __init__(self,val): self.data = val self.next = None l1, l2, result = None,None,0 # To push a new node to linked listdef push(new_data): global l1 # Allocate node new_node = Node(0) # Put in the data new_node.data = new_data # Link the old list off the new node new_node.next = l1 # Move the head to point to the new node l1 = new_node def push1(new_data): global l2 # Allocate node new_node = Node(0) # Put in the data new_node.data = new_data # Link the old list off the new node new_node.next = l2 # Move the head to point to # the new node l2 = new_node # To add two new numbersdef addTwoNumbers(): global l1,l2,result stack1 = [] stack2 = [] while (l1 != None): stack1.append(l1.data) l1 = l1.next while (l2 != None): stack2.append(l2.data) l2 = l2.next carry = 0 result = None while (len(stack1) != 0 or len(stack2) != 0): a,b = 0,0 if (len(stack1) != 0): a = stack1.pop() if (len(stack2) != 0): b = stack2.pop() total = a + b + carry temp = Node(total % 10) carry = total // 10 if (result == None): result = temp else: temp.next = result result = temp if (carry != 0): temp = Node(carry) temp.next = result result = temp return result # To print a linked listdef printList(): global result while (result != None): print(result.data ,end = " ") result = result.next # Driver code arr1 = [ 5, 6, 7 ]arr2 = [ 1, 8 ] size1 = 3size2 = 2 # Create first list as 5->6->7 for i in range(size1-1,-1,-1): push(arr1[i]) # Create second list as 1->8for i in range(size2-1,-1,-1): push1(arr2[i]) result = addTwoNumbers() printList() # This code is contributed by shinjanpatra
// C# Iterative program to add// two linked lists using System;using System.Collections; class GFG{ public class Node { public int data; public Node next; public Node(int data) { this.data = data; } } static Node l1, l2, result; // To push a new node to linked list public static void push(int new_data) { // Allocate node Node new_node = new Node(0); // Put in the data new_node.data = new_data; // Link the old list off the new node new_node.next = l1; // Move the head to point to the new node l1 = new_node; } public static void push1(int new_data) { // Allocate node Node new_node = new Node(0); // Put in the data new_node.data = new_data; // Link the old list off the new node new_node.next = l2; // Move the head to point to // the new node l2 = new_node; } // To add two new numbers public static Node addTwoNumbers() { Stack stack1 = new Stack(); Stack stack2 = new Stack(); while (l1 != null) { stack1.Push(l1.data); l1 = l1.next; } while (l2 != null) { stack2.Push(l2.data); l2 = l2.next; } int carry = 0; Node result = null; while (stack1.Count != 0 || stack2.Count != 0) { int a = 0, b = 0; if (stack1.Count != 0) { a = (int)stack1.Pop(); } if (stack2.Count != 0) { b = (int)stack2.Pop(); } int total = a + b + carry; Node temp = new Node(total % 10); carry = total / 10; if (result == null) { result = temp; } else { temp.next = result; result = temp; } } if (carry != 0) { Node temp = new Node(carry); temp.next = result; result = temp; } return result; } // To print a linked list public static void printList() { while (result != null) { Console.Write(result.data + " "); result = result.next; } Console.WriteLine(); } // Driver code public static void Main(string[] args) { int []arr1 = { 5, 6, 7 }; int []arr2 = { 1, 8 }; int size1 = 3; int size2 = 2; // Create first list as 5->6->7 int i; for(i = size1 - 1; i >= 0; --i) push(arr1[i]); // Create second list as 1->8 for(i = size2 - 1; i >= 0; --i) push1(arr2[i]); result = addTwoNumbers(); printList(); }} // This code is contributed by pratham76
<script>// javascript Iterative program to add// two linked lists class Node { constructor(val) { this.data = val; this.next = null; }} var l1, l2, result; // To push a new node to linked list function push(new_data) { // Allocate nodevar new_node = new Node(0); // Put in the data new_node.data = new_data; // Link the old list off the new node new_node.next = l1; // Move the head to point to the new node l1 = new_node; } function push1(new_data) { // Allocate nodevar new_node = new Node(0); // Put in the data new_node.data = new_data; // Link the old list off the new node new_node.next = l2; // Move the head to point to // the new node l2 = new_node; } // To add two new numbers function addTwoNumbers() { var stack1 = []; var stack2 = []; while (l1 != null) { stack1.push(l1.data); l1 = l1.next; } while (l2 != null) { stack2.push(l2.data); l2 = l2.next; } var carry = 0;var result = null; while (stack1.length != 0 || stack2.length != 0) { var a = 0, b = 0; if (stack1.length != 0) { a = stack1.pop(); } if (stack2.length != 0) { b = stack2.pop(); } var total = a + b + carry; var temp = new Node(total % 10); carry = parseInt(total / 10); if (result == null) { result = temp; } else { temp.next = result; result = temp; } } if (carry != 0) { var temp = new Node(carry); temp.next = result; result = temp; } return result; } // To print a linked list function printList() { while (result != null) { document.write(result.data + " "); result = result.next; } document.write(); } // Driver code var arr1 = [ 5, 6, 7 ]; var arr2 = [ 1, 8 ]; var size1 = 3; var size2 = 2; // Create first list as 5->6->7 var i; for (var i = size1 - 1; i >= 0; --i) push(arr1[i]); // Create second list as 1->8 for (i = size2 - 1; i >= 0; --i) push1(arr2[i]); result = addTwoNumbers(); printList(); // This code contributed by umadevi9616</script>
5 8 5
Time Complexity: O(nlogn)
Here, n is the number of elements in the larger list. Adding/removing elements in a stack is a O(log n) operation and we have to add/remove 3*n elements at max. thus our total time complexity becomes O(nlogn).
Auxiliary Space: O(n)
Extra space is used to store the elements of the list in the stack
Related Article: Add two numbers represented by linked lists | Set 1Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
rathbhupendra
manupathria
RohitOberoi
rutvik_56
pratham76
todaysgaurav
umadevi9616
khushboogoyal499
simmytarika5
kalrap615
shinjanpatra
abhijeet19403
technophpfij
Accolite
Amazon
Flipkart
large-numbers
Microsoft
Morgan Stanley
Snapdeal
Zoho
Arrays
Linked List
Zoho
Flipkart
Morgan Stanley
Accolite
Amazon
Microsoft
Snapdeal
Linked List
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Jul, 2022"
},
{
"code": null,
"e": 336,
"s": 52,
"text": "Given two numbers represented by two linked lists, write a function that returns the sum list. The sum list is linked list representation of the addition of two input numbers. It is not allowed to modify the lists. Also, not allowed to use explicit extra space (Hint: Use Recursion)."
},
{
"code": null,
"e": 346,
"s": 336,
"text": "Example :"
},
{
"code": null,
"e": 437,
"s": 346,
"text": "Input:\n First List: 5->6->3 \n Second List: 8->4->2 \nOutput\n Resultant list: 1->4->0->5"
},
{
"code": null,
"e": 819,
"s": 437,
"text": "We have discussed a solution here which is for linked lists where a least significant digit is the first node of lists and the most significant digit is the last node. In this problem, the most significant node is the first node and the least significant digit is the last node and we are not allowed to modify the lists. Recursion is used here to calculate sum from right to left."
},
{
"code": null,
"e": 1634,
"s": 819,
"text": "Following are the steps. 1) Calculate sizes of given two linked lists. 2) If sizes are same, then calculate sum using recursion. Hold all nodes in recursion call stack till the rightmost node, calculate the sum of rightmost nodes and forward carry to the left side. 3) If size is not same, then follow below steps: ....a) Calculate difference of sizes of two linked lists. Let the difference be diff ....b) Move diff nodes ahead in the bigger linked list. Now use step 2 to calculate the sum of the smaller list and right sub-list (of the same size) of a larger list. Also, store the carry of this sum. ....c) Calculate the sum of the carry (calculated in the previous step) with the remaining left sub-list of a larger list. Nodes of this sum are added at the beginning of the sum list obtained the previous step."
},
{
"code": null,
"e": 1676,
"s": 1634,
"text": "Below is a dry run of the above approach:"
},
{
"code": null,
"e": 1734,
"s": 1676,
"text": "Below image is the implementation of the above approach. "
},
{
"code": null,
"e": 1738,
"s": 1734,
"text": "C++"
},
{
"code": null,
"e": 1740,
"s": 1738,
"text": "C"
},
{
"code": null,
"e": 1745,
"s": 1740,
"text": "Java"
},
{
"code": null,
"e": 1748,
"s": 1745,
"text": "C#"
},
{
"code": null,
"e": 1759,
"s": 1748,
"text": "Javascript"
},
{
"code": "// A C++ recursive program to add two linked lists#include <bits/stdc++.h>using namespace std; // A linked List Nodeclass Node {public: int data; Node* next;}; typedef Node node; /* A utility function to inserta node at the beginning of linked list */void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = new Node[(sizeof(Node))]; /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* A utility function to print linked list */void printList(Node* node){ while (node != NULL) { cout << node->data << \" \"; node = node->next; } cout << endl;} // A utility function to swap two pointersvoid swapPointer(Node** a, Node** b){ node* t = *a; *a = *b; *b = t;} /* A utility function to get size of linked list */int getSize(Node* node){ int size = 0; while (node != NULL) { node = node->next; size++; } return size;} // Adds two linked lists of same size// represented by head1 and head2 and returns// head of the resultant linked list. Carry// is propagated while returning from the recursionnode* addSameSize(Node* head1, Node* head2, int* carry){ // Since the function assumes linked lists are of same // size, check any of the two head pointers if (head1 == NULL) return NULL; int sum; // Allocate memory for sum node of current two nodes Node* result = new Node[(sizeof(Node))]; // Recursively add remaining nodes and get the carry result->next = addSameSize(head1->next, head2->next, carry); // add digits of current nodes and propagated carry sum = head1->data + head2->data + *carry; *carry = sum / 10; sum = sum % 10; // Assign the sum to current node of resultant list result->data = sum; return result;} // This function is called after the// smaller list is added to the bigger// lists's sublist of same size. Once the// right sublist is added, the carry// must be added toe left side of larger// list to get the final result.void addCarryToRemaining(Node* head1, Node* cur, int* carry, Node** result){ int sum; // If diff. number of nodes are not traversed, add carry if (head1 != cur) { addCarryToRemaining(head1->next, cur, carry, result); sum = head1->data + *carry; *carry = sum / 10; sum %= 10; // add this node to the front of the result push(result, sum); }} // The main function that adds two linked lists// represented by head1 and head2. The sum of// two lists is stored in a list referred by resultvoid addList(Node* head1, Node* head2, Node** result){ Node* cur; // first list is empty if (head1 == NULL) { *result = head2; return; } // second list is empty else if (head2 == NULL) { *result = head1; return; } int size1 = getSize(head1); int size2 = getSize(head2); int carry = 0; // Add same size lists if (size1 == size2) *result = addSameSize(head1, head2, &carry); else { int diff = abs(size1 - size2); // First list should always be larger than second // list. If not, swap pointers if (size1 < size2) swapPointer(&head1, &head2); // move diff. number of nodes in first list for (cur = head1; diff--; cur = cur->next) ; // get addition of same size lists *result = addSameSize(cur, head2, &carry); // get addition of remaining first list and carry addCarryToRemaining(head1, cur, &carry, result); } // if some carry is still there, add a new node to the // front of the result list. e.g. 999 and 87 if (carry) push(result, carry);} // Driver codeint main(){ Node *head1 = NULL, *head2 = NULL, *result = NULL; int arr1[] = { 9, 9, 9 }; int arr2[] = { 1, 8 }; int size1 = sizeof(arr1) / sizeof(arr1[0]); int size2 = sizeof(arr2) / sizeof(arr2[0]); // Create first list as 9->9->9 int i; for (i = size1 - 1; i >= 0; --i) push(&head1, arr1[i]); // Create second list as 1->8 for (i = size2 - 1; i >= 0; --i) push(&head2, arr2[i]); addList(head1, head2, &result); printList(result); return 0;} // This code is contributed by rathbhupendra",
"e": 6200,
"s": 1759,
"text": null
},
{
"code": "// A C recursive program to add two linked lists #include <stdio.h>#include <stdlib.h> // A linked List Nodestruct Node { int data; struct Node* next;}; typedef struct Node node; /* A utility function to insert a node at the beginning of * linked list */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* A utility function to print linked list */void printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; } printf(\"n\");} // A utility function to swap two pointersvoid swapPointer(Node** a, Node** b){ node* t = *a; *a = *b; *b = t;} /* A utility function to get size of linked list */int getSize(struct Node* node){ int size = 0; while (node != NULL) { node = node->next; size++; } return size;} // Adds two linked lists of same// size represented by head1// and head2 and returns head of// the resultant linked list.// Carry is propagated while// returning from the recursionnode* addSameSize(Node* head1, Node* head2, int* carry){ // Since the function assumes // linked lists are of same // size, check any of the two // head pointers if (head1 == NULL) return NULL; int sum; // Allocate memory for sum // node of current two nodes Node* result = (Node*)malloc(sizeof(Node)); // Recursively add remaining nodes // and get the carry result->next = addSameSize(head1->next, head2->next, carry); // add digits of current nodes // and propagated carry sum = head1->data + head2->data + *carry; *carry = sum / 10; sum = sum % 10; // Assigne the sum to current // node of resultant list result->data = sum; return result;} // This function is called after// the smaller list is added// to the bigger lists's sublist// of same size. Once the// right sublist is added, the// carry must be added toe left// side of larger list to get// the final result.void addCarryToRemaining(Node* head1, Node* cur, int* carry, Node** result){ int sum; // If diff. number of nodes are // not traversed, add carry if (head1 != cur) { addCarryToRemaining(head1->next, cur, carry, result); sum = head1->data + *carry; *carry = sum / 10; sum %= 10; // add this node to the front of the result push(result, sum); }} // The main function that adds two// linked lists represented// by head1 and head2. The sum of// two lists is stored in a// list referred by resultvoid addList(Node* head1, Node* head2, Node** result){ Node* cur; // first list is empty if (head1 == NULL) { *result = head2; return; } // second list is empty else if (head2 == NULL) { *result = head1; return; } int size1 = getSize(head1); int size2 = getSize(head2); int carry = 0; // Add same size lists if (size1 == size2) *result = addSameSize(head1, head2, &carry); else { int diff = abs(size1 - size2); // First list should always be // larger than second // list. If not, swap pointers if (size1 < size2) swapPointer(&head1, &head2); // move diff. number of nodes in first list for (cur = head1; diff--; cur = cur->next) ; // get addition of same size lists *result = addSameSize(cur, head2, &carry); // get addition of remaining first list and carry addCarryToRemaining(head1, cur, &carry, result); } // if some carry is still there, add a new node to the // front of the result list. e.g. 999 and 87 if (carry) push(result, carry);} // Driver codeint main(){ Node *head1 = NULL, *head2 = NULL, *result = NULL; int arr1[] = { 9, 9, 9 }; int arr2[] = { 1, 8 }; int size1 = sizeof(arr1) / sizeof(arr1[0]); int size2 = sizeof(arr2) / sizeof(arr2[0]); // Create first list as 9->9->9 int i; for (i = size1 - 1; i >= 0; --i) push(&head1, arr1[i]); // Create second list as 1->8 for (i = size2 - 1; i >= 0; --i) push(&head2, arr2[i]); addList(head1, head2, &result); printList(result); return 0;}",
"e": 10884,
"s": 6200,
"text": null
},
{
"code": "// A Java recursive program to add two linked lists public class linkedlistATN{ class node { int val; node next; public node(int val) { this.val = val; } } // Function to print linked list void printlist(node head) { while (head != null) { System.out.print(head.val + \" \"); head = head.next; } } node head1, head2, result; int carry; /* A utility function to push a value to linked list */ void push(int val, int list) { node newnode = new node(val); if (list == 1) { newnode.next = head1; head1 = newnode; } else if (list == 2) { newnode.next = head2; head2 = newnode; } else { newnode.next = result; result = newnode; } } // Adds two linked lists of same size represented by // head1 and head2 and returns head of the resultant // linked list. Carry is propagated while returning // from the recursion void addsamesize(node n, node m) { // Since the function assumes linked lists are of // same size, check any of the two head pointers if (n == null) return; // Recursively add remaining nodes and get the carry addsamesize(n.next, m.next); // add digits of current nodes and propagated carry int sum = n.val + m.val + carry; carry = sum / 10; sum = sum % 10; // Push this to result list push(sum, 3); } node cur; // This function is called after the smaller list is // added to the bigger lists's sublist of same size. // Once the right sublist is added, the carry must be // added to the left side of larger list to get the // final result. void propogatecarry(node head1) { // If diff. number of nodes are not traversed, add carry if (head1 != cur) { propogatecarry(head1.next); int sum = carry + head1.val; carry = sum / 10; sum %= 10; // add this node to the front of the result push(sum, 3); } } int getsize(node head) { int count = 0; while (head != null) { count++; head = head.next; } return count; } // The main function that adds two linked lists // represented by head1 and head2. The sum of two // lists is stored in a list referred by result void addlists() { // first list is empty if (head1 == null) { result = head2; return; } // first list is empty if (head2 == null) { result = head1; return; } int size1 = getsize(head1); int size2 = getsize(head2); // Add same size lists if (size1 == size2) { addsamesize(head1, head2); } else { // First list should always be larger than second list. // If not, swap pointers if (size1 < size2) { node temp = head1; head1 = head2; head2 = temp; } int diff = Math.abs(size1 - size2); // move diff. number of nodes in first list node temp = head1; while (diff-- >= 0) { cur = temp; temp = temp.next; } // get addition of same size lists addsamesize(cur, head2); // get addition of remaining first list and carry propogatecarry(head1); } // if some carry is still there, add a new node to // the front of the result list. e.g. 999 and 87 if (carry > 0) push(carry, 3); } // Driver program to test above functions public static void main(String args[]) { linkedlistATN list = new linkedlistATN(); list.head1 = null; list.head2 = null; list.result = null; list.carry = 0; int arr1[] = { 9, 9, 9 }; int arr2[] = { 1, 8 }; // Create first list as 9->9->9 for (int i = arr1.length - 1; i >= 0; --i) list.push(arr1[i], 1); // Create second list as 1->8 for (int i = arr2.length - 1; i >= 0; --i) list.push(arr2[i], 2); list.addlists(); list.printlist(list.result); }} // This code is contributed by Rishabh Mahrsee",
"e": 15452,
"s": 10884,
"text": null
},
{
"code": "// A C# recursive program to add two linked listsusing System; public class linkedlistATN{ class node{ public int val; public node next; public node(int val) { this.val = val; }} // Function to print linked listvoid printlist(node head){ while (head != null) { Console.Write(head.val + \" \"); head = head.next; }} node head1, head2, result;int carry; // A utility function to push a// value to linked listvoid push(int val, int list){ node newnode = new node(val); if (list == 1) { newnode.next = head1; head1 = newnode; } else if (list == 2) { newnode.next = head2; head2 = newnode; } else { newnode.next = result; result = newnode; } } // Adds two linked lists of same size represented by// head1 and head2 and returns head of the resultant// linked list. Carry is propagated while returning// from the recursionvoid addsamesize(node n, node m){ // Since the function assumes linked // lists are of same size, check any // of the two head pointers if (n == null) return; // Recursively add remaining nodes // and get the carry addsamesize(n.next, m.next); // Add digits of current nodes // and propagated carry int sum = n.val + m.val + carry; carry = sum / 10; sum = sum % 10; // Push this to result list push(sum, 3);} node cur; // This function is called after the smaller// list is added to the bigger lists's sublist// of same size. Once the right sublist is added,// the carry must be added to the left side of// larger list to get the final result.void propogatecarry(node head1){ // If diff. number of nodes are // not traversed, add carry if (head1 != cur) { propogatecarry(head1.next); int sum = carry + head1.val; carry = sum / 10; sum %= 10; // Add this node to the front // of the result push(sum, 3); }} int getsize(node head){ int count = 0; while (head != null) { count++; head = head.next; } return count;} // The main function that adds two linked// lists represented by head1 and head2.// The sum of two lists is stored in a// list referred by resultvoid addlists(){ // First list is empty if (head1 == null) { result = head2; return; } // Second list is empty if (head2 == null) { result = head1; return; } int size1 = getsize(head1); int size2 = getsize(head2); // Add same size lists if (size1 == size2) { addsamesize(head1, head2); } else { // First list should always be // larger than second list. // If not, swap pointers if (size1 < size2) { node temp = head1; head1 = head2; head2 = temp; } int diff = Math.Abs(size1 - size2); // Move diff. number of nodes in // first list node tmp = head1; while (diff-- >= 0) { cur = tmp; tmp = tmp.next; } // Get addition of same size lists addsamesize(cur, head2); // Get addition of remaining // first list and carry propogatecarry(head1); } // If some carry is still there, // add a new node to the front of // the result list. e.g. 999 and 87 if (carry > 0) push(carry, 3);} // Driver codepublic static void Main(string []args){ linkedlistATN list = new linkedlistATN(); list.head1 = null; list.head2 = null; list.result = null; list.carry = 0; int []arr1 = { 9, 9, 9 }; int []arr2 = { 1, 8 }; // Create first list as 9->9->9 for(int i = arr1.Length - 1; i >= 0; --i) list.push(arr1[i], 1); // Create second list as 1->8 for(int i = arr2.Length - 1; i >= 0; --i) list.push(arr2[i], 2); list.addlists(); list.printlist(list.result);}} // This code is contributed by rutvik_56",
"e": 19488,
"s": 15452,
"text": null
},
{
"code": "<script>// A javascript recursive program to add two linked lists class node { constructor(val) { this.val = val; this.next = null; } } // Function to print linked list function printlist( head) { while (head != null) { document.write(head.val + \" \"); head = head.next; } } var head1, head2, result; var carry; /* A utility function to push a value to linked list */ function push(val , list) { var newnode = new node(val); if (list == 1) { newnode.next = head1; head1 = newnode; } else if (list == 2) { newnode.next = head2; head2 = newnode; } else { newnode.next = result; result = newnode; } } // Adds two linked lists of same size represented by // head1 and head2 and returns head of the resultant // linked list. Carry is propagated while returning // from the recursion function addsamesize( n, m) { // Since the function assumes linked lists are of // same size, check any of the two head pointers if (n == null) return; // Recursively add remaining nodes and get the carry addsamesize(n.next, m.next); // add digits of current nodes and propagated carry var sum = n.val + m.val + carry; carry = parseInt(sum / 10); sum = sum % 10; // Push this to result list push(sum, 3); } var cur; // This function is called after the smaller list is // added to the bigger lists's sublist of same size. // Once the right sublist is added, the carry must be // added to the left side of larger list to get the // final result. function propogatecarry( head1) { // If diff. number of nodes are not traversed, add carry if (head1 != cur) { propogatecarry(head1.next); var sum = carry + head1.val; carry = parseInt(sum / 10); sum %= 10; // add this node to the front of the result push(sum, 3); } } function getsize( head) { var count = 0; while (head != null) { count++; head = head.next; } return count; } // The main function that adds two linked lists // represented by head1 and head2. The sum of two // lists is stored in a list referred by result function addlists() { // first list is empty if (head1 == null) { result = head2; return; } // first list is empty if (head2 == null) { result = head1; return; } var size1 = getsize(head1); var size2 = getsize(head2); // Add same size lists if (size1 == size2) { addsamesize(head1, head2); } else { // First list should always be larger than second list. // If not, swap pointers if (size1 < size2) { var temp = head1; head1 = head2; head2 = temp; } var diff = Math.abs(size1 - size2); // move diff. number of nodes in first list var temp = head1; while (diff-- >= 0) { cur = temp; temp = temp.next; } // get addition of same size lists addsamesize(cur, head2); // get addition of remaining first list and carry propogatecarry(head1); } // if some carry is still there, add a new node to // the front of the result list. e.g. 999 and 87 if (carry > 0) push(carry, 3); } // Driver program to test above functions head1 = null; head2 = null; result = null; carry = 0; var arr1 = [ 9, 9, 9 ]; var arr2 = [ 1, 8 ]; // Create first list as 9->9->9 for (i = arr1.length - 1; i >= 0; --i) push(arr1[i], 1); // Create second list as 1->8 for (i = arr2.length - 1; i >= 0; --i) push(arr2[i], 2); addlists(); printlist(result); // This code is contributed by todaysgaurav</script>",
"e": 23725,
"s": 19488,
"text": null
},
{
"code": null,
"e": 23733,
"s": 23725,
"text": "1 0 1 7"
},
{
"code": null,
"e": 23812,
"s": 23733,
"text": "Time Complexity: O(m+n) where m and n are the sizes of given two linked lists."
},
{
"code": null,
"e": 23852,
"s": 23812,
"text": "Space Complexity: O(m+n) for call stack"
},
{
"code": null,
"e": 23872,
"s": 23852,
"text": "Iterative Approach:"
},
{
"code": null,
"e": 23976,
"s": 23872,
"text": "This implementation does not have any recursion call overhead, which means it is an iterative solution."
},
{
"code": null,
"e": 24118,
"s": 23976,
"text": "Since we need to start adding numbers from the last of the two linked lists. So, here we will use the stack data structure to implement this."
},
{
"code": null,
"e": 24183,
"s": 24118,
"text": "We will firstly make two stacks from the given two linked lists."
},
{
"code": null,
"e": 24242,
"s": 24183,
"text": "Then, we will run a loop till both the stack become empty."
},
{
"code": null,
"e": 24294,
"s": 24242,
"text": "in every iteration, we keep the track of the carry."
},
{
"code": null,
"e": 24410,
"s": 24294,
"text": "In the end, if carry>0, that means we need extra node at the start of the resultant list to accommodate this carry."
},
{
"code": null,
"e": 24414,
"s": 24410,
"text": "C++"
},
{
"code": null,
"e": 24419,
"s": 24414,
"text": "Java"
},
{
"code": null,
"e": 24427,
"s": 24419,
"text": "Python3"
},
{
"code": null,
"e": 24430,
"s": 24427,
"text": "C#"
},
{
"code": null,
"e": 24441,
"s": 24430,
"text": "Javascript"
},
{
"code": "// C++ Iterative program to add two linked lists #include <bits/stdc++.h>using namespace std; // A linked List Node class Node { public: int data; Node* next; }; // to push a new node to linked listvoid push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node[(sizeof(Node))]; /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } // to add two new numbersNode* addTwoNumList(Node* l1, Node* l2) { stack<int> s1,s2; while(l1!=NULL){ s1.push(l1->data); l1=l1->next; } while(l2!=NULL){ s2.push(l2->data); l2=l2->next; } int carry=0; Node* result=NULL; while(s1.empty()==false || s2.empty()==false){ int a=0,b=0; if(s1.empty()==false){ a=s1.top();s1.pop(); } if(s2.empty()==false){ b=s2.top();s2.pop(); } int total=a+b+carry; Node* temp=new Node(); temp->data=total%10; carry=total/10; if(result==NULL){ result=temp; }else{ temp->next=result; result=temp; } } if(carry!=0){ Node* temp=new Node(); temp->data=carry; temp->next=result; result=temp; } return result;} // to print a linked listvoid printList(Node *node) { while (node != NULL) { cout<<node->data<<\" \"; node = node->next; } cout<<endl; } // Driver Codeint main() { Node *head1 = NULL, *head2 = NULL; int arr1[] = {5, 6, 7}; int arr2[] = {1, 8}; int size1 = sizeof(arr1) / sizeof(arr1[0]); int size2 = sizeof(arr2) / sizeof(arr2[0]); // Create first list as 5->6->7 int i; for (i = size1-1; i >= 0; --i) push(&head1, arr1[i]); // Create second list as 1->8 for (i = size2-1; i >= 0; --i) push(&head2, arr2[i]); Node* result=addTwoNumList(head1, head2); printList(result); return 0; }",
"e": 26547,
"s": 24441,
"text": null
},
{
"code": "// Java Iterative program to add// two linked lists import java.io.*;import java.util.*; class GFG{ static class Node{ int data; Node next; public Node(int data) { this.data = data; }} static Node l1, l2, result; // To push a new node to linked listpublic static void push(int new_data){ // Allocate node Node new_node = new Node(0); // Put in the data new_node.data = new_data; // Link the old list off the new node new_node.next = l1; // Move the head to point to the new node l1 = new_node;} public static void push1(int new_data){ // Allocate node Node new_node = new Node(0); // Put in the data new_node.data = new_data; // Link the old list off the new node new_node.next = l2; // Move the head to point to // the new node l2 = new_node;} // To add two new numberspublic static Node addTwoNumbers(){ Stack<Integer> stack1 = new Stack<>(); Stack<Integer> stack2 = new Stack<>(); while (l1 != null) { stack1.add(l1.data); l1 = l1.next; } while (l2 != null) { stack2.add(l2.data); l2 = l2.next; } int carry = 0; Node result = null; while (!stack1.isEmpty() || !stack2.isEmpty()) { int a = 0, b = 0; if (!stack1.isEmpty()) { a = stack1.pop(); } if (!stack2.isEmpty()) { b = stack2.pop(); } int total = a + b + carry; Node temp = new Node(total % 10); carry = total / 10; if (result == null) { result = temp; } else { temp.next = result; result = temp; } } if (carry != 0) { Node temp = new Node(carry); temp.next = result; result = temp; } return result;} // To print a linked listpublic static void printList(){ while (result != null) { System.out.print(result.data + \" \"); result = result.next; } System.out.println();} // Driver codepublic static void main(String[] args){ int arr1[] = { 5, 6, 7 }; int arr2[] = { 1, 8 }; int size1 = 3; int size2 = 2; // Create first list as 5->6->7 int i; for(i = size1 - 1; i >= 0; --i) push(arr1[i]); // Create second list as 1->8 for(i = size2 - 1; i >= 0; --i) push1(arr2[i]); result = addTwoNumbers(); printList();}} // This code is contributed by RohitOberoi",
"e": 29015,
"s": 26547,
"text": null
},
{
"code": "# Python Iterative program to add# two linked lists class Node: def __init__(self,val): self.data = val self.next = None l1, l2, result = None,None,0 # To push a new node to linked listdef push(new_data): global l1 # Allocate node new_node = Node(0) # Put in the data new_node.data = new_data # Link the old list off the new node new_node.next = l1 # Move the head to point to the new node l1 = new_node def push1(new_data): global l2 # Allocate node new_node = Node(0) # Put in the data new_node.data = new_data # Link the old list off the new node new_node.next = l2 # Move the head to point to # the new node l2 = new_node # To add two new numbersdef addTwoNumbers(): global l1,l2,result stack1 = [] stack2 = [] while (l1 != None): stack1.append(l1.data) l1 = l1.next while (l2 != None): stack2.append(l2.data) l2 = l2.next carry = 0 result = None while (len(stack1) != 0 or len(stack2) != 0): a,b = 0,0 if (len(stack1) != 0): a = stack1.pop() if (len(stack2) != 0): b = stack2.pop() total = a + b + carry temp = Node(total % 10) carry = total // 10 if (result == None): result = temp else: temp.next = result result = temp if (carry != 0): temp = Node(carry) temp.next = result result = temp return result # To print a linked listdef printList(): global result while (result != None): print(result.data ,end = \" \") result = result.next # Driver code arr1 = [ 5, 6, 7 ]arr2 = [ 1, 8 ] size1 = 3size2 = 2 # Create first list as 5->6->7 for i in range(size1-1,-1,-1): push(arr1[i]) # Create second list as 1->8for i in range(size2-1,-1,-1): push1(arr2[i]) result = addTwoNumbers() printList() # This code is contributed by shinjanpatra",
"e": 30988,
"s": 29015,
"text": null
},
{
"code": "// C# Iterative program to add// two linked lists using System;using System.Collections; class GFG{ public class Node { public int data; public Node next; public Node(int data) { this.data = data; } } static Node l1, l2, result; // To push a new node to linked list public static void push(int new_data) { // Allocate node Node new_node = new Node(0); // Put in the data new_node.data = new_data; // Link the old list off the new node new_node.next = l1; // Move the head to point to the new node l1 = new_node; } public static void push1(int new_data) { // Allocate node Node new_node = new Node(0); // Put in the data new_node.data = new_data; // Link the old list off the new node new_node.next = l2; // Move the head to point to // the new node l2 = new_node; } // To add two new numbers public static Node addTwoNumbers() { Stack stack1 = new Stack(); Stack stack2 = new Stack(); while (l1 != null) { stack1.Push(l1.data); l1 = l1.next; } while (l2 != null) { stack2.Push(l2.data); l2 = l2.next; } int carry = 0; Node result = null; while (stack1.Count != 0 || stack2.Count != 0) { int a = 0, b = 0; if (stack1.Count != 0) { a = (int)stack1.Pop(); } if (stack2.Count != 0) { b = (int)stack2.Pop(); } int total = a + b + carry; Node temp = new Node(total % 10); carry = total / 10; if (result == null) { result = temp; } else { temp.next = result; result = temp; } } if (carry != 0) { Node temp = new Node(carry); temp.next = result; result = temp; } return result; } // To print a linked list public static void printList() { while (result != null) { Console.Write(result.data + \" \"); result = result.next; } Console.WriteLine(); } // Driver code public static void Main(string[] args) { int []arr1 = { 5, 6, 7 }; int []arr2 = { 1, 8 }; int size1 = 3; int size2 = 2; // Create first list as 5->6->7 int i; for(i = size1 - 1; i >= 0; --i) push(arr1[i]); // Create second list as 1->8 for(i = size2 - 1; i >= 0; --i) push1(arr2[i]); result = addTwoNumbers(); printList(); }} // This code is contributed by pratham76",
"e": 33402,
"s": 30988,
"text": null
},
{
"code": "<script>// javascript Iterative program to add// two linked lists class Node { constructor(val) { this.data = val; this.next = null; }} var l1, l2, result; // To push a new node to linked list function push(new_data) { // Allocate nodevar new_node = new Node(0); // Put in the data new_node.data = new_data; // Link the old list off the new node new_node.next = l1; // Move the head to point to the new node l1 = new_node; } function push1(new_data) { // Allocate nodevar new_node = new Node(0); // Put in the data new_node.data = new_data; // Link the old list off the new node new_node.next = l2; // Move the head to point to // the new node l2 = new_node; } // To add two new numbers function addTwoNumbers() { var stack1 = []; var stack2 = []; while (l1 != null) { stack1.push(l1.data); l1 = l1.next; } while (l2 != null) { stack2.push(l2.data); l2 = l2.next; } var carry = 0;var result = null; while (stack1.length != 0 || stack2.length != 0) { var a = 0, b = 0; if (stack1.length != 0) { a = stack1.pop(); } if (stack2.length != 0) { b = stack2.pop(); } var total = a + b + carry; var temp = new Node(total % 10); carry = parseInt(total / 10); if (result == null) { result = temp; } else { temp.next = result; result = temp; } } if (carry != 0) { var temp = new Node(carry); temp.next = result; result = temp; } return result; } // To print a linked list function printList() { while (result != null) { document.write(result.data + \" \"); result = result.next; } document.write(); } // Driver code var arr1 = [ 5, 6, 7 ]; var arr2 = [ 1, 8 ]; var size1 = 3; var size2 = 2; // Create first list as 5->6->7 var i; for (var i = size1 - 1; i >= 0; --i) push(arr1[i]); // Create second list as 1->8 for (i = size2 - 1; i >= 0; --i) push1(arr2[i]); result = addTwoNumbers(); printList(); // This code contributed by umadevi9616</script>",
"e": 35923,
"s": 33402,
"text": null
},
{
"code": null,
"e": 35929,
"s": 35923,
"text": "5 8 5"
},
{
"code": null,
"e": 35955,
"s": 35929,
"text": "Time Complexity: O(nlogn)"
},
{
"code": null,
"e": 36166,
"s": 35955,
"text": "Here, n is the number of elements in the larger list. Adding/removing elements in a stack is a O(log n) operation and we have to add/remove 3*n elements at max. thus our total time complexity becomes O(nlogn)."
},
{
"code": null,
"e": 36188,
"s": 36166,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 36255,
"s": 36188,
"text": "Extra space is used to store the elements of the list in the stack"
},
{
"code": null,
"e": 36448,
"s": 36255,
"text": "Related Article: Add two numbers represented by linked lists | Set 1Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 36462,
"s": 36448,
"text": "rathbhupendra"
},
{
"code": null,
"e": 36474,
"s": 36462,
"text": "manupathria"
},
{
"code": null,
"e": 36486,
"s": 36474,
"text": "RohitOberoi"
},
{
"code": null,
"e": 36496,
"s": 36486,
"text": "rutvik_56"
},
{
"code": null,
"e": 36506,
"s": 36496,
"text": "pratham76"
},
{
"code": null,
"e": 36519,
"s": 36506,
"text": "todaysgaurav"
},
{
"code": null,
"e": 36531,
"s": 36519,
"text": "umadevi9616"
},
{
"code": null,
"e": 36548,
"s": 36531,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 36561,
"s": 36548,
"text": "simmytarika5"
},
{
"code": null,
"e": 36571,
"s": 36561,
"text": "kalrap615"
},
{
"code": null,
"e": 36584,
"s": 36571,
"text": "shinjanpatra"
},
{
"code": null,
"e": 36598,
"s": 36584,
"text": "abhijeet19403"
},
{
"code": null,
"e": 36611,
"s": 36598,
"text": "technophpfij"
},
{
"code": null,
"e": 36620,
"s": 36611,
"text": "Accolite"
},
{
"code": null,
"e": 36627,
"s": 36620,
"text": "Amazon"
},
{
"code": null,
"e": 36636,
"s": 36627,
"text": "Flipkart"
},
{
"code": null,
"e": 36650,
"s": 36636,
"text": "large-numbers"
},
{
"code": null,
"e": 36660,
"s": 36650,
"text": "Microsoft"
},
{
"code": null,
"e": 36675,
"s": 36660,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 36684,
"s": 36675,
"text": "Snapdeal"
},
{
"code": null,
"e": 36689,
"s": 36684,
"text": "Zoho"
},
{
"code": null,
"e": 36696,
"s": 36689,
"text": "Arrays"
},
{
"code": null,
"e": 36708,
"s": 36696,
"text": "Linked List"
},
{
"code": null,
"e": 36713,
"s": 36708,
"text": "Zoho"
},
{
"code": null,
"e": 36722,
"s": 36713,
"text": "Flipkart"
},
{
"code": null,
"e": 36737,
"s": 36722,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 36746,
"s": 36737,
"text": "Accolite"
},
{
"code": null,
"e": 36753,
"s": 36746,
"text": "Amazon"
},
{
"code": null,
"e": 36763,
"s": 36753,
"text": "Microsoft"
},
{
"code": null,
"e": 36772,
"s": 36763,
"text": "Snapdeal"
},
{
"code": null,
"e": 36784,
"s": 36772,
"text": "Linked List"
},
{
"code": null,
"e": 36791,
"s": 36784,
"text": "Arrays"
}
]
|
How to Detect Touch Event on Screen Programmatically in Android? | 23 Feb, 2021
Detecting a touch confirms that the screen is fully functional. Responding to touch is something that a developer deals with. As Android devices have a touch-based input, things are programmed upon application of touch. For explicitly calling methods within the application, a touch action must be recognized. Such methods can have special functions. Common applications that use such special functions are:
Games: Most of the games come with touch listeners, that invoke different functions upon different touch applications.Lock Screen: Screen Locks are generally touched movement-based, where a single tap doesn’t unlock the device. Rather, a pattern or a swipe has to be made by the user to unlock the device. Ex: Pattern-based locks, swipe locks.
Games: Most of the games come with touch listeners, that invoke different functions upon different touch applications.
Lock Screen: Screen Locks are generally touched movement-based, where a single tap doesn’t unlock the device. Rather, a pattern or a swipe has to be made by the user to unlock the device. Ex: Pattern-based locks, swipe locks.
Note that we are going to implement this project using the Kotlin language.
To check if there were touch movements on a screen in Android, we shall follow the following steps:
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language. There are no changes made to the activity_main.xml file.
Step 2: Working with the MainActivity.kt file
Finally, go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.os.Bundleimport android.view.MotionEventimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.core.view.MotionEventCompat class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Do Nothing } // create an override function onTouchEvent that takes // in the MotionEvent and returns a boolean value override fun onTouchEvent(event: MotionEvent): Boolean { return when (MotionEventCompat.getActionMasked(event)) { // Display a Toast whenever a movement is captured on the screen MotionEvent.ACTION_MOVE -> { Toast.makeText(applicationContext, "Action was MOVE", Toast.LENGTH_SHORT).show() true } else -> super.onTouchEvent(event) } }}
To check if there were touch movements in a specific view displayed on a screen in Android, we shall follow the following steps:
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
Go to the activity_main.xml file which represents the UI of the application, and create a LinearLayout, give it a dark background, and no other elements so that we can see the touch impressions. Below is the code for the activity_main.xml file.
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:id="@+id/main_view" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--View (Sub-Class) where OnTouchListener is implemented--> <LinearLayout android:id="@+id/view1" android:layout_width="300sp" android:layout_height="400sp" android:layout_centerInParent="true" android:background="@color/colorPrimaryDark" android:orientation="horizontal"> </LinearLayout> </RelativeLayout>
Step 3: Working with the MainActivity.kt file
Finally, 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.annotation.SuppressLintimport android.os.Bundleimport android.view.MotionEventimport android.view.Viewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.core.view.MotionEventCompat class MainActivity : AppCompatActivity() { @SuppressLint("ClickableViewAccessibility") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // View (Sub-Class) where onTouchEvent is implemented val v1 = findViewById<View>(R.id.view1) // OnTouchListener on the selected view v1.setOnTouchListener { v, event -> return@setOnTouchListener when (MotionEventCompat.getActionMasked(event)) { MotionEvent.ACTION_DOWN -> { // Make a Toast when movements captured on the sub-class Toast.makeText(applicationContext, "Move", Toast.LENGTH_SHORT).show() true } else -> false } } }}
To check if there were touch movements in multiple views displayed on a screen in Android, we shall follow the following steps:
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
Go to the activity_main.xml file which represents the UI of the application, and create a LinearLayout, give it a dark background, and no other elements so that we can see the touch impressions. Below is the code for the activity_main.xml file.
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:id="@+id/main_view" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--View (Sub-Class) where OnTouchListener is implemented--> <LinearLayout android:id="@+id/view1" android:layout_width="300sp" android:layout_height="400sp" android:layout_centerInParent="true" android:background="@color/colorPrimaryDark" android:orientation="horizontal"> </LinearLayout> </RelativeLayout>
Step 3: Working with the MainActivity.kt file
Finally, 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.annotation.SuppressLintimport android.os.Bundleimport android.view.MotionEventimport android.view.Viewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.core.view.MotionEventCompat class MainActivity : AppCompatActivity() { @SuppressLint("ClickableViewAccessibility") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // mainView is nothing but the parent activity_main layout // subView is a explicitly declared Linear // Layout and occupies a minor part of the screen val mainView = findViewById<View>(R.id.main_view) val subView = findViewById<View>(R.id.view1) // OnTouchListener on the Screen mainView.setOnTouchListener { v, event -> return@setOnTouchListener when (MotionEventCompat.getActionMasked (event)) { MotionEvent.ACTION_DOWN -> { if (isInside(subView, event)) { Toast.makeText(applicationContext, "Inside", Toast.LENGTH_SHORT).show() } if (!isInside(subView, event)) { Toast.makeText(applicationContext, "Outside", Toast.LENGTH_SHORT).show() } true } else -> false } } } // V shall be the subclass i.e. the subView declared in onCreate function // This functions confirms the dimensions of the view (subView in out program) private fun isInside(v: View, e: MotionEvent): Boolean { return !(e.x < 0 || e.y < 0 || e.x > v.measuredWidth || e.y > v.measuredHeight) }}
Android-Misc
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 436,
"s": 28,
"text": "Detecting a touch confirms that the screen is fully functional. Responding to touch is something that a developer deals with. As Android devices have a touch-based input, things are programmed upon application of touch. For explicitly calling methods within the application, a touch action must be recognized. Such methods can have special functions. Common applications that use such special functions are:"
},
{
"code": null,
"e": 780,
"s": 436,
"text": "Games: Most of the games come with touch listeners, that invoke different functions upon different touch applications.Lock Screen: Screen Locks are generally touched movement-based, where a single tap doesn’t unlock the device. Rather, a pattern or a swipe has to be made by the user to unlock the device. Ex: Pattern-based locks, swipe locks."
},
{
"code": null,
"e": 899,
"s": 780,
"text": "Games: Most of the games come with touch listeners, that invoke different functions upon different touch applications."
},
{
"code": null,
"e": 1125,
"s": 899,
"text": "Lock Screen: Screen Locks are generally touched movement-based, where a single tap doesn’t unlock the device. Rather, a pattern or a swipe has to be made by the user to unlock the device. Ex: Pattern-based locks, swipe locks."
},
{
"code": null,
"e": 1201,
"s": 1125,
"text": "Note that we are going to implement this project using the Kotlin language."
},
{
"code": null,
"e": 1301,
"s": 1201,
"text": "To check if there were touch movements on a screen in Android, we shall follow the following steps:"
},
{
"code": null,
"e": 1330,
"s": 1301,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 1552,
"s": 1330,
"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. There are no changes made to the activity_main.xml file. "
},
{
"code": null,
"e": 1598,
"s": 1552,
"text": "Step 2: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 1794,
"s": 1598,
"text": "Finally, 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": 1801,
"s": 1794,
"text": "Kotlin"
},
{
"code": "import android.os.Bundleimport android.view.MotionEventimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.core.view.MotionEventCompat class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Do Nothing } // create an override function onTouchEvent that takes // in the MotionEvent and returns a boolean value override fun onTouchEvent(event: MotionEvent): Boolean { return when (MotionEventCompat.getActionMasked(event)) { // Display a Toast whenever a movement is captured on the screen MotionEvent.ACTION_MOVE -> { Toast.makeText(applicationContext, \"Action was MOVE\", Toast.LENGTH_SHORT).show() true } else -> super.onTouchEvent(event) } }}",
"e": 2736,
"s": 1801,
"text": null
},
{
"code": null,
"e": 2865,
"s": 2736,
"text": "To check if there were touch movements in a specific view displayed on a screen in Android, we shall follow the following steps:"
},
{
"code": null,
"e": 2894,
"s": 2865,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 3058,
"s": 2894,
"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": 3106,
"s": 3058,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 3351,
"s": 3106,
"text": "Go to the activity_main.xml file which represents the UI of the application, and create a LinearLayout, give it a dark background, and no other elements so that we can see the touch impressions. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 3355,
"s": 3351,
"text": "XML"
},
{
"code": "<?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:id=\"@+id/main_view\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--View (Sub-Class) where OnTouchListener is implemented--> <LinearLayout android:id=\"@+id/view1\" android:layout_width=\"300sp\" android:layout_height=\"400sp\" android:layout_centerInParent=\"true\" android:background=\"@color/colorPrimaryDark\" android:orientation=\"horizontal\"> </LinearLayout> </RelativeLayout>",
"e": 4031,
"s": 3355,
"text": null
},
{
"code": null,
"e": 4077,
"s": 4031,
"text": "Step 3: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 4273,
"s": 4077,
"text": "Finally, 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": 4280,
"s": 4273,
"text": "Kotlin"
},
{
"code": "import android.annotation.SuppressLintimport android.os.Bundleimport android.view.MotionEventimport android.view.Viewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.core.view.MotionEventCompat class MainActivity : AppCompatActivity() { @SuppressLint(\"ClickableViewAccessibility\") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // View (Sub-Class) where onTouchEvent is implemented val v1 = findViewById<View>(R.id.view1) // OnTouchListener on the selected view v1.setOnTouchListener { v, event -> return@setOnTouchListener when (MotionEventCompat.getActionMasked(event)) { MotionEvent.ACTION_DOWN -> { // Make a Toast when movements captured on the sub-class Toast.makeText(applicationContext, \"Move\", Toast.LENGTH_SHORT).show() true } else -> false } } }}",
"e": 5350,
"s": 4280,
"text": null
},
{
"code": null,
"e": 5478,
"s": 5350,
"text": "To check if there were touch movements in multiple views displayed on a screen in Android, we shall follow the following steps:"
},
{
"code": null,
"e": 5507,
"s": 5478,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 5671,
"s": 5507,
"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": 5719,
"s": 5671,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 5964,
"s": 5719,
"text": "Go to the activity_main.xml file which represents the UI of the application, and create a LinearLayout, give it a dark background, and no other elements so that we can see the touch impressions. Below is the code for the activity_main.xml file."
},
{
"code": null,
"e": 5968,
"s": 5964,
"text": "XML"
},
{
"code": "<?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:id=\"@+id/main_view\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--View (Sub-Class) where OnTouchListener is implemented--> <LinearLayout android:id=\"@+id/view1\" android:layout_width=\"300sp\" android:layout_height=\"400sp\" android:layout_centerInParent=\"true\" android:background=\"@color/colorPrimaryDark\" android:orientation=\"horizontal\"> </LinearLayout> </RelativeLayout>",
"e": 6644,
"s": 5968,
"text": null
},
{
"code": null,
"e": 6690,
"s": 6644,
"text": "Step 3: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 6886,
"s": 6690,
"text": "Finally, 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": 6893,
"s": 6886,
"text": "Kotlin"
},
{
"code": "import android.annotation.SuppressLintimport android.os.Bundleimport android.view.MotionEventimport android.view.Viewimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivityimport androidx.core.view.MotionEventCompat class MainActivity : AppCompatActivity() { @SuppressLint(\"ClickableViewAccessibility\") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // mainView is nothing but the parent activity_main layout // subView is a explicitly declared Linear // Layout and occupies a minor part of the screen val mainView = findViewById<View>(R.id.main_view) val subView = findViewById<View>(R.id.view1) // OnTouchListener on the Screen mainView.setOnTouchListener { v, event -> return@setOnTouchListener when (MotionEventCompat.getActionMasked (event)) { MotionEvent.ACTION_DOWN -> { if (isInside(subView, event)) { Toast.makeText(applicationContext, \"Inside\", Toast.LENGTH_SHORT).show() } if (!isInside(subView, event)) { Toast.makeText(applicationContext, \"Outside\", Toast.LENGTH_SHORT).show() } true } else -> false } } } // V shall be the subclass i.e. the subView declared in onCreate function // This functions confirms the dimensions of the view (subView in out program) private fun isInside(v: View, e: MotionEvent): Boolean { return !(e.x < 0 || e.y < 0 || e.x > v.measuredWidth || e.y > v.measuredHeight) }}",
"e": 8648,
"s": 6893,
"text": null
},
{
"code": null,
"e": 8661,
"s": 8648,
"text": "Android-Misc"
},
{
"code": null,
"e": 8669,
"s": 8661,
"text": "Android"
},
{
"code": null,
"e": 8676,
"s": 8669,
"text": "Kotlin"
},
{
"code": null,
"e": 8684,
"s": 8676,
"text": "Android"
}
]
|
LinkedBlockingQueue Class in Java | 21 Oct, 2020
The LinkedBlockingQueue is an optionally-bounded blocking queue based on linked nodes. It means that the LinkedBlockingQueue can be bounded, if its capacity is given, else the LinkedBlockingQueue will be unbounded. The capacity can be given as a parameter to the constructor of LinkedBlockingQueue. This queue orders elements FIFO (first-in-first-out). It means that the head of this queue is the oldest element of the elements present in this queue. The tail of this queue is the newest element of the elements of this queue. The newly inserted elements are always inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. Linked queues typically have higher throughput than array-based queues but less predictable performance in most concurrent applications.
The capacity, if unspecified, is equal to Integer.MAX_VALUE. Linked nodes are dynamically created upon each insertion, till the capacity of the queue is not filled. This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. It is a member of the Java Collections Framework.
The Hierarchy of LinkedBlockingQueue
LinkedBlockingQueue<E> extends AbstractQueue<E> and implements Serializable, Iterable<E>, Collection<E>, BlockingQueue<E>, Queue<E> interfaces.
Declaration:
public class LinkedBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E>, Serializable
E – type of elements held in this collection.
To construct a LinkedBlockingQueue, we need to import it from java.util.concurrent.LinkedBlockingQueue. Here, capacity is the size of the linked blocking queue.
1. LinkedBlockingQueue() : Creates a LinkedBlockingQueue with a capacity of Integer.MAX_VALUE.
LinkedBlockingQueue<E> lbq = new LinkedBlockingQueue<E>();
Example:
Java
// Java program to demonstrate// LinkedBlockingQueue() constructor import java.util.concurrent.LinkedBlockingQueue; public class LinkedBlockingQueueDemo { public static void main(String[] args) { // create object of LinkedBlockingQueue // using LinkedBlockingQueue() constructor LinkedBlockingQueue<Integer> lbq = new LinkedBlockingQueue<Integer>(); // add numbers lbq.add(1); lbq.add(2); lbq.add(3); lbq.add(4); lbq.add(5); // print queue System.out.println("LinkedBlockingQueue:" + lbq); }}
LinkedBlockingQueue:[1, 2, 3, 4, 5]
2. LinkedBlockingQueue(int capacity): Creates a LinkedBlockingQueue with the given (fixed) capacity.
LinkedBlockingQueue<E> lbq = new LinkedBlockingQueue(int capacity);
Example:
Java
// Java program to demonstrate// LinkedBlockingQueue(int initialCapacity) constructor import java.util.concurrent.LinkedBlockingQueue; public class GFG { public static void main(String[] args) { // define capacity of LinkedBlockingQueue int capacity = 15; // create object of LinkedBlockingQueue // using LinkedBlockingQueue(int initialCapacity) // constructor LinkedBlockingQueue<Integer> lbq = new LinkedBlockingQueue<Integer>(capacity); // add numbers lbq.add(1); lbq.add(2); lbq.add(3); // print queue System.out.println("LinkedBlockingQueue:" + lbq); }}
LinkedBlockingQueue:[1, 2, 3]
3. LinkedBlockingQueue(Collection<? extends E> c): Creates a LinkedBlockingQueue with a capacity of Integer.MAX_VALUE, initially containing the elements of the given collection, added in traversal order of the collection’s iterator.
LinkedBlockingQueue<E> lbq = new LinkedBlockingQueue(Collection<? extends E> c);
Example:
Java
// Java program to demonstrate// LinkedBlockingQueue(Collection c) constructor import java.util.concurrent.LinkedBlockingQueue;import java.util.*; public class GFG { public static void main(String[] args) { // Creating a Collection Vector<Integer> v = new Vector<Integer>(); v.addElement(1); v.addElement(2); v.addElement(3); v.addElement(4); v.addElement(5); // create object of LinkedBlockingQueue // using LinkedBlockingQueue(Collection c) // constructor LinkedBlockingQueue<Integer> lbq = new LinkedBlockingQueue<Integer>(v); // print queue System.out.println("LinkedBlockingQueue:" + lbq); }}
LinkedBlockingQueue:[1, 2, 3, 4, 5]
1. Adding Elements
The add(E e) method of LinkedBlockingQueue inserts element passed as a parameter to method at the tail of this LinkedBlockingQueue, if the queue is not full. If the queue is full, then this method will wait for space to become available and after space is available, it inserts the element to LinkedBlockingQueue.
Java
// Java Program to Demonstrate adding // elements to the LinkedBlockingQueue import java.util.concurrent.LinkedBlockingQueue; public class AddingElementsExample { public static void main(String[] args) { // define capacity of LinkedBlockingQueue int capacity = 15; // create object of LinkedBlockingQueue LinkedBlockingQueue<Integer> lbq = new LinkedBlockingQueue<Integer>(capacity); // add numbers lbq.add(1); lbq.add(2); lbq.add(3); // print queue System.out.println("LinkedBlockingQueue:" + lbq); }}
LinkedBlockingQueue:[1, 2, 3]
2. Removing Elements
The remove(Object obj) method of LinkedBlockingQueue removes only one instance of the given Object, passed as a parameter, from this LinkedBlockingQueue if it is present. It removes an element e such that obj.equals(e) and if this queue contains one or more instances of element e. This method returns true if this queue contained the element which is now removed from LinkedBlockingQueue.
Java
// Java Program to Demonstrate removing // elements from the LinkedBlockingQueue import java.util.concurrent.LinkedBlockingQueue; public class RemovingElementsExample { public static void main(String[] args) { // define capacity of LinkedBlockingQueue int capacity = 15; // create object of LinkedBlockingQueue LinkedBlockingQueue<Integer> lbq = new LinkedBlockingQueue<Integer>(capacity); // add numbers lbq.add(1); lbq.add(2); lbq.add(3); // print queue System.out.println("LinkedBlockingQueue:" + lbq); // remove all the elements lbq.clear(); // print queue System.out.println("LinkedBlockingQueue:" + lbq); }}
LinkedBlockingQueue:[1, 2, 3]
LinkedBlockingQueue:[]
3. Iterating
The iterator() method of LinkedBlockingQueue returns an iterator of the same elements, as this LinkedBlockingQueue, in a proper sequence. The elements returned from this method contains all the elements in order from first(head) to last(tail) of LinkedBlockingQueue. The returned iterator is weakly consistent.
Java
// Java Program Demonstrate iterating// over LinkedBlockingQueue import java.util.concurrent.LinkedBlockingQueue; import java.util.Iterator; public class IteratingExample { public static void main(String[] args) { // define capacity of LinkedBlockingQueue int capacityOfQueue = 7; // create object of LinkedBlockingQueue LinkedBlockingQueue<String> linkedQueue = new LinkedBlockingQueue<String>(capacityOfQueue); // Add element to LinkedBlockingQueue linkedQueue.add("John"); linkedQueue.add("Tom"); linkedQueue.add("Clark"); linkedQueue.add("Kat"); // create Iterator of linkedQueue using iterator() method Iterator<String> listOfNames = linkedQueue.iterator(); // print result System.out.println("list of names:"); while (listOfNames.hasNext()) System.out.println(listOfNames.next()); } }
list of names:
John
Tom
Clark
Kat
4. Accessing Elements
The peek() method of LinkedBlockingQueue returns the head of the LinkedBlockingQueue. It retrieves the value of the head of LinkedBlockingQueue but does not remove it. If the LinkedBlockingQueue is empty then this method returns null.
Java
// Java Program Demonstrate accessing// elements of LinkedBlockingQueue import java.util.concurrent.LinkedBlockingQueue; public class AccessingElementsExample { public static void main(String[] args) { // define capacity of LinkedBlockingQueue int capacityOfQueue = 7; // create object of LinkedBlockingQueue LinkedBlockingQueue<String> linkedQueue = new LinkedBlockingQueue<String>(capacityOfQueue); // Add element to LinkedBlockingQueue linkedQueue.add("John"); linkedQueue.add("Tom"); linkedQueue.add("Clark"); linkedQueue.add("Kat"); // find head of linkedQueue using peek() method String head = linkedQueue.peek(); // print result System.out.println("Queue is " + linkedQueue); // print head of queue System.out.println("Head of Queue is " + head); // removing one element linkedQueue.remove(); // again get head of queue head = linkedQueue.peek(); // print result System.out.println("\nRemoving one element from Queue\n"); System.out.println("Queue is " + linkedQueue); // print head of queue System.out.println("Head of Queue is " + head); } }
Queue is [John, Tom, Clark, Kat]
Head of Queue is John
Removing one element from Queue
Queue is [Tom, Clark, Kat]
Head of Queue is Tom
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/LinkedBlockingQueue.html
Ganeshchowdharysadanala
Java - util package
Java-Collections
Java-LinkedBlockingQueue
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Oct, 2020"
},
{
"code": null,
"e": 843,
"s": 28,
"text": "The LinkedBlockingQueue is an optionally-bounded blocking queue based on linked nodes. It means that the LinkedBlockingQueue can be bounded, if its capacity is given, else the LinkedBlockingQueue will be unbounded. The capacity can be given as a parameter to the constructor of LinkedBlockingQueue. This queue orders elements FIFO (first-in-first-out). It means that the head of this queue is the oldest element of the elements present in this queue. The tail of this queue is the newest element of the elements of this queue. The newly inserted elements are always inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. Linked queues typically have higher throughput than array-based queues but less predictable performance in most concurrent applications."
},
{
"code": null,
"e": 1168,
"s": 843,
"text": "The capacity, if unspecified, is equal to Integer.MAX_VALUE. Linked nodes are dynamically created upon each insertion, till the capacity of the queue is not filled. This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. It is a member of the Java Collections Framework. "
},
{
"code": null,
"e": 1206,
"s": 1168,
"text": "The Hierarchy of LinkedBlockingQueue "
},
{
"code": null,
"e": 1350,
"s": 1206,
"text": "LinkedBlockingQueue<E> extends AbstractQueue<E> and implements Serializable, Iterable<E>, Collection<E>, BlockingQueue<E>, Queue<E> interfaces."
},
{
"code": null,
"e": 1364,
"s": 1350,
"text": "Declaration: "
},
{
"code": null,
"e": 1468,
"s": 1364,
"text": "public class LinkedBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E>, Serializable "
},
{
"code": null,
"e": 1514,
"s": 1468,
"text": "E – type of elements held in this collection."
},
{
"code": null,
"e": 1675,
"s": 1514,
"text": "To construct a LinkedBlockingQueue, we need to import it from java.util.concurrent.LinkedBlockingQueue. Here, capacity is the size of the linked blocking queue."
},
{
"code": null,
"e": 1770,
"s": 1675,
"text": "1. LinkedBlockingQueue() : Creates a LinkedBlockingQueue with a capacity of Integer.MAX_VALUE."
},
{
"code": null,
"e": 1829,
"s": 1770,
"text": "LinkedBlockingQueue<E> lbq = new LinkedBlockingQueue<E>();"
},
{
"code": null,
"e": 1838,
"s": 1829,
"text": "Example:"
},
{
"code": null,
"e": 1843,
"s": 1838,
"text": "Java"
},
{
"code": "// Java program to demonstrate// LinkedBlockingQueue() constructor import java.util.concurrent.LinkedBlockingQueue; public class LinkedBlockingQueueDemo { public static void main(String[] args) { // create object of LinkedBlockingQueue // using LinkedBlockingQueue() constructor LinkedBlockingQueue<Integer> lbq = new LinkedBlockingQueue<Integer>(); // add numbers lbq.add(1); lbq.add(2); lbq.add(3); lbq.add(4); lbq.add(5); // print queue System.out.println(\"LinkedBlockingQueue:\" + lbq); }}",
"e": 2444,
"s": 1843,
"text": null
},
{
"code": null,
"e": 2480,
"s": 2444,
"text": "LinkedBlockingQueue:[1, 2, 3, 4, 5]"
},
{
"code": null,
"e": 2582,
"s": 2480,
"text": "2. LinkedBlockingQueue(int capacity): Creates a LinkedBlockingQueue with the given (fixed) capacity."
},
{
"code": null,
"e": 2651,
"s": 2582,
"text": "LinkedBlockingQueue<E> lbq = new LinkedBlockingQueue(int capacity);"
},
{
"code": null,
"e": 2660,
"s": 2651,
"text": "Example:"
},
{
"code": null,
"e": 2665,
"s": 2660,
"text": "Java"
},
{
"code": "// Java program to demonstrate// LinkedBlockingQueue(int initialCapacity) constructor import java.util.concurrent.LinkedBlockingQueue; public class GFG { public static void main(String[] args) { // define capacity of LinkedBlockingQueue int capacity = 15; // create object of LinkedBlockingQueue // using LinkedBlockingQueue(int initialCapacity) // constructor LinkedBlockingQueue<Integer> lbq = new LinkedBlockingQueue<Integer>(capacity); // add numbers lbq.add(1); lbq.add(2); lbq.add(3); // print queue System.out.println(\"LinkedBlockingQueue:\" + lbq); }}",
"e": 3339,
"s": 2665,
"text": null
},
{
"code": null,
"e": 3369,
"s": 3339,
"text": "LinkedBlockingQueue:[1, 2, 3]"
},
{
"code": null,
"e": 3603,
"s": 3369,
"text": "3. LinkedBlockingQueue(Collection<? extends E> c): Creates a LinkedBlockingQueue with a capacity of Integer.MAX_VALUE, initially containing the elements of the given collection, added in traversal order of the collection’s iterator."
},
{
"code": null,
"e": 3685,
"s": 3603,
"text": "LinkedBlockingQueue<E> lbq = new LinkedBlockingQueue(Collection<? extends E> c);"
},
{
"code": null,
"e": 3694,
"s": 3685,
"text": "Example:"
},
{
"code": null,
"e": 3699,
"s": 3694,
"text": "Java"
},
{
"code": "// Java program to demonstrate// LinkedBlockingQueue(Collection c) constructor import java.util.concurrent.LinkedBlockingQueue;import java.util.*; public class GFG { public static void main(String[] args) { // Creating a Collection Vector<Integer> v = new Vector<Integer>(); v.addElement(1); v.addElement(2); v.addElement(3); v.addElement(4); v.addElement(5); // create object of LinkedBlockingQueue // using LinkedBlockingQueue(Collection c) // constructor LinkedBlockingQueue<Integer> lbq = new LinkedBlockingQueue<Integer>(v); // print queue System.out.println(\"LinkedBlockingQueue:\" + lbq); }}",
"e": 4418,
"s": 3699,
"text": null
},
{
"code": null,
"e": 4454,
"s": 4418,
"text": "LinkedBlockingQueue:[1, 2, 3, 4, 5]"
},
{
"code": null,
"e": 4473,
"s": 4454,
"text": "1. Adding Elements"
},
{
"code": null,
"e": 4787,
"s": 4473,
"text": "The add(E e) method of LinkedBlockingQueue inserts element passed as a parameter to method at the tail of this LinkedBlockingQueue, if the queue is not full. If the queue is full, then this method will wait for space to become available and after space is available, it inserts the element to LinkedBlockingQueue."
},
{
"code": null,
"e": 4792,
"s": 4787,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate adding // elements to the LinkedBlockingQueue import java.util.concurrent.LinkedBlockingQueue; public class AddingElementsExample { public static void main(String[] args) { // define capacity of LinkedBlockingQueue int capacity = 15; // create object of LinkedBlockingQueue LinkedBlockingQueue<Integer> lbq = new LinkedBlockingQueue<Integer>(capacity); // add numbers lbq.add(1); lbq.add(2); lbq.add(3); // print queue System.out.println(\"LinkedBlockingQueue:\" + lbq); }}",
"e": 5396,
"s": 4792,
"text": null
},
{
"code": null,
"e": 5426,
"s": 5396,
"text": "LinkedBlockingQueue:[1, 2, 3]"
},
{
"code": null,
"e": 5449,
"s": 5428,
"text": "2. Removing Elements"
},
{
"code": null,
"e": 5840,
"s": 5449,
"text": "The remove(Object obj) method of LinkedBlockingQueue removes only one instance of the given Object, passed as a parameter, from this LinkedBlockingQueue if it is present. It removes an element e such that obj.equals(e) and if this queue contains one or more instances of element e. This method returns true if this queue contained the element which is now removed from LinkedBlockingQueue. "
},
{
"code": null,
"e": 5845,
"s": 5840,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate removing // elements from the LinkedBlockingQueue import java.util.concurrent.LinkedBlockingQueue; public class RemovingElementsExample { public static void main(String[] args) { // define capacity of LinkedBlockingQueue int capacity = 15; // create object of LinkedBlockingQueue LinkedBlockingQueue<Integer> lbq = new LinkedBlockingQueue<Integer>(capacity); // add numbers lbq.add(1); lbq.add(2); lbq.add(3); // print queue System.out.println(\"LinkedBlockingQueue:\" + lbq); // remove all the elements lbq.clear(); // print queue System.out.println(\"LinkedBlockingQueue:\" + lbq); }}",
"e": 6592,
"s": 5845,
"text": null
},
{
"code": null,
"e": 6645,
"s": 6592,
"text": "LinkedBlockingQueue:[1, 2, 3]\nLinkedBlockingQueue:[]"
},
{
"code": null,
"e": 6661,
"s": 6647,
"text": "3. Iterating "
},
{
"code": null,
"e": 6972,
"s": 6661,
"text": "The iterator() method of LinkedBlockingQueue returns an iterator of the same elements, as this LinkedBlockingQueue, in a proper sequence. The elements returned from this method contains all the elements in order from first(head) to last(tail) of LinkedBlockingQueue. The returned iterator is weakly consistent."
},
{
"code": null,
"e": 6977,
"s": 6972,
"text": "Java"
},
{
"code": "// Java Program Demonstrate iterating// over LinkedBlockingQueue import java.util.concurrent.LinkedBlockingQueue; import java.util.Iterator; public class IteratingExample { public static void main(String[] args) { // define capacity of LinkedBlockingQueue int capacityOfQueue = 7; // create object of LinkedBlockingQueue LinkedBlockingQueue<String> linkedQueue = new LinkedBlockingQueue<String>(capacityOfQueue); // Add element to LinkedBlockingQueue linkedQueue.add(\"John\"); linkedQueue.add(\"Tom\"); linkedQueue.add(\"Clark\"); linkedQueue.add(\"Kat\"); // create Iterator of linkedQueue using iterator() method Iterator<String> listOfNames = linkedQueue.iterator(); // print result System.out.println(\"list of names:\"); while (listOfNames.hasNext()) System.out.println(listOfNames.next()); } } ",
"e": 7931,
"s": 6977,
"text": null
},
{
"code": null,
"e": 7965,
"s": 7931,
"text": "list of names:\nJohn\nTom\nClark\nKat"
},
{
"code": null,
"e": 7987,
"s": 7965,
"text": "4. Accessing Elements"
},
{
"code": null,
"e": 8222,
"s": 7987,
"text": "The peek() method of LinkedBlockingQueue returns the head of the LinkedBlockingQueue. It retrieves the value of the head of LinkedBlockingQueue but does not remove it. If the LinkedBlockingQueue is empty then this method returns null."
},
{
"code": null,
"e": 8227,
"s": 8222,
"text": "Java"
},
{
"code": "// Java Program Demonstrate accessing// elements of LinkedBlockingQueue import java.util.concurrent.LinkedBlockingQueue; public class AccessingElementsExample { public static void main(String[] args) { // define capacity of LinkedBlockingQueue int capacityOfQueue = 7; // create object of LinkedBlockingQueue LinkedBlockingQueue<String> linkedQueue = new LinkedBlockingQueue<String>(capacityOfQueue); // Add element to LinkedBlockingQueue linkedQueue.add(\"John\"); linkedQueue.add(\"Tom\"); linkedQueue.add(\"Clark\"); linkedQueue.add(\"Kat\"); // find head of linkedQueue using peek() method String head = linkedQueue.peek(); // print result System.out.println(\"Queue is \" + linkedQueue); // print head of queue System.out.println(\"Head of Queue is \" + head); // removing one element linkedQueue.remove(); // again get head of queue head = linkedQueue.peek(); // print result System.out.println(\"\\nRemoving one element from Queue\\n\"); System.out.println(\"Queue is \" + linkedQueue); // print head of queue System.out.println(\"Head of Queue is \" + head); } } ",
"e": 9517,
"s": 8227,
"text": null
},
{
"code": null,
"e": 9654,
"s": 9517,
"text": "Queue is [John, Tom, Clark, Kat]\nHead of Queue is John\n\nRemoving one element from Queue\n\nQueue is [Tom, Clark, Kat]\nHead of Queue is Tom"
},
{
"code": null,
"e": 9661,
"s": 9654,
"text": "METHOD"
},
{
"code": null,
"e": 9673,
"s": 9661,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 9680,
"s": 9673,
"text": "METHOD"
},
{
"code": null,
"e": 9692,
"s": 9680,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 9699,
"s": 9692,
"text": "METHOD"
},
{
"code": null,
"e": 9711,
"s": 9699,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 9718,
"s": 9711,
"text": "METHOD"
},
{
"code": null,
"e": 9730,
"s": 9718,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 9737,
"s": 9730,
"text": "METHOD"
},
{
"code": null,
"e": 9749,
"s": 9737,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 9756,
"s": 9749,
"text": "METHOD"
},
{
"code": null,
"e": 9768,
"s": 9756,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 9886,
"s": 9768,
"text": "Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/LinkedBlockingQueue.html"
},
{
"code": null,
"e": 9910,
"s": 9886,
"text": "Ganeshchowdharysadanala"
},
{
"code": null,
"e": 9930,
"s": 9910,
"text": "Java - util package"
},
{
"code": null,
"e": 9947,
"s": 9930,
"text": "Java-Collections"
},
{
"code": null,
"e": 9972,
"s": 9947,
"text": "Java-LinkedBlockingQueue"
},
{
"code": null,
"e": 9977,
"s": 9972,
"text": "Java"
},
{
"code": null,
"e": 9982,
"s": 9977,
"text": "Java"
},
{
"code": null,
"e": 9999,
"s": 9982,
"text": "Java-Collections"
}
]
|
Size of The Subarray With Maximum Sum | 09 Jun, 2022
An array is given, find length of the subarray having maximum sum.
Examples :
Input : a[] = {1, -2, 1, 1, -2, 1}
Output : Length of the subarray is 2
Explanation: Subarray with consecutive elements
and maximum sum will be {1, 1}. So length is 2
Input : ar[] = { -2, -3, 4, -1, -2, 1, 5, -3 }
Output : Length of the subarray is 5
Explanation: Subarray with consecutive elements
and maximum sum will be {4, -1, -2, 1, 5}.
This problem is mainly a variation of Largest Sum Contiguous Subarray Problem.The idea is to update starting index whenever sum ending here becomes less than 0.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print length of the largest// contiguous array sum#include<bits/stdc++.h>using namespace std; int maxSubArraySum(int a[], int size){ int max_so_far = INT_MIN, max_ending_here = 0, start =0, end = 0, s=0; for (int i=0; i< size; i++ ) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } return (end - start + 1);} /*Driver program to test maxSubArraySum*/int main(){ int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = sizeof(a)/sizeof(a[0]); cout << maxSubArraySum(a, n); return 0;}
// Java program to print length of the largest// contiguous array sumclass GFG { static int maxSubArraySum(int a[], int size) { int max_so_far = Integer.MIN_VALUE, max_ending_here = 0,start = 0, end = 0, s = 0; for (int i = 0; i < size; i++) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } return (end - start + 1); } // Driver code public static void main(String[] args) { int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; int n = a.length; System.out.println(maxSubArraySum(a, n)); }}
# Python3 program to print largest contiguous array sum from sys import maxsize # Function to find the maximum contiguous subarray# and print its starting and end indexdef maxSubArraySum(a,size): max_so_far = -maxsize - 1 max_ending_here = 0 start = 0 end = 0 s = 0 for i in range(0,size): max_ending_here += a[i] if max_so_far < max_ending_here: max_so_far = max_ending_here start = s end = i if max_ending_here < 0: max_ending_here = 0 s = i+1 return (end - start + 1) # Driver program to test maxSubArraySuma = [-2, -3, 4, -1, -2, 1, 5, -3]print(maxSubArraySum(a,len(a)))
// C# program to print length of the// largest contiguous array sumusing System; class GFG { // Function to find maximum subarray sum static int maxSubArraySum(int []a, int size) { int max_so_far = int.MinValue, max_ending_here = 0,start = 0, end = 0, s = 0; for (int i = 0; i < size; i++) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } return (end - start + 1); } // Driver code public static void Main(String[] args) { int []a = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = a.Length; Console.Write(maxSubArraySum(a, n)); }} // This code is contributed by parashar...
<?php// PHP program for Bresenham’s// Line Generation Assumptions : // 1) Line is drawn from// left to right.// 2) x1 < x2 and y1 < y2// 3) Slope of the line is// between 0 and 1.// We draw a line from lower// left to upper right. // function for line generationfunction bresenham($x1, $y1, $x2, $y2){$m_new = 2 * ($y2 - $y1);$slope_error_new = $m_new - ($x2 - $x1);for ($x = $x1, $y = $y1; $x <= $x2; $x++){ echo "(" ,$x , "," , $y, ")\n"; // Add slope to increment // angle formed $slope_error_new += $m_new; // Slope error reached limit, // time to increment y and // update slope error. if ($slope_error_new >= 0) { $y++; $slope_error_new -= 2 * ($x2 - $x1); }}} // Driver Code$x1 = 3; $y1 = 2; $x2 = 15; $y2 = 5;bresenham($x1, $y1, $x2, $y2); // This code is contributed by nitin mittal.?>
<script> // JavaScript program to print length// of the largest contiguous array sumfunction maxSubArraySum(a, size){ let max_so_far = Number.MIN_VALUE, max_ending_here = 0,start = 0, end = 0, s = 0; for(let i = 0; i < size; i++) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } return (end - start + 1);} // Driver codelet a = [ -2, -3, 4, -1, -2, 1, 5, -3 ];let n = a.length; document.write(maxSubArraySum(a, n)); // This code is contributed by splevel62 </script>
5
Time Complexity: O(n).
Auxiliary Space: O(1)
parashar
vt_m
splevel62
codewithshinchan
subarray
subarray-sum
Arrays
Dynamic Programming
Arrays
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Largest Sum Contiguous Subarray
Program for Fibonacci numbers
0-1 Knapsack Problem | DP-10
Find if there is a path between two vertices in an undirected graph
Longest Common Subsequence | DP-4 | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 119,
"s": 52,
"text": "An array is given, find length of the subarray having maximum sum."
},
{
"code": null,
"e": 131,
"s": 119,
"text": "Examples : "
},
{
"code": null,
"e": 478,
"s": 131,
"text": "Input : a[] = {1, -2, 1, 1, -2, 1}\nOutput : Length of the subarray is 2\nExplanation: Subarray with consecutive elements \nand maximum sum will be {1, 1}. So length is 2\n\nInput : ar[] = { -2, -3, 4, -1, -2, 1, 5, -3 }\nOutput : Length of the subarray is 5\nExplanation: Subarray with consecutive elements \nand maximum sum will be {4, -1, -2, 1, 5}. "
},
{
"code": null,
"e": 639,
"s": 478,
"text": "This problem is mainly a variation of Largest Sum Contiguous Subarray Problem.The idea is to update starting index whenever sum ending here becomes less than 0."
},
{
"code": null,
"e": 643,
"s": 639,
"text": "C++"
},
{
"code": null,
"e": 648,
"s": 643,
"text": "Java"
},
{
"code": null,
"e": 656,
"s": 648,
"text": "Python3"
},
{
"code": null,
"e": 659,
"s": 656,
"text": "C#"
},
{
"code": null,
"e": 663,
"s": 659,
"text": "PHP"
},
{
"code": null,
"e": 674,
"s": 663,
"text": "Javascript"
},
{
"code": "// C++ program to print length of the largest// contiguous array sum#include<bits/stdc++.h>using namespace std; int maxSubArraySum(int a[], int size){ int max_so_far = INT_MIN, max_ending_here = 0, start =0, end = 0, s=0; for (int i=0; i< size; i++ ) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } return (end - start + 1);} /*Driver program to test maxSubArraySum*/int main(){ int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = sizeof(a)/sizeof(a[0]); cout << maxSubArraySum(a, n); return 0;}",
"e": 1442,
"s": 674,
"text": null
},
{
"code": "// Java program to print length of the largest// contiguous array sumclass GFG { static int maxSubArraySum(int a[], int size) { int max_so_far = Integer.MIN_VALUE, max_ending_here = 0,start = 0, end = 0, s = 0; for (int i = 0; i < size; i++) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } return (end - start + 1); } // Driver code public static void main(String[] args) { int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; int n = a.length; System.out.println(maxSubArraySum(a, n)); }}",
"e": 2300,
"s": 1442,
"text": null
},
{
"code": "# Python3 program to print largest contiguous array sum from sys import maxsize # Function to find the maximum contiguous subarray# and print its starting and end indexdef maxSubArraySum(a,size): max_so_far = -maxsize - 1 max_ending_here = 0 start = 0 end = 0 s = 0 for i in range(0,size): max_ending_here += a[i] if max_so_far < max_ending_here: max_so_far = max_ending_here start = s end = i if max_ending_here < 0: max_ending_here = 0 s = i+1 return (end - start + 1) # Driver program to test maxSubArraySuma = [-2, -3, 4, -1, -2, 1, 5, -3]print(maxSubArraySum(a,len(a)))",
"e": 2978,
"s": 2300,
"text": null
},
{
"code": "// C# program to print length of the// largest contiguous array sumusing System; class GFG { // Function to find maximum subarray sum static int maxSubArraySum(int []a, int size) { int max_so_far = int.MinValue, max_ending_here = 0,start = 0, end = 0, s = 0; for (int i = 0; i < size; i++) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } return (end - start + 1); } // Driver code public static void Main(String[] args) { int []a = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = a.Length; Console.Write(maxSubArraySum(a, n)); }} // This code is contributed by parashar...",
"e": 3923,
"s": 2978,
"text": null
},
{
"code": "<?php// PHP program for Bresenham’s// Line Generation Assumptions : // 1) Line is drawn from// left to right.// 2) x1 < x2 and y1 < y2// 3) Slope of the line is// between 0 and 1.// We draw a line from lower// left to upper right. // function for line generationfunction bresenham($x1, $y1, $x2, $y2){$m_new = 2 * ($y2 - $y1);$slope_error_new = $m_new - ($x2 - $x1);for ($x = $x1, $y = $y1; $x <= $x2; $x++){ echo \"(\" ,$x , \",\" , $y, \")\\n\"; // Add slope to increment // angle formed $slope_error_new += $m_new; // Slope error reached limit, // time to increment y and // update slope error. if ($slope_error_new >= 0) { $y++; $slope_error_new -= 2 * ($x2 - $x1); }}} // Driver Code$x1 = 3; $y1 = 2; $x2 = 15; $y2 = 5;bresenham($x1, $y1, $x2, $y2); // This code is contributed by nitin mittal.?>",
"e": 4764,
"s": 3923,
"text": null
},
{
"code": "<script> // JavaScript program to print length// of the largest contiguous array sumfunction maxSubArraySum(a, size){ let max_so_far = Number.MIN_VALUE, max_ending_here = 0,start = 0, end = 0, s = 0; for(let i = 0; i < size; i++) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } return (end - start + 1);} // Driver codelet a = [ -2, -3, 4, -1, -2, 1, 5, -3 ];let n = a.length; document.write(maxSubArraySum(a, n)); // This code is contributed by splevel62 </script>",
"e": 5488,
"s": 4764,
"text": null
},
{
"code": null,
"e": 5490,
"s": 5488,
"text": "5"
},
{
"code": null,
"e": 5515,
"s": 5492,
"text": "Time Complexity: O(n)."
},
{
"code": null,
"e": 5537,
"s": 5515,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5546,
"s": 5537,
"text": "parashar"
},
{
"code": null,
"e": 5551,
"s": 5546,
"text": "vt_m"
},
{
"code": null,
"e": 5561,
"s": 5551,
"text": "splevel62"
},
{
"code": null,
"e": 5578,
"s": 5561,
"text": "codewithshinchan"
},
{
"code": null,
"e": 5587,
"s": 5578,
"text": "subarray"
},
{
"code": null,
"e": 5600,
"s": 5587,
"text": "subarray-sum"
},
{
"code": null,
"e": 5607,
"s": 5600,
"text": "Arrays"
},
{
"code": null,
"e": 5627,
"s": 5607,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 5634,
"s": 5627,
"text": "Arrays"
},
{
"code": null,
"e": 5654,
"s": 5634,
"text": "Dynamic Programming"
},
{
"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": 5767,
"s": 5752,
"text": "Arrays in Java"
},
{
"code": null,
"e": 5813,
"s": 5767,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 5881,
"s": 5813,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 5925,
"s": 5881,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 5957,
"s": 5925,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 5989,
"s": 5957,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 6019,
"s": 5989,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 6048,
"s": 6019,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 6116,
"s": 6048,
"text": "Find if there is a path between two vertices in an undirected graph"
}
]
|
Kotlin - if...else Expression | Kotlin if...else expressions works like an if...else expression in any other Modern Computer Programming. So let's start with our traditional if...else statement available in Kotlin.
The syntax of a traditional if...else expression is as follows:
if (condition) {
// code block A to be executed if condition is true
} else {
// code block B to be executed if condition is false
}
Here if statement is executed and the given condition is checked. If this condition is evaluated to true then code block A is executed, otherwise program goes into else part and code block B is executed.
You can try the following example:
fun main(args: Array<String>) {
val age:Int = 10
if (age > 18) {
print("Adult")
} else {
print("Minor")
}
}
When you run the above Kotlin program, it will generate the following output:
Minor
Kotlin if...else can also be used as an expression which returns a value and this value can be assigned to a variable. Below is a simple syntax of Kotlin if...else expression:
val result = if (condition) {
// code block A to be executed if condition is true
} else {
// code block B to be executed if condition is false
}
If you're using if as an expression, for example, for returning its value or assigning it to a variable, the else branch is mandatory.
fun main(args: Array<String>) {
val age:Int = 10
val result = if (age > 18) {
"Adult"
} else {
"Minor"
}
println(result)
}
When you run the above Kotlin program, it will generate the following output:
Minor
You can ommit the curly braces {} when if has only one statement:
fun main(args: Array<String>) {
val age:Int = 10
val result = if (age > 18) "Adult" else "Minor"
println(result)
}
When you run the above Kotlin program, it will generate the following output:
Minor
You can include multiple statements in if...else block, in this case the last expression is returned as the value of the block. Try the following example:
fun main(args: Array<String>) {
val age:Int = 10
val result = if (age > 18) {
println("Given condition is true")
"Adult"
} else {
println("Given condition is false")
"Minor"
}
print("The value of result : ")
println(result)
}
When you run the above Kotlin program, it will generate the following output:
Given condition is false
The value of result : Minor
You can use else if condition to specify a new condition if the first condition is false.
if (condition1) {
// code block A to be executed if condition1 is true
} else if (condition2) {
// code block B to be executed if condition2 is true
} else {
// code block C to be executed if condition1 and condition2 are false
}
fun main(args: Array<String>) {
val age:Int = 13
val result = if (age > 19) {
"Adult"
} else if ( age > 12 && age < 20 ){
"Teen"
} else {
"Minor"
}
print("The value of result : ")
println(result)
}
When you run the above Kotlin program, it will generate the following output:
The value of result : Teen
Kotlin allows to put an if expression inside another if expression. This is called nested if expression
if(condition1) {
// code block A to be executed if condition1 is true
if( (condition2) {
// code block B to be executed if condition2 is true
}else{
// code block C to be executed if condition2 is fals
}
} else {
// code block D to be executed if condition1 is false
}
fun main(args: Array<String>) {
val age:Int = 20
val result = if (age > 12) {
if ( age > 12 && age < 20 ){
"Teen"
}else{
"Adult"
}
} else {
"Minor"
}
print("The value of result : ")
println(result)
}
When you run the above Kotlin program, it will generate the following output:
The value of result : Adult
Q 1 - Which of the following is true about Kotlin if expression?
A - Kotlin support traditional if...else expression.
B - Kotlin if...else expression can be nested.
C - Kotlin if...else expression returns a value which can be assigned to a variable.
D - All of the above
All the mentioned statements are correct about Kotlin if expression.
Q 2 - Which of the following is not supported by Kotlin?
A - if...else if...else
B - if...then...else
C - if...else...
D - None of the above
Kotlin does not support if...then...else statement.
Q 3 - What will be the output of the following code?
fun main(args: Array<String>) {
var x = 20
var y = 15
var z = "Mango"
val result = if (x > y ) {
z = "Orange"
} else {
z = "Apple"
}
println("Value of result = $z")
}
A - Mango
B - Orange
C - Apple
D - None of the above
Correct answer is Orange, because x is greater than y, so once this condition is true, it will assign Orange to z variable.
68 Lectures
4.5 hours
Arnab Chakraborty
71 Lectures
5.5 hours
Frahaan Hussain
18 Lectures
1.5 hours
Mahmoud Ramadan
49 Lectures
6 hours
Catalin Stefan
49 Lectures
2.5 hours
Skillbakerystudios
22 Lectures
1 hours
CLEMENT OCHIENG
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2608,
"s": 2425,
"text": "Kotlin if...else expressions works like an if...else expression in any other Modern Computer Programming. So let's start with our traditional if...else statement available in Kotlin."
},
{
"code": null,
"e": 2672,
"s": 2608,
"text": "The syntax of a traditional if...else expression is as follows:"
},
{
"code": null,
"e": 2811,
"s": 2672,
"text": "if (condition) {\n // code block A to be executed if condition is true\n} else {\n // code block B to be executed if condition is false\n}\n"
},
{
"code": null,
"e": 3015,
"s": 2811,
"text": "Here if statement is executed and the given condition is checked. If this condition is evaluated to true then code block A is executed, otherwise program goes into else part and code block B is executed."
},
{
"code": null,
"e": 3050,
"s": 3015,
"text": "You can try the following example:"
},
{
"code": null,
"e": 3192,
"s": 3050,
"text": "fun main(args: Array<String>) {\n val age:Int = 10\n\n if (age > 18) {\n print(\"Adult\")\n } else {\n print(\"Minor\")\n }\n}\n"
},
{
"code": null,
"e": 3270,
"s": 3192,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 3277,
"s": 3270,
"text": "Minor\n"
},
{
"code": null,
"e": 3453,
"s": 3277,
"text": "Kotlin if...else can also be used as an expression which returns a value and this value can be assigned to a variable. Below is a simple syntax of Kotlin if...else expression:"
},
{
"code": null,
"e": 3605,
"s": 3453,
"text": "val result = if (condition) {\n // code block A to be executed if condition is true\n} else {\n // code block B to be executed if condition is false\n}\n"
},
{
"code": null,
"e": 3740,
"s": 3605,
"text": "If you're using if as an expression, for example, for returning its value or assigning it to a variable, the else branch is mandatory."
},
{
"code": null,
"e": 3901,
"s": 3740,
"text": "fun main(args: Array<String>) {\n val age:Int = 10\n\n val result = if (age > 18) {\n \"Adult\"\n } else {\n \"Minor\"\n }\n println(result)\n}\n"
},
{
"code": null,
"e": 3979,
"s": 3901,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 3986,
"s": 3979,
"text": "Minor\n"
},
{
"code": null,
"e": 4052,
"s": 3986,
"text": "You can ommit the curly braces {} when if has only one statement:"
},
{
"code": null,
"e": 4182,
"s": 4052,
"text": "fun main(args: Array<String>) {\n val age:Int = 10\n\n val result = if (age > 18) \"Adult\" else \"Minor\"\n println(result)\n}\n"
},
{
"code": null,
"e": 4260,
"s": 4182,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 4267,
"s": 4260,
"text": "Minor\n"
},
{
"code": null,
"e": 4423,
"s": 4267,
"text": "You can include multiple statements in if...else block, in this case the last expression is returned as the value of the block. Try the following example:"
},
{
"code": null,
"e": 4707,
"s": 4423,
"text": "fun main(args: Array<String>) {\n val age:Int = 10\n\n val result = if (age > 18) {\n println(\"Given condition is true\")\n \"Adult\"\n } else {\n println(\"Given condition is false\")\n \"Minor\"\n }\n print(\"The value of result : \")\n println(result)\n}\n"
},
{
"code": null,
"e": 4785,
"s": 4707,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 4839,
"s": 4785,
"text": "Given condition is false\nThe value of result : Minor\n"
},
{
"code": null,
"e": 4929,
"s": 4839,
"text": "You can use else if condition to specify a new condition if the first condition is false."
},
{
"code": null,
"e": 5166,
"s": 4929,
"text": "if (condition1) {\n // code block A to be executed if condition1 is true\n} else if (condition2) {\n // code block B to be executed if condition2 is true\n} else {\n // code block C to be executed if condition1 and condition2 are false\n}\n"
},
{
"code": null,
"e": 5419,
"s": 5166,
"text": "fun main(args: Array<String>) {\n val age:Int = 13\n\n val result = if (age > 19) {\n \"Adult\"\n } else if ( age > 12 && age < 20 ){\n \"Teen\"\n } else {\n \"Minor\"\n }\n print(\"The value of result : \")\n println(result)\n}\n"
},
{
"code": null,
"e": 5497,
"s": 5419,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 5525,
"s": 5497,
"text": "The value of result : Teen\n"
},
{
"code": null,
"e": 5629,
"s": 5525,
"text": "Kotlin allows to put an if expression inside another if expression. This is called nested if expression"
},
{
"code": null,
"e": 5925,
"s": 5629,
"text": "if(condition1) {\n // code block A to be executed if condition1 is true\n if( (condition2) {\n // code block B to be executed if condition2 is true\n }else{\n // code block C to be executed if condition2 is fals\n }\n} else {\n // code block D to be executed if condition1 is false\n}\n"
},
{
"code": null,
"e": 6204,
"s": 5925,
"text": "fun main(args: Array<String>) {\n val age:Int = 20 \n\n val result = if (age > 12) {\n if ( age > 12 && age < 20 ){\n \"Teen\"\n }else{\n \"Adult\"\n }\n } else {\n \"Minor\"\n }\n print(\"The value of result : \")\n println(result)\n}\n"
},
{
"code": null,
"e": 6282,
"s": 6204,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 6311,
"s": 6282,
"text": "The value of result : Adult\n"
},
{
"code": null,
"e": 6376,
"s": 6311,
"text": "Q 1 - Which of the following is true about Kotlin if expression?"
},
{
"code": null,
"e": 6429,
"s": 6376,
"text": "A - Kotlin support traditional if...else expression."
},
{
"code": null,
"e": 6476,
"s": 6429,
"text": "B - Kotlin if...else expression can be nested."
},
{
"code": null,
"e": 6561,
"s": 6476,
"text": "C - Kotlin if...else expression returns a value which can be assigned to a variable."
},
{
"code": null,
"e": 6582,
"s": 6561,
"text": "D - All of the above"
},
{
"code": null,
"e": 6651,
"s": 6582,
"text": "All the mentioned statements are correct about Kotlin if expression."
},
{
"code": null,
"e": 6708,
"s": 6651,
"text": "Q 2 - Which of the following is not supported by Kotlin?"
},
{
"code": null,
"e": 6732,
"s": 6708,
"text": "A - if...else if...else"
},
{
"code": null,
"e": 6753,
"s": 6732,
"text": "B - if...then...else"
},
{
"code": null,
"e": 6770,
"s": 6753,
"text": "C - if...else..."
},
{
"code": null,
"e": 6792,
"s": 6770,
"text": "D - None of the above"
},
{
"code": null,
"e": 6844,
"s": 6792,
"text": "Kotlin does not support if...then...else statement."
},
{
"code": null,
"e": 6897,
"s": 6844,
"text": "Q 3 - What will be the output of the following code?"
},
{
"code": null,
"e": 7109,
"s": 6897,
"text": "fun main(args: Array<String>) {\n\n var x = 20\n var y = 15\n var z = \"Mango\"\n\n val result = if (x > y ) {\n z = \"Orange\"\n } else {\n z = \"Apple\"\n }\n println(\"Value of result = $z\")\n}\n"
},
{
"code": null,
"e": 7119,
"s": 7109,
"text": "A - Mango"
},
{
"code": null,
"e": 7130,
"s": 7119,
"text": "B - Orange"
},
{
"code": null,
"e": 7140,
"s": 7130,
"text": "C - Apple"
},
{
"code": null,
"e": 7162,
"s": 7140,
"text": "D - None of the above"
},
{
"code": null,
"e": 7286,
"s": 7162,
"text": "Correct answer is Orange, because x is greater than y, so once this condition is true, it will assign Orange to z variable."
},
{
"code": null,
"e": 7321,
"s": 7286,
"text": "\n 68 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 7340,
"s": 7321,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7375,
"s": 7340,
"text": "\n 71 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7392,
"s": 7375,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7427,
"s": 7392,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7444,
"s": 7427,
"text": " Mahmoud Ramadan"
},
{
"code": null,
"e": 7477,
"s": 7444,
"text": "\n 49 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7493,
"s": 7477,
"text": " Catalin Stefan"
},
{
"code": null,
"e": 7528,
"s": 7493,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7548,
"s": 7528,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 7581,
"s": 7548,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7598,
"s": 7581,
"text": " CLEMENT OCHIENG"
},
{
"code": null,
"e": 7605,
"s": 7598,
"text": " Print"
},
{
"code": null,
"e": 7616,
"s": 7605,
"text": " Add Notes"
}
]
|
Biopython - Advanced Sequence Operations | In this chapter, we shall discuss some of the advanced sequence features provided by Biopython.
Nucleotide sequence can be reverse complemented to get new sequence. Also, the complemented sequence can be reverse complemented to get the original sequence. Biopython provides two methods to do this functionality − complement and reverse_complement. The code for this is given below −
>>> from Bio.Alphabet import IUPAC
>>> nucleotide = Seq('TCGAAGTCAGTC', IUPAC.ambiguous_dna)
>>> nucleotide.complement()
Seq('AGCTTCAGTCAG', IUPACAmbiguousDNA())
>>>
Here, the complement() method allows to complement a DNA or RNA sequence. The reverse_complement() method complements and reverses the resultant sequence from left to right. It is shown below −
>>> nucleotide.reverse_complement()
Seq('GACTGACTTCGA', IUPACAmbiguousDNA())
Biopython uses the ambiguous_dna_complement variable provided by Bio.Data.IUPACData to do the complement operation.
>>> from Bio.Data import IUPACData
>>> import pprint
>>> pprint.pprint(IUPACData.ambiguous_dna_complement) {
'A': 'T',
'B': 'V',
'C': 'G',
'D': 'H',
'G': 'C',
'H': 'D',
'K': 'M',
'M': 'K',
'N': 'N',
'R': 'Y',
'S': 'S',
'T': 'A',
'V': 'B',
'W': 'W',
'X': 'X',
'Y': 'R'}
>>>
Genomic DNA base composition (GC content) is predicted to significantly affect genome functioning and species ecology. The GC content is the number of GC nucleotides divided by the total nucleotides.
To get the GC nucleotide content, import the following module and perform the following steps −
>>> from Bio.SeqUtils import GC
>>> nucleotide = Seq("GACTGACTTCGA",IUPAC.unambiguous_dna)
>>> GC(nucleotide)
50.0
Transcription is the process of changing DNA sequence into RNA sequence. The actual biological transcription process is performing a reverse complement (TCAG → CUGA) to get the mRNA considering the DNA as template strand. However, in bioinformatics and so in Biopython, we typically work directly with the coding strand and we can get the mRNA sequence by changing the letter T to U.
Simple example for the above is as follows −
>>> from Bio.Seq import Seq
>>> from Bio.Seq import transcribe
>>> from Bio.Alphabet import IUPAC
>>> dna_seq = Seq("ATGCCGATCGTAT",IUPAC.unambiguous_dna) >>> transcribe(dna_seq)
Seq('AUGCCGAUCGUAU', IUPACUnambiguousRNA())
>>>
To reverse the transcription, T is changed to U as shown in the code below −
>>> rna_seq = transcribe(dna_seq)
>>> rna_seq.back_transcribe()
Seq('ATGCCGATCGTAT', IUPACUnambiguousDNA())
To get the DNA template strand, reverse_complement the back transcribed RNA as given below −
>>> rna_seq.back_transcribe().reverse_complement()
Seq('ATACGATCGGCAT', IUPACUnambiguousDNA())
Translation is a process of translating RNA sequence to protein sequence. Consider a RNA sequence as shown below −
>>> rna_seq = Seq("AUGGCCAUUGUAAU",IUPAC.unambiguous_rna)
>>> rna_seq
Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG', IUPACUnambiguousRNA())
Now, apply translate() function to the code above −
>>> rna_seq.translate()
Seq('MAIV', IUPACProtein())
The above RNA sequence is simple. Consider RNA sequence, AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGA and apply translate() −
>>> rna = Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGA', IUPAC.unambiguous_rna)
>>> rna.translate()
Seq('MAIVMGR*KGAR', HasStopCodon(IUPACProtein(), '*'))
Here, the stop codons are indicated with an asterisk ’*’.
It is possible in translate() method to stop at the first stop codon. To perform this, you can assign to_stop=True in translate() as follows −
>>> rna.translate(to_stop = True)
Seq('MAIVMGR', IUPACProtein())
Here, the stop codon is not included in the resulting sequence because it does not contain one.
The Genetic Codes page of the NCBI provides full list of translation tables used by Biopython. Let us see an example for standard table to visualize the code −
>>> from Bio.Data import CodonTable
>>> table = CodonTable.unambiguous_dna_by_name["Standard"]
>>> print(table)
Table 1 Standard, SGC0
| T | C | A | G |
--+---------+---------+---------+---------+--
T | TTT F | TCT S | TAT Y | TGT C | T
T | TTC F | TCC S | TAC Y | TGC C | C
T | TTA L | TCA S | TAA Stop| TGA Stop| A
T | TTG L(s)| TCG S | TAG Stop| TGG W | G
--+---------+---------+---------+---------+--
C | CTT L | CCT P | CAT H | CGT R | T
C | CTC L | CCC P | CAC H | CGC R | C
C | CTA L | CCA P | CAA Q | CGA R | A
C | CTG L(s)| CCG P | CAG Q | CGG R | G
--+---------+---------+---------+---------+--
A | ATT I | ACT T | AAT N | AGT S | T
A | ATC I | ACC T | AAC N | AGC S | C
A | ATA I | ACA T | AAA K | AGA R | A
A | ATG M(s)| ACG T | AAG K | AGG R | G
--+---------+---------+---------+---------+--
G | GTT V | GCT A | GAT D | GGT G | T
G | GTC V | GCC A | GAC D | GGC G | C
G | GTA V | GCA A | GAA E | GGA G | A
G | GTG V | GCG A | GAG E | GGG G | G
--+---------+---------+---------+---------+--
>>>
Biopython uses this table to translate the DNA to protein as well as to find the Stop codon.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2202,
"s": 2106,
"text": "In this chapter, we shall discuss some of the advanced sequence features provided by Biopython."
},
{
"code": null,
"e": 2489,
"s": 2202,
"text": "Nucleotide sequence can be reverse complemented to get new sequence. Also, the complemented sequence can be reverse complemented to get the original sequence. Biopython provides two methods to do this functionality − complement and reverse_complement. The code for this is given below −"
},
{
"code": null,
"e": 2659,
"s": 2489,
"text": ">>> from Bio.Alphabet import IUPAC \n>>> nucleotide = Seq('TCGAAGTCAGTC', IUPAC.ambiguous_dna) \n>>> nucleotide.complement() \nSeq('AGCTTCAGTCAG', IUPACAmbiguousDNA()) \n>>>"
},
{
"code": null,
"e": 2853,
"s": 2659,
"text": "Here, the complement() method allows to complement a DNA or RNA sequence. The reverse_complement() method complements and reverses the resultant sequence from left to right. It is shown below −"
},
{
"code": null,
"e": 2931,
"s": 2853,
"text": ">>> nucleotide.reverse_complement() \nSeq('GACTGACTTCGA', IUPACAmbiguousDNA())"
},
{
"code": null,
"e": 3047,
"s": 2931,
"text": "Biopython uses the ambiguous_dna_complement variable provided by Bio.Data.IUPACData to do the complement operation."
},
{
"code": null,
"e": 3371,
"s": 3047,
"text": ">>> from Bio.Data import IUPACData \n>>> import pprint \n>>> pprint.pprint(IUPACData.ambiguous_dna_complement) {\n 'A': 'T',\n 'B': 'V',\n 'C': 'G',\n 'D': 'H',\n 'G': 'C',\n 'H': 'D',\n 'K': 'M',\n 'M': 'K',\n 'N': 'N',\n 'R': 'Y',\n 'S': 'S',\n 'T': 'A',\n 'V': 'B',\n 'W': 'W',\n 'X': 'X',\n 'Y': 'R'} \n>>>"
},
{
"code": null,
"e": 3571,
"s": 3371,
"text": "Genomic DNA base composition (GC content) is predicted to significantly affect genome functioning and species ecology. The GC content is the number of GC nucleotides divided by the total nucleotides."
},
{
"code": null,
"e": 3667,
"s": 3571,
"text": "To get the GC nucleotide content, import the following module and perform the following steps −"
},
{
"code": null,
"e": 3785,
"s": 3667,
"text": ">>> from Bio.SeqUtils import GC \n>>> nucleotide = Seq(\"GACTGACTTCGA\",IUPAC.unambiguous_dna) \n>>> GC(nucleotide) \n50.0"
},
{
"code": null,
"e": 4169,
"s": 3785,
"text": "Transcription is the process of changing DNA sequence into RNA sequence. The actual biological transcription process is performing a reverse complement (TCAG → CUGA) to get the mRNA considering the DNA as template strand. However, in bioinformatics and so in Biopython, we typically work directly with the coding strand and we can get the mRNA sequence by changing the letter T to U."
},
{
"code": null,
"e": 4214,
"s": 4169,
"text": "Simple example for the above is as follows −"
},
{
"code": null,
"e": 4446,
"s": 4214,
"text": ">>> from Bio.Seq import Seq \n>>> from Bio.Seq import transcribe \n>>> from Bio.Alphabet import IUPAC \n>>> dna_seq = Seq(\"ATGCCGATCGTAT\",IUPAC.unambiguous_dna) >>> transcribe(dna_seq) \nSeq('AUGCCGAUCGUAU', IUPACUnambiguousRNA()) \n>>>"
},
{
"code": null,
"e": 4523,
"s": 4446,
"text": "To reverse the transcription, T is changed to U as shown in the code below −"
},
{
"code": null,
"e": 4633,
"s": 4523,
"text": ">>> rna_seq = transcribe(dna_seq) \n>>> rna_seq.back_transcribe() \nSeq('ATGCCGATCGTAT', IUPACUnambiguousDNA())"
},
{
"code": null,
"e": 4726,
"s": 4633,
"text": "To get the DNA template strand, reverse_complement the back transcribed RNA as given below −"
},
{
"code": null,
"e": 4822,
"s": 4726,
"text": ">>> rna_seq.back_transcribe().reverse_complement() \nSeq('ATACGATCGGCAT', IUPACUnambiguousDNA())"
},
{
"code": null,
"e": 4937,
"s": 4822,
"text": "Translation is a process of translating RNA sequence to protein sequence. Consider a RNA sequence as shown below −"
},
{
"code": null,
"e": 5079,
"s": 4937,
"text": ">>> rna_seq = Seq(\"AUGGCCAUUGUAAU\",IUPAC.unambiguous_rna) \n>>> rna_seq \nSeq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG', IUPACUnambiguousRNA())"
},
{
"code": null,
"e": 5131,
"s": 5079,
"text": "Now, apply translate() function to the code above −"
},
{
"code": null,
"e": 5184,
"s": 5131,
"text": ">>> rna_seq.translate() \nSeq('MAIV', IUPACProtein())"
},
{
"code": null,
"e": 5302,
"s": 5184,
"text": "The above RNA sequence is simple. Consider RNA sequence, AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGA and apply translate() −"
},
{
"code": null,
"e": 5456,
"s": 5302,
"text": ">>> rna = Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGA', IUPAC.unambiguous_rna) \n>>> rna.translate() \nSeq('MAIVMGR*KGAR', HasStopCodon(IUPACProtein(), '*'))"
},
{
"code": null,
"e": 5514,
"s": 5456,
"text": "Here, the stop codons are indicated with an asterisk ’*’."
},
{
"code": null,
"e": 5657,
"s": 5514,
"text": "It is possible in translate() method to stop at the first stop codon. To perform this, you can assign to_stop=True in translate() as follows −"
},
{
"code": null,
"e": 5723,
"s": 5657,
"text": ">>> rna.translate(to_stop = True) \nSeq('MAIVMGR', IUPACProtein())"
},
{
"code": null,
"e": 5819,
"s": 5723,
"text": "Here, the stop codon is not included in the resulting sequence because it does not contain one."
},
{
"code": null,
"e": 5979,
"s": 5819,
"text": "The Genetic Codes page of the NCBI provides full list of translation tables used by Biopython. Let us see an example for standard table to visualize the code −"
},
{
"code": null,
"e": 7161,
"s": 5979,
"text": ">>> from Bio.Data import CodonTable \n>>> table = CodonTable.unambiguous_dna_by_name[\"Standard\"] \n>>> print(table) \nTable 1 Standard, SGC0\n | T | C | A | G | \n --+---------+---------+---------+---------+-- \n T | TTT F | TCT S | TAT Y | TGT C | T\n T | TTC F | TCC S | TAC Y | TGC C | C\n T | TTA L | TCA S | TAA Stop| TGA Stop| A\n T | TTG L(s)| TCG S | TAG Stop| TGG W | G \n --+---------+---------+---------+---------+--\n C | CTT L | CCT P | CAT H | CGT R | T\n C | CTC L | CCC P | CAC H | CGC R | C\n C | CTA L | CCA P | CAA Q | CGA R | A\n C | CTG L(s)| CCG P | CAG Q | CGG R | G \n --+---------+---------+---------+---------+--\n A | ATT I | ACT T | AAT N | AGT S | T\n A | ATC I | ACC T | AAC N | AGC S | C\n A | ATA I | ACA T | AAA K | AGA R | A\n A | ATG M(s)| ACG T | AAG K | AGG R | G \n --+---------+---------+---------+---------+--\n G | GTT V | GCT A | GAT D | GGT G | T\n G | GTC V | GCC A | GAC D | GGC G | C\n G | GTA V | GCA A | GAA E | GGA G | A\n G | GTG V | GCG A | GAG E | GGG G | G \n --+---------+---------+---------+---------+-- \n>>>\n"
},
{
"code": null,
"e": 7254,
"s": 7161,
"text": "Biopython uses this table to translate the DNA to protein as well as to find the Stop codon."
},
{
"code": null,
"e": 7261,
"s": 7254,
"text": " Print"
},
{
"code": null,
"e": 7272,
"s": 7261,
"text": " Add Notes"
}
]
|
Displaying Logging While Drilling (LWD) Image Logs in Python | by Andy McDonald | Towards Data Science | Borehole image logs are false-color pseudo images of the borehole wall generated from different logging measurements/tools. How borehole images are acquired differs between wireline logging and logging while drilling (LWD). In the wireline environment measurements are made from buttons on pads that are pressed up against the borehole wall and provide limited coverage, but at a high resolution. In contrast, in the LWD environment measurements are made from sensors built into tools that form part of the drillstring/tool assembly, and using the tool rotation, provide full 360-degree coverage. LWD image data is often split into sectors, the number of which will vary depending on the tool technology. As the tool rotates the data is binned into the relevant sector and from it we can build up a pseudo image of the borehole wall.
The generated images are often viewed in two dimensions on a log plot as an ‘unwrapped borehole’ and as seen in the image above. The cylindrical borehole is cut along the north azimuth in vertical wells or along the highside of the borehole in deviated/horizontal wells. As a result of being projected onto a 2D surface, any planar features that intersect the borehole are represented as sinusoid shapes on the plot. By analyzing the amplitude and offset of these sinusoids geologists can gain an understanding of the geological structure of the subsurface. Borehole image data can also be used to identify and classify different geological facies/textures, identify thin-beds, fault and fracture analysis, and more.
In this article, I am going to work through displaying logging while drilling image data from azimuthal gamma ray and azimuthal density measurements using Python and matplotlib.
This article forms part of my Python & Petrophysics series. Details of which can be found here. For the examples below you can find my Jupyter Notebook and dataset on my GitHub repository at the following link.
github.com
To follow along, the data file for this article can be found in the Data subfolder of the Python & Petrophysics repository.
Before we begin working with our data we will need to import a number of libraries for us to work with. For this article, we will be using pandas, matplotlib, numpy and lasio libraries. These three libraries allow us to load our las data, work with it and create visualizations of the data.
The dataset we are using comes from the publicly accessible Netherlands NLOG database. The las file contains a mixture of LWD measurements and two images. As las files are flat and don’t support arrays, LWD image data is often delivered as individual sectors. The second file we will load is the survey, this allows us to understand the deviation and azimuth of the wellbore and is useful for calculating accurate formation dips. We will not be covering dip picking in this article.
We will first load the las file using lasio and convert it to a dataframe using .df().
Once the data has been loaded, we can confirm the data that we have by using .describe(). As there is a large number of curves present within the file, we can call upon df.columns() to view the full list of curves present:
Which returns:
Index(['APRESM', 'GRAFM', 'RACELM', 'RPCELM', 'RACEHM', 'RPCEHM', 'RACESLM', 'RPCESLM', 'RACESHM', 'RPCESHM', 'RPTHM', 'NPCKLFM', 'DPEFM', 'BDCFM', 'DRHFM', 'TVD', 'BLOCKCOMP', 'INNM', 'ROP_AVG', 'WOB_AVG', 'TCDM', 'ABDCUM', 'ABDCLM', 'ABDCRM', 'ABDCDM', 'ABDC1M', 'ABDC2M', 'ABDC3M', 'ABDC4M', 'ABDC5M', 'ABDC6M', 'ABDC7M', 'ABDC8M', 'ABDC9M', 'ABDC10M', 'ABDC11M', 'ABDC12M', 'ABDC13M', 'ABDC14M', 'ABDC15M', 'ABDC16M','ABDCM', 'GRAS0M', 'GRAS1M', 'GRAS2M', 'GRAS3M', 'GRAS4M', 'GRAS5M', 'GRAS6M', 'GRAS7M', 'GRASM'], dtype='object')
As explained in the introduction, we can see the azimuthal density image is split into 16 individual sectors labeled ABDC1M to ABDC16M. The azimuthal gamma ray image is split into 8 sectors and labeled GRAS0M to GRAS7M.
The survey data is contained within a csv file and can be loaded as follows.
When we read the columns from the dataframe we find we have three curves present: measured depth (DEPTH), hole deviation (DEVI), and hole azimuth (AZIM). We will be using these curves for additional visualization on our plot.
Before we plot the data, we will make the data simpler to handle by splitting it the main dataframe into two smaller ones for each image. We can achieve this by calling upon the dataframe (df) and supplying a list of curve names that we want to extract.
Plotting the image data is fairly straight forward. We first have to create a figure object using plt.figure(figsize=(7,15)). The figsize argument allows us to control the size, in inches, of our final plot.
We can also, optionally, create two new variables for our min and max depth. These are used to define the extent of the plotting area. As the index of our dataframe contains our depth values we can create two new variables miny and maxy that are equal to the minimum and maximum index values.
When we execute the code we generate an image that shows us our features, but at the same time, we can see it is a bit blocky looking. If you look close enough you will be able to make out the individual sectors for the image.
We can apply some interpolation to the image and smooth it out. In the example below, the interpolation has been changed to bilinear.
You can find a full list of options for interpolation available in the matplotlib documentation. To illustrate the different methods, I have used the code from the documentation to generate a grid show the different options.
You can see from the image above that some (lanczos and sinc) appear slightly sharper than the others. The choice will ultimately be down to user preference when working with the image data.
We can repeat the above code, by change the data frame from azidendf to azigamdf to generate our Azimuthal Gamma Ray image.
When we view our image, we notice that the level of detail is significantly less compared to the density image. This is related to the measurement type and the lower number of sectors being recorded.
We can now plot both our image logs together alongside the survey data using subplots. The subplot2grid((1,3),(0,0)) method allows us to set up the shape of the plot, in this case, we are plotting 1 row and 3 columns. We then assign ax1, ax2, and ax3 to the three columns as denoted by the second set of numbers in the function. As we are plotting deviation on the same track as the azimuth we need to use ax.twiny() to add a new axis on top of an existing one.
To plot our image data, we can use the code in the previous sections for each of the images and instead of assigning it to a plot, we can assign them to subplot axes.
Now we can see both images together and we can also take into account our borehole deviation, which indicates that we are in a horizontal section. This is important to know, especially when calculating any dips from image logs.
You may notice that the bed at 2,500 appears to offset between the two plots and would warrant further investigation. This will not be covered in this article.
In this article, we have covered how to load and display borehole image logs from LWD azimuthal gamma ray and density measurements. Once the data has been separated into their respective dataframes it is easy to pass them to the imshow() plot in matplotlib. From this image data geologists and petrophysicists can gain a better understanding of the geological makeup of the subsurface.
“All images generated by the author”
Thanks for reading!
If you have found this article useful, please feel free to check out my other articles looking at various aspects of Python and well log data. You can also find my code used in this article and others at GitHub.
If you want to get in touch you can find me on LinkedIn or at my website.
Interested in learning more about python and well log data or petrophysics? Follow me on Medium. | [
{
"code": null,
"e": 1006,
"s": 172,
"text": "Borehole image logs are false-color pseudo images of the borehole wall generated from different logging measurements/tools. How borehole images are acquired differs between wireline logging and logging while drilling (LWD). In the wireline environment measurements are made from buttons on pads that are pressed up against the borehole wall and provide limited coverage, but at a high resolution. In contrast, in the LWD environment measurements are made from sensors built into tools that form part of the drillstring/tool assembly, and using the tool rotation, provide full 360-degree coverage. LWD image data is often split into sectors, the number of which will vary depending on the tool technology. As the tool rotates the data is binned into the relevant sector and from it we can build up a pseudo image of the borehole wall."
},
{
"code": null,
"e": 1723,
"s": 1006,
"text": "The generated images are often viewed in two dimensions on a log plot as an ‘unwrapped borehole’ and as seen in the image above. The cylindrical borehole is cut along the north azimuth in vertical wells or along the highside of the borehole in deviated/horizontal wells. As a result of being projected onto a 2D surface, any planar features that intersect the borehole are represented as sinusoid shapes on the plot. By analyzing the amplitude and offset of these sinusoids geologists can gain an understanding of the geological structure of the subsurface. Borehole image data can also be used to identify and classify different geological facies/textures, identify thin-beds, fault and fracture analysis, and more."
},
{
"code": null,
"e": 1901,
"s": 1723,
"text": "In this article, I am going to work through displaying logging while drilling image data from azimuthal gamma ray and azimuthal density measurements using Python and matplotlib."
},
{
"code": null,
"e": 2112,
"s": 1901,
"text": "This article forms part of my Python & Petrophysics series. Details of which can be found here. For the examples below you can find my Jupyter Notebook and dataset on my GitHub repository at the following link."
},
{
"code": null,
"e": 2123,
"s": 2112,
"text": "github.com"
},
{
"code": null,
"e": 2247,
"s": 2123,
"text": "To follow along, the data file for this article can be found in the Data subfolder of the Python & Petrophysics repository."
},
{
"code": null,
"e": 2538,
"s": 2247,
"text": "Before we begin working with our data we will need to import a number of libraries for us to work with. For this article, we will be using pandas, matplotlib, numpy and lasio libraries. These three libraries allow us to load our las data, work with it and create visualizations of the data."
},
{
"code": null,
"e": 3021,
"s": 2538,
"text": "The dataset we are using comes from the publicly accessible Netherlands NLOG database. The las file contains a mixture of LWD measurements and two images. As las files are flat and don’t support arrays, LWD image data is often delivered as individual sectors. The second file we will load is the survey, this allows us to understand the deviation and azimuth of the wellbore and is useful for calculating accurate formation dips. We will not be covering dip picking in this article."
},
{
"code": null,
"e": 3108,
"s": 3021,
"text": "We will first load the las file using lasio and convert it to a dataframe using .df()."
},
{
"code": null,
"e": 3331,
"s": 3108,
"text": "Once the data has been loaded, we can confirm the data that we have by using .describe(). As there is a large number of curves present within the file, we can call upon df.columns() to view the full list of curves present:"
},
{
"code": null,
"e": 3346,
"s": 3331,
"text": "Which returns:"
},
{
"code": null,
"e": 3882,
"s": 3346,
"text": "Index(['APRESM', 'GRAFM', 'RACELM', 'RPCELM', 'RACEHM', 'RPCEHM', 'RACESLM', 'RPCESLM', 'RACESHM', 'RPCESHM', 'RPTHM', 'NPCKLFM', 'DPEFM', 'BDCFM', 'DRHFM', 'TVD', 'BLOCKCOMP', 'INNM', 'ROP_AVG', 'WOB_AVG', 'TCDM', 'ABDCUM', 'ABDCLM', 'ABDCRM', 'ABDCDM', 'ABDC1M', 'ABDC2M', 'ABDC3M', 'ABDC4M', 'ABDC5M', 'ABDC6M', 'ABDC7M', 'ABDC8M', 'ABDC9M', 'ABDC10M', 'ABDC11M', 'ABDC12M', 'ABDC13M', 'ABDC14M', 'ABDC15M', 'ABDC16M','ABDCM', 'GRAS0M', 'GRAS1M', 'GRAS2M', 'GRAS3M', 'GRAS4M', 'GRAS5M', 'GRAS6M', 'GRAS7M', 'GRASM'], dtype='object')"
},
{
"code": null,
"e": 4102,
"s": 3882,
"text": "As explained in the introduction, we can see the azimuthal density image is split into 16 individual sectors labeled ABDC1M to ABDC16M. The azimuthal gamma ray image is split into 8 sectors and labeled GRAS0M to GRAS7M."
},
{
"code": null,
"e": 4179,
"s": 4102,
"text": "The survey data is contained within a csv file and can be loaded as follows."
},
{
"code": null,
"e": 4405,
"s": 4179,
"text": "When we read the columns from the dataframe we find we have three curves present: measured depth (DEPTH), hole deviation (DEVI), and hole azimuth (AZIM). We will be using these curves for additional visualization on our plot."
},
{
"code": null,
"e": 4659,
"s": 4405,
"text": "Before we plot the data, we will make the data simpler to handle by splitting it the main dataframe into two smaller ones for each image. We can achieve this by calling upon the dataframe (df) and supplying a list of curve names that we want to extract."
},
{
"code": null,
"e": 4867,
"s": 4659,
"text": "Plotting the image data is fairly straight forward. We first have to create a figure object using plt.figure(figsize=(7,15)). The figsize argument allows us to control the size, in inches, of our final plot."
},
{
"code": null,
"e": 5160,
"s": 4867,
"text": "We can also, optionally, create two new variables for our min and max depth. These are used to define the extent of the plotting area. As the index of our dataframe contains our depth values we can create two new variables miny and maxy that are equal to the minimum and maximum index values."
},
{
"code": null,
"e": 5387,
"s": 5160,
"text": "When we execute the code we generate an image that shows us our features, but at the same time, we can see it is a bit blocky looking. If you look close enough you will be able to make out the individual sectors for the image."
},
{
"code": null,
"e": 5521,
"s": 5387,
"text": "We can apply some interpolation to the image and smooth it out. In the example below, the interpolation has been changed to bilinear."
},
{
"code": null,
"e": 5746,
"s": 5521,
"text": "You can find a full list of options for interpolation available in the matplotlib documentation. To illustrate the different methods, I have used the code from the documentation to generate a grid show the different options."
},
{
"code": null,
"e": 5937,
"s": 5746,
"text": "You can see from the image above that some (lanczos and sinc) appear slightly sharper than the others. The choice will ultimately be down to user preference when working with the image data."
},
{
"code": null,
"e": 6061,
"s": 5937,
"text": "We can repeat the above code, by change the data frame from azidendf to azigamdf to generate our Azimuthal Gamma Ray image."
},
{
"code": null,
"e": 6261,
"s": 6061,
"text": "When we view our image, we notice that the level of detail is significantly less compared to the density image. This is related to the measurement type and the lower number of sectors being recorded."
},
{
"code": null,
"e": 6723,
"s": 6261,
"text": "We can now plot both our image logs together alongside the survey data using subplots. The subplot2grid((1,3),(0,0)) method allows us to set up the shape of the plot, in this case, we are plotting 1 row and 3 columns. We then assign ax1, ax2, and ax3 to the three columns as denoted by the second set of numbers in the function. As we are plotting deviation on the same track as the azimuth we need to use ax.twiny() to add a new axis on top of an existing one."
},
{
"code": null,
"e": 6890,
"s": 6723,
"text": "To plot our image data, we can use the code in the previous sections for each of the images and instead of assigning it to a plot, we can assign them to subplot axes."
},
{
"code": null,
"e": 7118,
"s": 6890,
"text": "Now we can see both images together and we can also take into account our borehole deviation, which indicates that we are in a horizontal section. This is important to know, especially when calculating any dips from image logs."
},
{
"code": null,
"e": 7278,
"s": 7118,
"text": "You may notice that the bed at 2,500 appears to offset between the two plots and would warrant further investigation. This will not be covered in this article."
},
{
"code": null,
"e": 7664,
"s": 7278,
"text": "In this article, we have covered how to load and display borehole image logs from LWD azimuthal gamma ray and density measurements. Once the data has been separated into their respective dataframes it is easy to pass them to the imshow() plot in matplotlib. From this image data geologists and petrophysicists can gain a better understanding of the geological makeup of the subsurface."
},
{
"code": null,
"e": 7701,
"s": 7664,
"text": "“All images generated by the author”"
},
{
"code": null,
"e": 7721,
"s": 7701,
"text": "Thanks for reading!"
},
{
"code": null,
"e": 7933,
"s": 7721,
"text": "If you have found this article useful, please feel free to check out my other articles looking at various aspects of Python and well log data. You can also find my code used in this article and others at GitHub."
},
{
"code": null,
"e": 8007,
"s": 7933,
"text": "If you want to get in touch you can find me on LinkedIn or at my website."
}
]
|
Intersection of Two Arrays II in Python | Suppose we have two arrays A and B, there are few elements in these array. We have to find the intersection of them. So if A = [1, 4, 5, 3, 6], and B = [2, 3, 5, 7, 9], then intersection will be [3, 5]
To solve this, we will follow these steps −
Take two arrays A and B
if length of A is smaller than length of B, then swap them
calculate the frequency of elements in the array and store them into m
for each element e in B, if e is present in m, and frequency is non-zero,decrease frequency m[e] by 1insert e into the resultant array
decrease frequency m[e] by 1
insert e into the resultant array
return the resultant array
Let us see the following implementation to get better understanding −
Live Demo
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
m = {}
if len(nums1)<len(nums2):
nums1,nums2 = nums2,nums1
for i in nums1:
if i not in m:
m[i] = 1
else:
m[i]+=1
result = []
for i in nums2:
if i in m and m[i]:
m[i]-=1
result.append(i)
return result
ob1 = Solution()
print(ob1.intersect([1,4,5,3,6], [2,3,5,7,9]))
[1,4,5,3,6]
[2,3,5,7,9]
[3,5] | [
{
"code": null,
"e": 1264,
"s": 1062,
"text": "Suppose we have two arrays A and B, there are few elements in these array. We have to find the intersection of them. So if A = [1, 4, 5, 3, 6], and B = [2, 3, 5, 7, 9], then intersection will be [3, 5]"
},
{
"code": null,
"e": 1308,
"s": 1264,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1332,
"s": 1308,
"text": "Take two arrays A and B"
},
{
"code": null,
"e": 1391,
"s": 1332,
"text": "if length of A is smaller than length of B, then swap them"
},
{
"code": null,
"e": 1462,
"s": 1391,
"text": "calculate the frequency of elements in the array and store them into m"
},
{
"code": null,
"e": 1597,
"s": 1462,
"text": "for each element e in B, if e is present in m, and frequency is non-zero,decrease frequency m[e] by 1insert e into the resultant array"
},
{
"code": null,
"e": 1626,
"s": 1597,
"text": "decrease frequency m[e] by 1"
},
{
"code": null,
"e": 1660,
"s": 1626,
"text": "insert e into the resultant array"
},
{
"code": null,
"e": 1687,
"s": 1660,
"text": "return the resultant array"
},
{
"code": null,
"e": 1757,
"s": 1687,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1768,
"s": 1757,
"text": " Live Demo"
},
{
"code": null,
"e": 2316,
"s": 1768,
"text": "class Solution(object):\n def intersect(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: List[int]\n \"\"\"\n m = {}\n if len(nums1)<len(nums2):\n nums1,nums2 = nums2,nums1\n for i in nums1:\n if i not in m:\n m[i] = 1\n else:\n m[i]+=1\n result = []\n for i in nums2:\n if i in m and m[i]:\n m[i]-=1\n result.append(i)\n return result\nob1 = Solution()\nprint(ob1.intersect([1,4,5,3,6], [2,3,5,7,9]))"
},
{
"code": null,
"e": 2340,
"s": 2316,
"text": "[1,4,5,3,6]\n[2,3,5,7,9]"
},
{
"code": null,
"e": 2346,
"s": 2340,
"text": "[3,5]"
}
]
|
How to change ttk.Treeview column width and weight in Python 3.3? | To display a large set of data in a Tkinter application, we can use the Treeview widget. Generally, we represent data through tables that contain a set of rows and columns. We can add the data in the form of a table with the help of the Treeview widget.
To configure the column width of the Treeview widget, we can use the width and stretch property. It sets the width of the Treeview widget column with the given value.
In this example, we have created a table that contains a list of programming languages. The width of columns ‘ID’ and ‘Programming Language’ is set to their content. Further, we can give a value to set the width of the columns.
# Import the required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame
win=Tk()
# Set the size of the tkinter window
win.geometry("700x350")
# Create an instance of Style widget
style=ttk.Style()
style.theme_use('clam')
# Add a Treeview widget
tree=ttk.Treeview(win, column=("c1", "c2"), show='headings', height=8)
tree.column("# 1",anchor=CENTER, stretch=NO, width=100)
tree.heading("# 1", text="ID")
tree.column("# 2", anchor=CENTER, stretch=NO)
tree.heading("# 2", text="Programming Language")
# Insert the data in Treeview widget
tree.insert('', 'end',text="1",values=('1','C++'))
tree.insert('', 'end',text="2",values=('2', 'Java'))
tree.insert('', 'end',text="3",values=('3', 'Python'))
tree.insert('', 'end',text="4",values=('4', 'Golang'))
tree.insert('', 'end',text="5",values=('5', 'JavaScript'))
tree.insert('', 'end',text="6",values=('6', 'C# '))
tree.insert('', 'end',text="7",values=('6', 'Rust'))
tree.insert('', 'end',text="8",values=('6', 'SQL'))
tree.pack()
win.mainloop()
Run the above code to display a Table that contains a list of programming languages and Index. | [
{
"code": null,
"e": 1316,
"s": 1062,
"text": "To display a large set of data in a Tkinter application, we can use the Treeview widget. Generally, we represent data through tables that contain a set of rows and columns. We can add the data in the form of a table with the help of the Treeview widget."
},
{
"code": null,
"e": 1483,
"s": 1316,
"text": "To configure the column width of the Treeview widget, we can use the width and stretch property. It sets the width of the Treeview widget column with the given value."
},
{
"code": null,
"e": 1711,
"s": 1483,
"text": "In this example, we have created a table that contains a list of programming languages. The width of columns ‘ID’ and ‘Programming Language’ is set to their content. Further, we can give a value to set the width of the columns."
},
{
"code": null,
"e": 2753,
"s": 1711,
"text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame\nwin=Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\n\n# Create an instance of Style widget\nstyle=ttk.Style()\nstyle.theme_use('clam')\n\n# Add a Treeview widget\ntree=ttk.Treeview(win, column=(\"c1\", \"c2\"), show='headings', height=8)\ntree.column(\"# 1\",anchor=CENTER, stretch=NO, width=100)\ntree.heading(\"# 1\", text=\"ID\")\ntree.column(\"# 2\", anchor=CENTER, stretch=NO)\ntree.heading(\"# 2\", text=\"Programming Language\")\n\n# Insert the data in Treeview widget\ntree.insert('', 'end',text=\"1\",values=('1','C++'))\ntree.insert('', 'end',text=\"2\",values=('2', 'Java'))\ntree.insert('', 'end',text=\"3\",values=('3', 'Python'))\ntree.insert('', 'end',text=\"4\",values=('4', 'Golang'))\ntree.insert('', 'end',text=\"5\",values=('5', 'JavaScript'))\ntree.insert('', 'end',text=\"6\",values=('6', 'C# '))\ntree.insert('', 'end',text=\"7\",values=('6', 'Rust'))\ntree.insert('', 'end',text=\"8\",values=('6', 'SQL'))\n\ntree.pack()\nwin.mainloop()"
},
{
"code": null,
"e": 2848,
"s": 2753,
"text": "Run the above code to display a Table that contains a list of programming languages and Index."
}
]
|
HTML | <input> required Attribute - GeeksforGeeks | 07 Oct, 2021
The HTML required Attribute is a Boolean attribute which is used to specify that the input element must be filled out before submitting the Form. This attribute works with other types of input like radio, checkbox, number, text, etc.Syntax:
<input required>
Example-1: This Example that illustrates the use of required attribute in input Element.
html
<!DOCTYPE html><html> <head> <title> required Attribute </title> <style> h1, h2 { color: green; font-style: italic; } body { text-align: center; } </style></head> <body> <h1>GeeksForGeeks</h1> <h2> HTML input required attribute </h2> <form action=""> Username: <input type="text" name="username" required> <br> Password: <input type="password" name="password"> <br> <input type="submit"> </form></body> </html>
Output :
Example-2: This Example that illustrates the use of required attribute in input Element.
html
<!DOCTYPE html><html> <head> <title> required Attribute </title> <style> h1, h2 { color: green; font-style: italic; } body { text-align: center; } </style></head> <body> <h1>GeeksForGeeks</h1> <h2> HTML input required attribute </h2> <form action=""> Required: <input type="radio" name="radiocheck" required> <br> <input type="submit"> </form></body> </html>
Output :
Supported Browsers: The browser supported by HTML input required Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
prachisoda1234
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 24336,
"s": 24308,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 24578,
"s": 24336,
"text": "The HTML required Attribute is a Boolean attribute which is used to specify that the input element must be filled out before submitting the Form. This attribute works with other types of input like radio, checkbox, number, text, etc.Syntax: "
},
{
"code": null,
"e": 24596,
"s": 24578,
"text": "<input required> "
},
{
"code": null,
"e": 24686,
"s": 24596,
"text": "Example-1: This Example that illustrates the use of required attribute in input Element. "
},
{
"code": null,
"e": 24691,
"s": 24686,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> required Attribute </title> <style> h1, h2 { color: green; font-style: italic; } body { text-align: center; } </style></head> <body> <h1>GeeksForGeeks</h1> <h2> HTML input required attribute </h2> <form action=\"\"> Username: <input type=\"text\" name=\"username\" required> <br> Password: <input type=\"password\" name=\"password\"> <br> <input type=\"submit\"> </form></body> </html>",
"e": 25296,
"s": 24691,
"text": null
},
{
"code": null,
"e": 25306,
"s": 25296,
"text": "Output : "
},
{
"code": null,
"e": 25396,
"s": 25306,
"text": "Example-2: This Example that illustrates the use of required attribute in input Element. "
},
{
"code": null,
"e": 25401,
"s": 25396,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> required Attribute </title> <style> h1, h2 { color: green; font-style: italic; } body { text-align: center; } </style></head> <body> <h1>GeeksForGeeks</h1> <h2> HTML input required attribute </h2> <form action=\"\"> Required: <input type=\"radio\" name=\"radiocheck\" required> <br> <input type=\"submit\"> </form></body> </html>",
"e": 25926,
"s": 25401,
"text": null
},
{
"code": null,
"e": 25936,
"s": 25926,
"text": "Output : "
},
{
"code": null,
"e": 26030,
"s": 25936,
"text": "Supported Browsers: The browser supported by HTML input required Attribute are listed below: "
},
{
"code": null,
"e": 26044,
"s": 26030,
"text": "Google Chrome"
},
{
"code": null,
"e": 26062,
"s": 26044,
"text": "Internet Explorer"
},
{
"code": null,
"e": 26070,
"s": 26062,
"text": "Firefox"
},
{
"code": null,
"e": 26076,
"s": 26070,
"text": "Opera"
},
{
"code": null,
"e": 26083,
"s": 26076,
"text": "Safari"
},
{
"code": null,
"e": 26220,
"s": 26083,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 26235,
"s": 26220,
"text": "prachisoda1234"
},
{
"code": null,
"e": 26251,
"s": 26235,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 26256,
"s": 26251,
"text": "HTML"
},
{
"code": null,
"e": 26273,
"s": 26256,
"text": "Web Technologies"
},
{
"code": null,
"e": 26278,
"s": 26273,
"text": "HTML"
},
{
"code": null,
"e": 26376,
"s": 26278,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26424,
"s": 26376,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 26474,
"s": 26424,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26498,
"s": 26474,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26548,
"s": 26498,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 26585,
"s": 26548,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 26627,
"s": 26585,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26660,
"s": 26627,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26703,
"s": 26660,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26748,
"s": 26703,
"text": "Convert a string to an integer in JavaScript"
}
]
|
How to solve a constraint optimization problem in R | by Rahul Bhadani | Towards Data Science | Often in physical science research, we end up with a hard problem of optimizing a function (called objective) that needs to satisfy a range of constraints — linear or non-linear equalities and inequalities. The optimizers usually also have to adhere to the upper and lower bound. I recently worked on a similar problem in Quantum Information Science (QIS) where I attempted to optimize a non-linear function based on a few constraints dictated by rules of physics and mathematics. Interested readers may find my work on Constellation Optimization for Phase-Shift Keying Coherent States With Displacement Receiver to Maximize Mutual Information where I optimized mutual information for QuadriPhase-Shift Keying (QPSK) based on a set of constraints.
ieeexplore.ieee.org
While chasing the problem of non-linear optimization with a set of constraints, I found out that not all optimization routines are created equally. There are several libraries available in different languages such as python (scipy.optimize), Matlab (fmincon), C++ (robotim, nlopt), and R (nloptr). While my list for optimization routine is not exhaustive, some of them are more reliable than others, some provide faster execution than others and some have better documentation. Based on several key factors, I find nloptr, implemented in the R language to be most suitable for nonlinear optimization. nloptr uses nlopt implemented in C++ as a backend. As a result, it provides the elegance of the R language and the speed of C++. The optimization procedure is performed quickly in a fraction of seconds even with a tolerance of the order of 10e-15.
A general nonlinear optimization problem usually have the form
where f is an objective function, g defines a set of inequality constraints, h is a set of equality constraints. xL and xU are lower and upper bounds respectively. In the literature, several optimization algorithms have been presented. For example, MMA (Method of moving asymptotes)1 supports arbitrary nonlinear inequality constraints, (COBYLA) Constrained Optimization BY Linear Approximation2, (ORIG_DRIECT) DIRECT algorithm3. Optimization algorithms that also support nonlinear equality constraints include ISRES (Improved Stochastic Ranking Evolution Strategy)4, (AUGLAG) Augmented Lagrangian Algorithm5. A full list of such methods can be found on nlopt C++ reference page at https://nlopt.readthedocs.io/en/latest/NLopt_Reference/. nloptr uses one of these methods to solve the given optimization problem.
“MMA (Method of moving asymptotes) supports arbitrary nonlinear inequality constraints, (COBYLA) Constrained Optimization BY Linear Approximation, (ORIG_DRIECT) DIRECT algorithm. Optimization algorithms that also support nonlinear equality constraints include ISRES (Improved Stochastic Ranking Evolution Strategy), (AUGLAG) Augmented Lagrangian Algorithm.”
In the rest of the article, I provide several examples of solving a constraint optimization problem using R. I personally use R Studio that combines R compiler and editor. R Studio also provides knitr tool which is great for writing documentation or articles with inline code which can also generate a latex source code and a pdf file. Most of the example presented here has been modified from test suites used to validate functions in nloptr R package.
Installation of nloptr in R is fairly straightforward.
install.packages(“nloptr”)library(‘nloptr’)
In the first example, we will minimize the Rosenbrock Banana function
whose gradient is given by
However, not all the algorithms in nlopt require explicit gradient as we will see in further examples. Let’s define the objective function and its gradient first:
eval_f <- function(x){ return ( 100 * (x[2] - x[1] * x[1])^2 + (1 - x[1])^2 )}eval_grad_f <- function(x) {return( c( -400 * x[1] * (x[2] - x[1] * x[1]) - 2 * (1 - x[1]),200 * (x[2] - x[1] * x[1]) ) )}
We will also need initial values of optimizers:
x0 <- c( -1.2, 1 )
Before we run the minimization procedure, we need to specify which algorithm we will use. That can be done as follows:
opts <- list("algorithm"="NLOPT_LD_LBFGS","xtol_rel"=1.0e-8)
Here, we will use the L-BFGS algorithm. Now we are ready to run the optimization procedure.
# solve Rosenbrock Banana functionres <- nloptr( x0=x0,eval_f=eval_f,eval_grad_f=eval_grad_f,opts=opts)
We can see the result by typing
print(res)
The function is optimized at (1,1) which is the ground truth. Check yourself by running the code in R Studio.
The problem to minimize is
with a1= 2, b1 = 0, a2 = −1, and b2 = 1. We re-arrange the constraints to have the form g(x) ≤ 0:
First, define the objective function
# objective functioneval_f0 <- function( x, a, b ){return( sqrt(x[2]) )}
and constraints are
# constraint functioneval_g0 <- function( x, a, b ) {return( (a*x[1] + b)^3 - x[2] )}
Define parameters
# define parametersa <- c(2,-1)b <- c(0, 1)
Now solve using NLOPT_LN_COBYLA without gradient information
# Solve using NLOPT_LN_COBYLA without gradient informationres1 <- nloptr( x0=c(1.234,5.678),eval_f=eval_f0,lb = c(-Inf,0),ub = c(Inf,Inf),eval_g_ineq = eval_g0,opts = list("algorithm"="NLOPT_LN_COBYLA","xtol_rel"=1.0e-8),a = a,b = b )print( res1 )
We want to solve the following constraint optimization problem
subject to constraints
For this example, the optimal solution is achieved at (1.00000000, 4.74299963, 3.82114998, 1.37940829).
# Objective Functioneval_f <- function(x){return (x[1]*x[4]*(x[1] +x[2] + x[3] ) + x[3] )}# Inequality constraintseval_g_ineq <- function(x){return (25 - x[1]*x[2]*x[3]*x[4])}# Equality constraintseval_g_eq <- function(x){return ( x[1]^2 + x[2]^2 + x[3]^2 + x[4]^2 - 40 )}# Lower and upper boundslb <- c(1,1,1,1)ub <- c(5,5,5,5)#initial valuesx0 <- c(1,5,5,1)
We will also need to define options for optimizations
# Set optimization options.local_opts <- list( "algorithm" = "NLOPT_LD_MMA", "xtol_rel" = 1.0e-15 )opts <- list( "algorithm"= "NLOPT_GN_ISRES","xtol_rel"= 1.0e-15,"maxeval"= 160000,"local_opts" = local_opts,"print_level" = 0 )
We use NL_OPT_LD_MMA for local optimization and NL_OPT_GN_ISRES for overall optimization. You can set the tolerance to really low to get the best result. The number of iterations is set using maxeval. Setting tolerance to really low or the number of iterations to very high may result in the best approximation at the cost of increased computation time. Finally, we optimize
res <- nloptr ( x0 = x0, eval_f = eval_f, lb = lb, ub = ub, eval_g_ineq = eval_g_ineq, eval_g_eq = eval_g_eq, opts = opts)print(res)
In my case, the result came out to be (1 4.768461 3.78758 1.384204) which is fairly close to the ground truth.
Our objective function in this case is
subject to
with bounds on variables as
For this problem, the optimal solution is reached at (1, 1). Let’s write the code now.
# Objective functioneval_f <- function(x){return ( x[1]^2 + x[2]^2 )}# Inequality constraintseval_g_ineq <- function (x) {constr <- c(1 - x[1] - x[2],1 - x[1]^2 - x[2]^2,9 - 9*x[1]^2 - x[2]^2,x[2] - x[1]^2,x[1] - x[2]^2)return (constr)}# Lower and upper boundslb <- c(-50, -50)ub <- c(50, 50)# Initial valuesx0 <- c(3, 1)
Finally, define options for nloptr as follows:
opts <- list( "algorithm"= "NLOPT_GN_ISRES","xtol_rel"= 1.0e-15,"maxeval"= 160000,"tol_constraints_ineq" = rep( 1.0e-10, 5 ))
and then perform the optimization
res <- nloptr( x0 = x0, eval_f = eval_f, lb = lb, ub = ub, eval_g_ineq = eval_g_ineq, opts = opts )print(res)
With the specified tolerance and the number of iteration, I was able to achieve the optimal solution of (1, 1).
While I didn’t present the examples with multiple equality constraints, they are very similar to Example 4. However, be sure to select the optimization algorithm as NLOPT_GN_ISRES.
K. Svanberg, The method of moving asymptotes — a new method for structural optimization, International Journal for Numerical Methods in Engineering, 1987, 24, 359–373.Powell MJD (1994) Advances in Optimization and Numerical Analysis, Kluwer Academic, Dordrecht, A direct search optimization method that models the objective and constraint functions by linear interpolation, pp 51–67.https://people.cs.vt.edu/~ltw/lecture_notes/HPCS08tut.pdfThomas P. Runarsson and Xin Yao, “Stochastic ranking for constrained evolutionary optimization,” IEEE Trans. Evolutionary Computation, vol. 4 (no. 3), pp. 284–294 (2000).https://www.him.uni-bonn.de/fileadmin/him/Section6_HIM_v1.pdfhttps://people.kth.se/~krille/mmagcmma.pdfhttps://cran.r-project.org/web/packages/nloptr/vignettes/nloptr.pdfhttp://faculty.cas.usf.edu/jkwilde/mathcamp/Constrained_Optimization.pdfhttps://nlopt.readthedocs.io/en/latest/
K. Svanberg, The method of moving asymptotes — a new method for structural optimization, International Journal for Numerical Methods in Engineering, 1987, 24, 359–373.
Powell MJD (1994) Advances in Optimization and Numerical Analysis, Kluwer Academic, Dordrecht, A direct search optimization method that models the objective and constraint functions by linear interpolation, pp 51–67.
https://people.cs.vt.edu/~ltw/lecture_notes/HPCS08tut.pdf
Thomas P. Runarsson and Xin Yao, “Stochastic ranking for constrained evolutionary optimization,” IEEE Trans. Evolutionary Computation, vol. 4 (no. 3), pp. 284–294 (2000).
https://www.him.uni-bonn.de/fileadmin/him/Section6_HIM_v1.pdf
https://people.kth.se/~krille/mmagcmma.pdf
https://cran.r-project.org/web/packages/nloptr/vignettes/nloptr.pdf
http://faculty.cas.usf.edu/jkwilde/mathcamp/Constrained_Optimization.pdf
https://nlopt.readthedocs.io/en/latest/
If this article benefits you, please use the following citations for referencing my work:
Rahul Bhadani. Nonlinear Optimization in R using nlopt. arXiv preprint arXiv:2101.02912, 2021.
or
@article{bhadani2021nonlinear, title={Nonlinear Optimization in R using nlopt}, author={Rahul Bhadani}, year={2021}, eprint={2101.02912}, archivePrefix={arXiv}, primaryClass={math.OC}, journal={arXiv preprint arXiv:2101.02912},} | [
{
"code": null,
"e": 919,
"s": 171,
"text": "Often in physical science research, we end up with a hard problem of optimizing a function (called objective) that needs to satisfy a range of constraints — linear or non-linear equalities and inequalities. The optimizers usually also have to adhere to the upper and lower bound. I recently worked on a similar problem in Quantum Information Science (QIS) where I attempted to optimize a non-linear function based on a few constraints dictated by rules of physics and mathematics. Interested readers may find my work on Constellation Optimization for Phase-Shift Keying Coherent States With Displacement Receiver to Maximize Mutual Information where I optimized mutual information for QuadriPhase-Shift Keying (QPSK) based on a set of constraints."
},
{
"code": null,
"e": 939,
"s": 919,
"text": "ieeexplore.ieee.org"
},
{
"code": null,
"e": 1788,
"s": 939,
"text": "While chasing the problem of non-linear optimization with a set of constraints, I found out that not all optimization routines are created equally. There are several libraries available in different languages such as python (scipy.optimize), Matlab (fmincon), C++ (robotim, nlopt), and R (nloptr). While my list for optimization routine is not exhaustive, some of them are more reliable than others, some provide faster execution than others and some have better documentation. Based on several key factors, I find nloptr, implemented in the R language to be most suitable for nonlinear optimization. nloptr uses nlopt implemented in C++ as a backend. As a result, it provides the elegance of the R language and the speed of C++. The optimization procedure is performed quickly in a fraction of seconds even with a tolerance of the order of 10e-15."
},
{
"code": null,
"e": 1851,
"s": 1788,
"text": "A general nonlinear optimization problem usually have the form"
},
{
"code": null,
"e": 2664,
"s": 1851,
"text": "where f is an objective function, g defines a set of inequality constraints, h is a set of equality constraints. xL and xU are lower and upper bounds respectively. In the literature, several optimization algorithms have been presented. For example, MMA (Method of moving asymptotes)1 supports arbitrary nonlinear inequality constraints, (COBYLA) Constrained Optimization BY Linear Approximation2, (ORIG_DRIECT) DIRECT algorithm3. Optimization algorithms that also support nonlinear equality constraints include ISRES (Improved Stochastic Ranking Evolution Strategy)4, (AUGLAG) Augmented Lagrangian Algorithm5. A full list of such methods can be found on nlopt C++ reference page at https://nlopt.readthedocs.io/en/latest/NLopt_Reference/. nloptr uses one of these methods to solve the given optimization problem."
},
{
"code": null,
"e": 3022,
"s": 2664,
"text": "“MMA (Method of moving asymptotes) supports arbitrary nonlinear inequality constraints, (COBYLA) Constrained Optimization BY Linear Approximation, (ORIG_DRIECT) DIRECT algorithm. Optimization algorithms that also support nonlinear equality constraints include ISRES (Improved Stochastic Ranking Evolution Strategy), (AUGLAG) Augmented Lagrangian Algorithm.”"
},
{
"code": null,
"e": 3476,
"s": 3022,
"text": "In the rest of the article, I provide several examples of solving a constraint optimization problem using R. I personally use R Studio that combines R compiler and editor. R Studio also provides knitr tool which is great for writing documentation or articles with inline code which can also generate a latex source code and a pdf file. Most of the example presented here has been modified from test suites used to validate functions in nloptr R package."
},
{
"code": null,
"e": 3531,
"s": 3476,
"text": "Installation of nloptr in R is fairly straightforward."
},
{
"code": null,
"e": 3575,
"s": 3531,
"text": "install.packages(“nloptr”)library(‘nloptr’)"
},
{
"code": null,
"e": 3645,
"s": 3575,
"text": "In the first example, we will minimize the Rosenbrock Banana function"
},
{
"code": null,
"e": 3672,
"s": 3645,
"text": "whose gradient is given by"
},
{
"code": null,
"e": 3835,
"s": 3672,
"text": "However, not all the algorithms in nlopt require explicit gradient as we will see in further examples. Let’s define the objective function and its gradient first:"
},
{
"code": null,
"e": 4039,
"s": 3835,
"text": "eval_f <- function(x){ return ( 100 * (x[2] - x[1] * x[1])^2 + (1 - x[1])^2 )}eval_grad_f <- function(x) {return( c( -400 * x[1] * (x[2] - x[1] * x[1]) - 2 * (1 - x[1]),200 * (x[2] - x[1] * x[1]) ) )}"
},
{
"code": null,
"e": 4087,
"s": 4039,
"text": "We will also need initial values of optimizers:"
},
{
"code": null,
"e": 4106,
"s": 4087,
"text": "x0 <- c( -1.2, 1 )"
},
{
"code": null,
"e": 4225,
"s": 4106,
"text": "Before we run the minimization procedure, we need to specify which algorithm we will use. That can be done as follows:"
},
{
"code": null,
"e": 4286,
"s": 4225,
"text": "opts <- list(\"algorithm\"=\"NLOPT_LD_LBFGS\",\"xtol_rel\"=1.0e-8)"
},
{
"code": null,
"e": 4378,
"s": 4286,
"text": "Here, we will use the L-BFGS algorithm. Now we are ready to run the optimization procedure."
},
{
"code": null,
"e": 4482,
"s": 4378,
"text": "# solve Rosenbrock Banana functionres <- nloptr( x0=x0,eval_f=eval_f,eval_grad_f=eval_grad_f,opts=opts)"
},
{
"code": null,
"e": 4514,
"s": 4482,
"text": "We can see the result by typing"
},
{
"code": null,
"e": 4525,
"s": 4514,
"text": "print(res)"
},
{
"code": null,
"e": 4635,
"s": 4525,
"text": "The function is optimized at (1,1) which is the ground truth. Check yourself by running the code in R Studio."
},
{
"code": null,
"e": 4662,
"s": 4635,
"text": "The problem to minimize is"
},
{
"code": null,
"e": 4760,
"s": 4662,
"text": "with a1= 2, b1 = 0, a2 = −1, and b2 = 1. We re-arrange the constraints to have the form g(x) ≤ 0:"
},
{
"code": null,
"e": 4797,
"s": 4760,
"text": "First, define the objective function"
},
{
"code": null,
"e": 4870,
"s": 4797,
"text": "# objective functioneval_f0 <- function( x, a, b ){return( sqrt(x[2]) )}"
},
{
"code": null,
"e": 4890,
"s": 4870,
"text": "and constraints are"
},
{
"code": null,
"e": 4976,
"s": 4890,
"text": "# constraint functioneval_g0 <- function( x, a, b ) {return( (a*x[1] + b)^3 - x[2] )}"
},
{
"code": null,
"e": 4994,
"s": 4976,
"text": "Define parameters"
},
{
"code": null,
"e": 5038,
"s": 4994,
"text": "# define parametersa <- c(2,-1)b <- c(0, 1)"
},
{
"code": null,
"e": 5099,
"s": 5038,
"text": "Now solve using NLOPT_LN_COBYLA without gradient information"
},
{
"code": null,
"e": 5347,
"s": 5099,
"text": "# Solve using NLOPT_LN_COBYLA without gradient informationres1 <- nloptr( x0=c(1.234,5.678),eval_f=eval_f0,lb = c(-Inf,0),ub = c(Inf,Inf),eval_g_ineq = eval_g0,opts = list(\"algorithm\"=\"NLOPT_LN_COBYLA\",\"xtol_rel\"=1.0e-8),a = a,b = b )print( res1 )"
},
{
"code": null,
"e": 5410,
"s": 5347,
"text": "We want to solve the following constraint optimization problem"
},
{
"code": null,
"e": 5433,
"s": 5410,
"text": "subject to constraints"
},
{
"code": null,
"e": 5537,
"s": 5433,
"text": "For this example, the optimal solution is achieved at (1.00000000, 4.74299963, 3.82114998, 1.37940829)."
},
{
"code": null,
"e": 5897,
"s": 5537,
"text": "# Objective Functioneval_f <- function(x){return (x[1]*x[4]*(x[1] +x[2] + x[3] ) + x[3] )}# Inequality constraintseval_g_ineq <- function(x){return (25 - x[1]*x[2]*x[3]*x[4])}# Equality constraintseval_g_eq <- function(x){return ( x[1]^2 + x[2]^2 + x[3]^2 + x[4]^2 - 40 )}# Lower and upper boundslb <- c(1,1,1,1)ub <- c(5,5,5,5)#initial valuesx0 <- c(1,5,5,1)"
},
{
"code": null,
"e": 5951,
"s": 5897,
"text": "We will also need to define options for optimizations"
},
{
"code": null,
"e": 6178,
"s": 5951,
"text": "# Set optimization options.local_opts <- list( \"algorithm\" = \"NLOPT_LD_MMA\", \"xtol_rel\" = 1.0e-15 )opts <- list( \"algorithm\"= \"NLOPT_GN_ISRES\",\"xtol_rel\"= 1.0e-15,\"maxeval\"= 160000,\"local_opts\" = local_opts,\"print_level\" = 0 )"
},
{
"code": null,
"e": 6553,
"s": 6178,
"text": "We use NL_OPT_LD_MMA for local optimization and NL_OPT_GN_ISRES for overall optimization. You can set the tolerance to really low to get the best result. The number of iterations is set using maxeval. Setting tolerance to really low or the number of iterations to very high may result in the best approximation at the cost of increased computation time. Finally, we optimize"
},
{
"code": null,
"e": 6776,
"s": 6553,
"text": "res <- nloptr ( x0 = x0, eval_f = eval_f, lb = lb, ub = ub, eval_g_ineq = eval_g_ineq, eval_g_eq = eval_g_eq, opts = opts)print(res)"
},
{
"code": null,
"e": 6887,
"s": 6776,
"text": "In my case, the result came out to be (1 4.768461 3.78758 1.384204) which is fairly close to the ground truth."
},
{
"code": null,
"e": 6926,
"s": 6887,
"text": "Our objective function in this case is"
},
{
"code": null,
"e": 6937,
"s": 6926,
"text": "subject to"
},
{
"code": null,
"e": 6965,
"s": 6937,
"text": "with bounds on variables as"
},
{
"code": null,
"e": 7052,
"s": 6965,
"text": "For this problem, the optimal solution is reached at (1, 1). Let’s write the code now."
},
{
"code": null,
"e": 7374,
"s": 7052,
"text": "# Objective functioneval_f <- function(x){return ( x[1]^2 + x[2]^2 )}# Inequality constraintseval_g_ineq <- function (x) {constr <- c(1 - x[1] - x[2],1 - x[1]^2 - x[2]^2,9 - 9*x[1]^2 - x[2]^2,x[2] - x[1]^2,x[1] - x[2]^2)return (constr)}# Lower and upper boundslb <- c(-50, -50)ub <- c(50, 50)# Initial valuesx0 <- c(3, 1)"
},
{
"code": null,
"e": 7421,
"s": 7374,
"text": "Finally, define options for nloptr as follows:"
},
{
"code": null,
"e": 7547,
"s": 7421,
"text": "opts <- list( \"algorithm\"= \"NLOPT_GN_ISRES\",\"xtol_rel\"= 1.0e-15,\"maxeval\"= 160000,\"tol_constraints_ineq\" = rep( 1.0e-10, 5 ))"
},
{
"code": null,
"e": 7581,
"s": 7547,
"text": "and then perform the optimization"
},
{
"code": null,
"e": 7772,
"s": 7581,
"text": "res <- nloptr( x0 = x0, eval_f = eval_f, lb = lb, ub = ub, eval_g_ineq = eval_g_ineq, opts = opts )print(res)"
},
{
"code": null,
"e": 7884,
"s": 7772,
"text": "With the specified tolerance and the number of iteration, I was able to achieve the optimal solution of (1, 1)."
},
{
"code": null,
"e": 8065,
"s": 7884,
"text": "While I didn’t present the examples with multiple equality constraints, they are very similar to Example 4. However, be sure to select the optimization algorithm as NLOPT_GN_ISRES."
},
{
"code": null,
"e": 8957,
"s": 8065,
"text": "K. Svanberg, The method of moving asymptotes — a new method for structural optimization, International Journal for Numerical Methods in Engineering, 1987, 24, 359–373.Powell MJD (1994) Advances in Optimization and Numerical Analysis, Kluwer Academic, Dordrecht, A direct search optimization method that models the objective and constraint functions by linear interpolation, pp 51–67.https://people.cs.vt.edu/~ltw/lecture_notes/HPCS08tut.pdfThomas P. Runarsson and Xin Yao, “Stochastic ranking for constrained evolutionary optimization,” IEEE Trans. Evolutionary Computation, vol. 4 (no. 3), pp. 284–294 (2000).https://www.him.uni-bonn.de/fileadmin/him/Section6_HIM_v1.pdfhttps://people.kth.se/~krille/mmagcmma.pdfhttps://cran.r-project.org/web/packages/nloptr/vignettes/nloptr.pdfhttp://faculty.cas.usf.edu/jkwilde/mathcamp/Constrained_Optimization.pdfhttps://nlopt.readthedocs.io/en/latest/"
},
{
"code": null,
"e": 9125,
"s": 8957,
"text": "K. Svanberg, The method of moving asymptotes — a new method for structural optimization, International Journal for Numerical Methods in Engineering, 1987, 24, 359–373."
},
{
"code": null,
"e": 9342,
"s": 9125,
"text": "Powell MJD (1994) Advances in Optimization and Numerical Analysis, Kluwer Academic, Dordrecht, A direct search optimization method that models the objective and constraint functions by linear interpolation, pp 51–67."
},
{
"code": null,
"e": 9400,
"s": 9342,
"text": "https://people.cs.vt.edu/~ltw/lecture_notes/HPCS08tut.pdf"
},
{
"code": null,
"e": 9571,
"s": 9400,
"text": "Thomas P. Runarsson and Xin Yao, “Stochastic ranking for constrained evolutionary optimization,” IEEE Trans. Evolutionary Computation, vol. 4 (no. 3), pp. 284–294 (2000)."
},
{
"code": null,
"e": 9633,
"s": 9571,
"text": "https://www.him.uni-bonn.de/fileadmin/him/Section6_HIM_v1.pdf"
},
{
"code": null,
"e": 9676,
"s": 9633,
"text": "https://people.kth.se/~krille/mmagcmma.pdf"
},
{
"code": null,
"e": 9744,
"s": 9676,
"text": "https://cran.r-project.org/web/packages/nloptr/vignettes/nloptr.pdf"
},
{
"code": null,
"e": 9817,
"s": 9744,
"text": "http://faculty.cas.usf.edu/jkwilde/mathcamp/Constrained_Optimization.pdf"
},
{
"code": null,
"e": 9857,
"s": 9817,
"text": "https://nlopt.readthedocs.io/en/latest/"
},
{
"code": null,
"e": 9947,
"s": 9857,
"text": "If this article benefits you, please use the following citations for referencing my work:"
},
{
"code": null,
"e": 10042,
"s": 9947,
"text": "Rahul Bhadani. Nonlinear Optimization in R using nlopt. arXiv preprint arXiv:2101.02912, 2021."
},
{
"code": null,
"e": 10045,
"s": 10042,
"text": "or"
}
]
|
Min distance between two given nodes of a Binary Tree | Practice | GeeksforGeeks | Given a binary tree and two node values your task is to find the minimum distance between them.
Example 1:
Input:
1
/ \
2 3
a = 2, b = 3
Output: 2
Explanation: The tree formed is:
1
/ \
2 3
We need the distance between 2 and 3.
Being at node 2, we need to take two
steps ahead in order to reach node 3.
The path followed will be:
2 -> 1 -> 3. Hence, the result is 2.
Your Task:
You don't need to read input or print anything. Your task is to complete the function findDist() which takes the root node of the Tree and the two node values a and b as input parameters and returns the minimum distance between the nodes represented by the two given node values.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).
Constraints:
1 <= Number of nodes <= 104
1 <= Data of a node <= 105
Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.
0
tirtha19025681 week ago
class GfG {
int findDist(Node root, int a, int b) {
int ans = distance(root,a,b);
return ans;
}
int distance(Node root,int a,int b) {
if(root == null) return 0;
Node lca = lca(root,a,b);
if(lca == null) return 0;
int ans = helper(lca,a,b);
return ans;
}
int helper(Node lca,int a,int b) {
// dist b/w : (a - lca) + (b - lca)
int cnt1 = 0;
int cnt2 = 0;
cnt1 = dist(lca,a);
cnt2 = dist(lca,b);
return cnt1 + cnt2;
}
int dist(Node root, int x)
{
// Base case
if (root == null)
return -1;
// Initialize distance
int dist = -1;
// Check if x is present at root or in left
// subtree or right subtree.
if ((root.data == x) ||
(dist = dist(root.left, x)) >= 0 ||
(dist = dist(root.right, x)) >= 0)
return dist + 1;
return dist;
}
Node lca(Node root,int a,int b) {
if(root == null) return null;
if(root.data == a || root.data == b) return root;
Node left = lca(root.left,a,b);
Node right = lca(root.right,a,b);
if(left == null) return right;
else if(right == null) return left;
else return root;
}
}
0
ajaysingh74181 week ago
simple same logic as LCA
bool fill_path(Node* root , vector<int> &path , int n) { if(root == NULL) return false; path.push_back(root->data); if(root->data == n) return true; if(fill_path(root->left , path , n) || fill_path(root->right , path , n)) { return true; } path.pop_back(); return false; } int findDist(Node* root, int a, int b) { // Your code here vector<int> path1; vector<int> path2; fill_path(root , path1 , a); fill_path(root , path2 , b); int ans = 0; path1.resize(100 , 0); path2.resize(100 , 0); for(int i = 0; i < path1.size() && path2.size(); i ++) { if(path1[i] == 0 && path2[i] != 0) ans ++; else if(path1[i] != 0 && path2[i] == 0) ans ++; else if(path1[i] != path2[i]) ans += 2; if(path1[i] == 0 && path2[i] == 0) break; } if(ans == 0)return 1; return ans; }
+3
goswamikrunal85718652 weeks ago
The updated version of the code: It will work for sure:)
Please give an upvote if you liked the approach.
Same common ancestor approach, but to avoid duplicate values and get the nearest value of LCA, changed the logic in solve part.
class Solution{
Node* leastCommonAncestor(Node* root, int a, int b){
if(!root) return NULL;
if(root->data==a or root->data==b) return root;
Node* l = leastCommonAncestor(root->left, a, b);
Node* r = leastCommonAncestor(root->right, a, b);
if(l and r) return root;
if(l) return l;
return r;
}
int solve(Node* root, int a){
if(!root) return 0;
if(root->data == a) return 1;
int l = solve(root->left, a);
int r = solve(root->right, a);
if(!l and !r) return 0;
if(!l) return r+1;
if(!r) return l+1;
int minVal = min(l,r);
return minVal +1;
}
public:
/* Should return minimum distance between a and b
in a tree with given root*/
int findDist(Node* root, int a, int b) {
// Your code here
Node* lca = leastCommonAncestor(root, a, b);
int x = solve(lca, a);
int y = solve(lca, b);
return (x + y - 2);
}
};
+1
upadhyayabhi01072 weeks ago
class Solution{
public:
Node* lca(Node* root , int a , int b){
if(!root) return nullptr;
if(root->data == a || root->data == b){
return root;
}
Node* lst = lca(root->left , a , b);
Node* rst = lca(root->right , a , b);
if(!lst) return rst;
if(!rst) return lst;
return root;
}
void traverse(Node* root , Node* ancestor , int a , int b , int& l1 , int &l2 , int& l3 , int level){
if(root){
if(root->data == ancestor->data && l1 == -1){
l1 = level;
}
if(root->data == a && l2 == -1){
l2 = level;
}
if(root->data == b && l3 == -1){
l3 = level;
}
traverse(root->left , ancestor , a , b , l1 , l2 , l3 , level + 1);
traverse(root->right , ancestor , a , b , l1 , l2 , l3 , level + 1);
}
}
int findDist(Node* root, int a, int b) {
Node* ancestor = lca(root , a , b);
int l1 = -1 , l2 = -1 , l3 = -1;
traverse(root , ancestor , a , b , l1 , l2 , l3 , 0);
return (l3 + l2 - 2 * l1);
}
};
0
upadhyayabhi0107
This comment was deleted.
-1
apurvkumarak3 weeks ago
C++ Solution
bool route(Node * node,int goal,vector<int> & vec){
if(node != NULL){
vec.push_back(node->data);
if(node->data==goal){
return true;
}
bool res1=route(node->left,goal,vec);
if(res1){
return true;
}
bool res2=route(node->right,goal,vec);
if(res2){
return true;
}
vec.pop_back();
}
return false;
}
int findDist(Node* root, int a, int b) {
vector<int> r1;
route(root,a,r1);
vector<int> r2;
route(root,b,r2);
unordered_map<int,int> mp,mp1;
for(auto v:r1){
mp[v]++;
}
for(auto v:r2){
mp[v]++;
}
for(int i=r1.size()-1;i >=0;i--){
if(mp[r1[i]] > 1){
mp1[r1[i]]=r1.size()-i-1;
}
}
int res=INT_MAX;
for(int i=r2.size()-1;i >=0;i--){
if(mp[r2[i]] > 1){
int temp=r2.size()-i-1+mp1[r2[i]];
res=std::min(res,temp);
}
}
return res;
}
0
6288264 weeks ago
Base on the observation that
path(a→b) equals to
path(root→a) + path(root→b) - 2 * path(root→lowest_common_ancestor(a, b))
Happy coding.
bool find(Node* root, int x, vector<int> &path)
{
if (! root)
return false;
if (root->data == x)
return true;
path.push_back(0);
if (find(root->left, x, path))
return true;
path.back() = 1;
if (find(root->right, x, path))
return true;
path.pop_back();
return false;
}
int findDist(Node* root, int a, int b) {
vector<int> pa, pb;
find(root, a, pa);
find(root, b, pb);
int r = pa.size() + pb.size();
for (int i = 0;
i < pa.size() && i < pb.size() && pa[i] == pb[i];
++i, r -= 2)
;
return r;
}
0
0166621m4 weeks ago
class Solution{
int res,x,y;
int func(Node* root, int a, int b,int len=0)
{
if(root==NULL)
return -1;
int l=func(root->left,a,b,len+1), r = func(root->right,a,b,len+1);
if(root->data == a)
{
if(l==2)
{
res = y-len;
return -1;
}
if(r==2)
{
res = y - len;
return -1;
}
x=len;
// cout<<root->data<<" "<<len<<endl;
return 1;
}
if(root->data == b)
{
if(l==1)
{
res = x-len;
return -1;
}
if(r==1)
{
res = x - len;
return -1;
}
// cout<<root->data<<" "<<len<<endl;
y=len;
return 2;
}
if(l+r == 3)
{
res = x-len + y-len;
return -1;
}
if(l!=-1)
return l;
return r;
}
public:
/* Should return minimum distance between a and b
in a tree with given root*/
int findDist(Node* root, int a, int b) {
// Your code here
res=x=y=0;
func(root,a,b);
return res;
}
};
+1
satyamagarwal2491 month ago
class Solution:
def findDist(self,root,a,b):
self.visit =[False, False]
self.ans= None
ans = self.LCA(root, a, b)
if self.visit[0] and self.visit[1]:
return self.ans
elif self.visit[0]:
return self.find(root, b) - ans
elif self.visit[1]:
return self.find(root, a) - ans
return None
def find(self, root, key):
if root is None:
return None
if root.data == key:
return 1
l = self.find(root.left, key)
if l is not None:
return l + 1
r = self.find(root.right, key)
if r is not None:
return r + 1
return None
def LCA(self, root, a, b):
if root is None:
return None
if root.data == a:
self.visit[0] = True
return 1
if root.data == b:
self.visit[1] = True
return 1
l = self.LCA(root.left, a, b)
r = self.LCA(root.right, a, b)
if l is not None and r is not None :
self.ans = l + r
return l + r
elif l is not None:
return 1 + l
elif r is not None:
return 1 + r
else:
return None
0
abrajput15061 month ago
void helper(Node* root,int a,int b,int &mn,
int &levelA,int &levelB,int level,Node* lca){
if(!root)
return;
if(root->data == a && levelA == -1)
levelA = level;
if(root->data == b && levelB == -1)
levelB = level;
helper(root->left,a,b,mn,levelA,levelB,level+1,lca);
helper(root->right,a,b,mn,levelA,levelB,level+1,lca);
if(levelA != -1 && levelB != -1 && lca == root){
mn = abs(levelA-level)+abs(levelB-level);
}
}
Node* lca(Node* root, int a, int b){
if(!root)
return root;
if(root->data == a || root->data == b)
return root;
Node* left = lca(root->left,a,b);
Node* right = lca(root->right,a,b);
if(left && right) return root;
return left ? left : right;
}
int findDist(Node* root, int a, int b) {
// Your code here
int mn = INT_MAX,levelA = -1,levelB = -1,level = 0;
helper(root,a,b,mn,levelA,levelB,0,lca(root,a,b));
return mn;
}
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": 334,
"s": 238,
"text": "Given a binary tree and two node values your task is to find the minimum distance between them."
},
{
"code": null,
"e": 345,
"s": 334,
"text": "Example 1:"
},
{
"code": null,
"e": 652,
"s": 345,
"text": "Input:\n 1\n / \\\n 2 3\na = 2, b = 3\nOutput: 2\nExplanation: The tree formed is:\n 1\n / \\ \n 2 3\nWe need the distance between 2 and 3.\nBeing at node 2, we need to take two\nsteps ahead in order to reach node 3.\nThe path followed will be:\n2 -> 1 -> 3. Hence, the result is 2. "
},
{
"code": null,
"e": 943,
"s": 652,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function findDist() which takes the root node of the Tree and the two node values a and b as input parameters and returns the minimum distance between the nodes represented by the two given node values."
},
{
"code": null,
"e": 1024,
"s": 943,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(Height of the Tree)."
},
{
"code": null,
"e": 1404,
"s": 1024,
"text": "Constraints:\n1 <= Number of nodes <= 104\n1 <= Data of a node <= 105\n\n\n\nNote:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code."
},
{
"code": null,
"e": 1406,
"s": 1404,
"text": "0"
},
{
"code": null,
"e": 1430,
"s": 1406,
"text": "tirtha19025681 week ago"
},
{
"code": null,
"e": 2557,
"s": 1430,
"text": "class GfG {\n int findDist(Node root, int a, int b) {\n int ans = distance(root,a,b);\n return ans;\n }\n \n int distance(Node root,int a,int b) {\n if(root == null) return 0;\n Node lca = lca(root,a,b);\n if(lca == null) return 0;\n int ans = helper(lca,a,b);\n \n return ans;\n}\n\n int helper(Node lca,int a,int b) {\n // dist b/w : (a - lca) + (b - lca)\n int cnt1 = 0;\n int cnt2 = 0;\n cnt1 = dist(lca,a);\n cnt2 = dist(lca,b);\n \n return cnt1 + cnt2;\n}\n\n int dist(Node root, int x)\n{\n // Base case\n if (root == null)\n return -1;\n \n // Initialize distance\n int dist = -1;\n \n // Check if x is present at root or in left\n // subtree or right subtree.\n if ((root.data == x) ||\n (dist = dist(root.left, x)) >= 0 ||\n (dist = dist(root.right, x)) >= 0)\n return dist + 1;\n \n return dist;\n}\n\n Node lca(Node root,int a,int b) {\n if(root == null) return null;\n if(root.data == a || root.data == b) return root;\n \n Node left = lca(root.left,a,b);\n Node right = lca(root.right,a,b);\n \n if(left == null) return right;\n else if(right == null) return left;\n \n else return root;\n}\n\n \n}"
},
{
"code": null,
"e": 2559,
"s": 2557,
"text": "0"
},
{
"code": null,
"e": 2583,
"s": 2559,
"text": "ajaysingh74181 week ago"
},
{
"code": null,
"e": 2609,
"s": 2583,
"text": "simple same logic as LCA "
},
{
"code": null,
"e": 3710,
"s": 2611,
"text": "bool fill_path(Node* root , vector<int> &path , int n) { if(root == NULL) return false; path.push_back(root->data); if(root->data == n) return true; if(fill_path(root->left , path , n) || fill_path(root->right , path , n)) { return true; } path.pop_back(); return false; } int findDist(Node* root, int a, int b) { // Your code here vector<int> path1; vector<int> path2; fill_path(root , path1 , a); fill_path(root , path2 , b); int ans = 0; path1.resize(100 , 0); path2.resize(100 , 0); for(int i = 0; i < path1.size() && path2.size(); i ++) { if(path1[i] == 0 && path2[i] != 0) ans ++; else if(path1[i] != 0 && path2[i] == 0) ans ++; else if(path1[i] != path2[i]) ans += 2; if(path1[i] == 0 && path2[i] == 0) break; } if(ans == 0)return 1; return ans; }"
},
{
"code": null,
"e": 3713,
"s": 3710,
"text": "+3"
},
{
"code": null,
"e": 3745,
"s": 3713,
"text": "goswamikrunal85718652 weeks ago"
},
{
"code": null,
"e": 3802,
"s": 3745,
"text": "The updated version of the code: It will work for sure:)"
},
{
"code": null,
"e": 3851,
"s": 3802,
"text": "Please give an upvote if you liked the approach."
},
{
"code": null,
"e": 3979,
"s": 3851,
"text": "Same common ancestor approach, but to avoid duplicate values and get the nearest value of LCA, changed the logic in solve part."
},
{
"code": null,
"e": 4961,
"s": 3979,
"text": "\nclass Solution{\n Node* leastCommonAncestor(Node* root, int a, int b){\n if(!root) return NULL;\n if(root->data==a or root->data==b) return root;\n Node* l = leastCommonAncestor(root->left, a, b);\n Node* r = leastCommonAncestor(root->right, a, b);\n \n if(l and r) return root;\n if(l) return l;\n return r;\n }\n int solve(Node* root, int a){\n if(!root) return 0;\n if(root->data == a) return 1;\n int l = solve(root->left, a);\n int r = solve(root->right, a);\n if(!l and !r) return 0;\n if(!l) return r+1;\n if(!r) return l+1;\n int minVal = min(l,r);\n return minVal +1;\n }\n public:\n /* Should return minimum distance between a and b\n in a tree with given root*/\n int findDist(Node* root, int a, int b) {\n // Your code here\n Node* lca = leastCommonAncestor(root, a, b);\n int x = solve(lca, a);\n int y = solve(lca, b);\n return (x + y - 2);\n }\n};"
},
{
"code": null,
"e": 4966,
"s": 4963,
"text": "+1"
},
{
"code": null,
"e": 4994,
"s": 4966,
"text": "upadhyayabhi01072 weeks ago"
},
{
"code": null,
"e": 6170,
"s": 4994,
"text": "class Solution{\n public:\n Node* lca(Node* root , int a , int b){\n if(!root) return nullptr;\n if(root->data == a || root->data == b){\n return root;\n }\n Node* lst = lca(root->left , a , b);\n Node* rst = lca(root->right , a , b);\n if(!lst) return rst;\n if(!rst) return lst;\n return root;\n }\n void traverse(Node* root , Node* ancestor , int a , int b , int& l1 , int &l2 , int& l3 , int level){\n if(root){\n if(root->data == ancestor->data && l1 == -1){\n l1 = level;\n }\n if(root->data == a && l2 == -1){\n l2 = level;\n }\n if(root->data == b && l3 == -1){\n l3 = level;\n }\n traverse(root->left , ancestor , a , b , l1 , l2 , l3 , level + 1);\n traverse(root->right , ancestor , a , b , l1 , l2 , l3 , level + 1);\n }\n }\n int findDist(Node* root, int a, int b) {\n Node* ancestor = lca(root , a , b);\n int l1 = -1 , l2 = -1 , l3 = -1;\n traverse(root , ancestor , a , b , l1 , l2 , l3 , 0);\n return (l3 + l2 - 2 * l1);\n }\n};"
},
{
"code": null,
"e": 6172,
"s": 6170,
"text": "0"
},
{
"code": null,
"e": 6189,
"s": 6172,
"text": "upadhyayabhi0107"
},
{
"code": null,
"e": 6215,
"s": 6189,
"text": "This comment was deleted."
},
{
"code": null,
"e": 6218,
"s": 6215,
"text": "-1"
},
{
"code": null,
"e": 6242,
"s": 6218,
"text": "apurvkumarak3 weeks ago"
},
{
"code": null,
"e": 6256,
"s": 6242,
"text": "C++ Solution "
},
{
"code": null,
"e": 7423,
"s": 6256,
"text": " bool route(Node * node,int goal,vector<int> & vec){\n if(node != NULL){\n vec.push_back(node->data);\n if(node->data==goal){\n return true;\n }\n bool res1=route(node->left,goal,vec);\n if(res1){\n return true;\n }\n bool res2=route(node->right,goal,vec);\n if(res2){\n return true;\n }\n vec.pop_back();\n }\n return false;\n }\n int findDist(Node* root, int a, int b) {\n vector<int> r1;\n route(root,a,r1);\n vector<int> r2;\n route(root,b,r2);\n unordered_map<int,int> mp,mp1;\n for(auto v:r1){\n mp[v]++;\n }\n for(auto v:r2){\n mp[v]++;\n }\n for(int i=r1.size()-1;i >=0;i--){\n if(mp[r1[i]] > 1){\n mp1[r1[i]]=r1.size()-i-1;\n }\n }\n int res=INT_MAX;\n for(int i=r2.size()-1;i >=0;i--){\n if(mp[r2[i]] > 1){\n int temp=r2.size()-i-1+mp1[r2[i]];\n res=std::min(res,temp);\n }\n }\n return res;\n }"
},
{
"code": null,
"e": 7425,
"s": 7423,
"text": "0"
},
{
"code": null,
"e": 7443,
"s": 7425,
"text": "6288264 weeks ago"
},
{
"code": null,
"e": 7473,
"s": 7443,
"text": "Base on the observation that "
},
{
"code": null,
"e": 7498,
"s": 7473,
"text": " path(a→b) equals to "
},
{
"code": null,
"e": 7576,
"s": 7498,
"text": " path(root→a) + path(root→b) - 2 * path(root→lowest_common_ancestor(a, b))"
},
{
"code": null,
"e": 7590,
"s": 7576,
"text": "Happy coding."
},
{
"code": null,
"e": 8135,
"s": 7590,
"text": "bool find(Node* root, int x, vector<int> &path)\n{\n\tif (! root)\n\t\treturn false;\n\t\t\n\tif (root->data == x)\n\t\treturn true;\n\t\t\n\tpath.push_back(0);\n\t\n\tif (find(root->left, x, path))\n\t\treturn true;\n\t\t\n\tpath.back() = 1;\n\t\n\tif (find(root->right, x, path))\n\t\treturn true;\n\t\t\n\tpath.pop_back();\n\treturn false;\n}\n\nint findDist(Node* root, int a, int b) {\n\tvector<int> pa, pb;\n\t\n\tfind(root, a, pa);\n\tfind(root, b, pb);\n\t\n\tint r = pa.size() + pb.size();\n\t\n\tfor (int i = 0; \n\t\ti < pa.size() && i < pb.size() && pa[i] == pb[i]; \n\t\t++i, r -= 2)\n\t;\n\t\n\treturn r;\n}"
},
{
"code": null,
"e": 8137,
"s": 8135,
"text": "0"
},
{
"code": null,
"e": 8157,
"s": 8137,
"text": "0166621m4 weeks ago"
},
{
"code": null,
"e": 9495,
"s": 8157,
"text": "class Solution{\n int res,x,y;\n int func(Node* root, int a, int b,int len=0)\n {\n if(root==NULL)\n return -1;\n \n int l=func(root->left,a,b,len+1), r = func(root->right,a,b,len+1);\n if(root->data == a)\n {\n if(l==2)\n {\n \n res = y-len;\n return -1;\n }\n if(r==2)\n {\n res = y - len;\n return -1;\n }\n x=len;\n // cout<<root->data<<\" \"<<len<<endl;\n return 1;\n }\n if(root->data == b)\n {\n if(l==1)\n {\n res = x-len;\n return -1;\n }\n if(r==1)\n {\n res = x - len;\n return -1;\n }\n // cout<<root->data<<\" \"<<len<<endl;\n y=len;\n return 2;\n }\n \n if(l+r == 3)\n {\n res = x-len + y-len;\n return -1;\n }\n if(l!=-1)\n return l;\n return r;\n }\n public:\n /* Should return minimum distance between a and b\n in a tree with given root*/\n int findDist(Node* root, int a, int b) {\n // Your code here\n res=x=y=0;\n func(root,a,b);\n return res;\n }\n};"
},
{
"code": null,
"e": 9498,
"s": 9495,
"text": "+1"
},
{
"code": null,
"e": 9526,
"s": 9498,
"text": "satyamagarwal2491 month ago"
},
{
"code": null,
"e": 10864,
"s": 9526,
"text": "class Solution:\n \n def findDist(self,root,a,b):\n self.visit =[False, False]\n self.ans= None\n ans = self.LCA(root, a, b)\n if self.visit[0] and self.visit[1]:\n return self.ans\n elif self.visit[0]:\n return self.find(root, b) - ans \n elif self.visit[1]:\n return self.find(root, a) - ans \n return None\n \n def find(self, root, key):\n if root is None:\n return None\n if root.data == key:\n return 1\n l = self.find(root.left, key)\n if l is not None:\n return l + 1\n r = self.find(root.right, key)\n if r is not None:\n return r + 1\n return None\n \n \n \n def LCA(self, root, a, b):\n if root is None:\n return None\n if root.data == a:\n self.visit[0] = True\n return 1\n if root.data == b:\n self.visit[1] = True\n return 1\n \n l = self.LCA(root.left, a, b)\n r = self.LCA(root.right, a, b)\n \n if l is not None and r is not None :\n self.ans = l + r\n return l + r\n elif l is not None:\n return 1 + l\n elif r is not None:\n return 1 + r\n else:\n return None\n "
},
{
"code": null,
"e": 10866,
"s": 10864,
"text": "0"
},
{
"code": null,
"e": 10890,
"s": 10866,
"text": "abrajput15061 month ago"
},
{
"code": null,
"e": 12060,
"s": 10890,
"text": "void helper(Node* root,int a,int b,int &mn,\n int &levelA,int &levelB,int level,Node* lca){\n if(!root)\n return;\n \n if(root->data == a && levelA == -1)\n levelA = level;\n if(root->data == b && levelB == -1)\n levelB = level;\n \n \n helper(root->left,a,b,mn,levelA,levelB,level+1,lca);\n helper(root->right,a,b,mn,levelA,levelB,level+1,lca); \n \n if(levelA != -1 && levelB != -1 && lca == root){\n mn = abs(levelA-level)+abs(levelB-level);\n \n }\n \n }\n Node* lca(Node* root, int a, int b){\n if(!root)\n return root;\n if(root->data == a || root->data == b)\n return root;\n \n Node* left = lca(root->left,a,b);\n Node* right = lca(root->right,a,b);\n \n if(left && right) return root;\n return left ? left : right;\n }\n int findDist(Node* root, int a, int b) {\n // Your code here\n int mn = INT_MAX,levelA = -1,levelB = -1,level = 0;\n helper(root,a,b,mn,levelA,levelB,0,lca(root,a,b));\n return mn;\n }"
},
{
"code": null,
"e": 12206,
"s": 12060,
"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": 12242,
"s": 12206,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 12252,
"s": 12242,
"text": "\nProblem\n"
},
{
"code": null,
"e": 12262,
"s": 12252,
"text": "\nContest\n"
},
{
"code": null,
"e": 12325,
"s": 12262,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 12473,
"s": 12325,
"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": 12681,
"s": 12473,
"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": 12787,
"s": 12681,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
Design Pattern - Service Locator Pattern | The service locator design pattern is used when we want to locate various services using JNDI lookup. Considering high cost of looking up JNDI for a service, Service Locator pattern makes use of caching technique. For the first time a service is required, Service Locator looks up in JNDI and caches the service object. Further lookup or same service via Service Locator is done in its cache which improves the performance of application to great extent. Following are the entities of this type of design pattern.
Service - Actual Service which will process the request. Reference of such service is to be looked upon in JNDI server.
Service - Actual Service which will process the request. Reference of such service is to be looked upon in JNDI server.
Context / Initial Context - JNDI Context carries the reference to service used for lookup purpose.
Context / Initial Context - JNDI Context carries the reference to service used for lookup purpose.
Service Locator - Service Locator is a single point of contact to get services by JNDI lookup caching the services.
Service Locator - Service Locator is a single point of contact to get services by JNDI lookup caching the services.
Cache - Cache to store references of services to reuse them
Cache - Cache to store references of services to reuse them
Client - Client is the object that invokes the services via ServiceLocator.
Client - Client is the object that invokes the services via ServiceLocator.
We are going to create a ServiceLocator,InitialContext, Cache, Service as various objects representing our entities.Service1 and Service2 represent concrete services.
ServiceLocatorPatternDemo, our demo class, is acting as a client here and will use ServiceLocator to demonstrate Service Locator Design Pattern.
Create Service interface.
Service.java
public interface Service {
public String getName();
public void execute();
}
Create concrete services.
Service1.java
public class Service1 implements Service {
public void execute(){
System.out.println("Executing Service1");
}
@Override
public String getName() {
return "Service1";
}
}
Service2.java
public class Service2 implements Service {
public void execute(){
System.out.println("Executing Service2");
}
@Override
public String getName() {
return "Service2";
}
}
Create InitialContext for JNDI lookup
InitialContext.java
public class InitialContext {
public Object lookup(String jndiName){
if(jndiName.equalsIgnoreCase("SERVICE1")){
System.out.println("Looking up and creating a new Service1 object");
return new Service1();
}
else if (jndiName.equalsIgnoreCase("SERVICE2")){
System.out.println("Looking up and creating a new Service2 object");
return new Service2();
}
return null;
}
}
Create Cache
Cache.java
import java.util.ArrayList;
import java.util.List;
public class Cache {
private List<Service> services;
public Cache(){
services = new ArrayList<Service>();
}
public Service getService(String serviceName){
for (Service service : services) {
if(service.getName().equalsIgnoreCase(serviceName)){
System.out.println("Returning cached " + serviceName + " object");
return service;
}
}
return null;
}
public void addService(Service newService){
boolean exists = false;
for (Service service : services) {
if(service.getName().equalsIgnoreCase(newService.getName())){
exists = true;
}
}
if(!exists){
services.add(newService);
}
}
}
Create Service Locator
ServiceLocator.java
public class ServiceLocator {
private static Cache cache;
static {
cache = new Cache();
}
public static Service getService(String jndiName){
Service service = cache.getService(jndiName);
if(service != null){
return service;
}
InitialContext context = new InitialContext();
Service service1 = (Service)context.lookup(jndiName);
cache.addService(service1);
return service1;
}
}
Use the ServiceLocator to demonstrate Service Locator Design Pattern.
ServiceLocatorPatternDemo.java
public class ServiceLocatorPatternDemo {
public static void main(String[] args) {
Service service = ServiceLocator.getService("Service1");
service.execute();
service = ServiceLocator.getService("Service2");
service.execute();
service = ServiceLocator.getService("Service1");
service.execute();
service = ServiceLocator.getService("Service2");
service.execute();
}
}
Verify the output.
Looking up and creating a new Service1 object
Executing Service1
Looking up and creating a new Service2 object
Executing Service2
Returning cached Service1 object
Executing Service1
Returning cached Service2 object
Executing Service2
102 Lectures
10 hours
Arnab Chakraborty
30 Lectures
3 hours
Arnab Chakraborty
31 Lectures
4 hours
Arnab Chakraborty
43 Lectures
1.5 hours
Manoj Kumar
7 Lectures
1 hours
Zach Miller
54 Lectures
4 hours
Sasha Miller
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3265,
"s": 2751,
"text": "The service locator design pattern is used when we want to locate various services using JNDI lookup. Considering high cost of looking up JNDI for a service, Service Locator pattern makes use of caching technique. For the first time a service is required, Service Locator looks up in JNDI and caches the service object. Further lookup or same service via Service Locator is done in its cache which improves the performance of application to great extent. Following are the entities of this type of design pattern."
},
{
"code": null,
"e": 3385,
"s": 3265,
"text": "Service - Actual Service which will process the request. Reference of such service is to be looked upon in JNDI server."
},
{
"code": null,
"e": 3505,
"s": 3385,
"text": "Service - Actual Service which will process the request. Reference of such service is to be looked upon in JNDI server."
},
{
"code": null,
"e": 3604,
"s": 3505,
"text": "Context / Initial Context - JNDI Context carries the reference to service used for lookup purpose."
},
{
"code": null,
"e": 3703,
"s": 3604,
"text": "Context / Initial Context - JNDI Context carries the reference to service used for lookup purpose."
},
{
"code": null,
"e": 3819,
"s": 3703,
"text": "Service Locator - Service Locator is a single point of contact to get services by JNDI lookup caching the services."
},
{
"code": null,
"e": 3935,
"s": 3819,
"text": "Service Locator - Service Locator is a single point of contact to get services by JNDI lookup caching the services."
},
{
"code": null,
"e": 3995,
"s": 3935,
"text": "Cache - Cache to store references of services to reuse them"
},
{
"code": null,
"e": 4055,
"s": 3995,
"text": "Cache - Cache to store references of services to reuse them"
},
{
"code": null,
"e": 4131,
"s": 4055,
"text": "Client - Client is the object that invokes the services via ServiceLocator."
},
{
"code": null,
"e": 4207,
"s": 4131,
"text": "Client - Client is the object that invokes the services via ServiceLocator."
},
{
"code": null,
"e": 4374,
"s": 4207,
"text": "We are going to create a ServiceLocator,InitialContext, Cache, Service as various objects representing our entities.Service1 and Service2 represent concrete services."
},
{
"code": null,
"e": 4519,
"s": 4374,
"text": "ServiceLocatorPatternDemo, our demo class, is acting as a client here and will use ServiceLocator to demonstrate Service Locator Design Pattern."
},
{
"code": null,
"e": 4545,
"s": 4519,
"text": "Create Service interface."
},
{
"code": null,
"e": 4558,
"s": 4545,
"text": "Service.java"
},
{
"code": null,
"e": 4641,
"s": 4558,
"text": "public interface Service {\n public String getName();\n public void execute();\n}"
},
{
"code": null,
"e": 4667,
"s": 4641,
"text": "Create concrete services."
},
{
"code": null,
"e": 4681,
"s": 4667,
"text": "Service1.java"
},
{
"code": null,
"e": 4878,
"s": 4681,
"text": "public class Service1 implements Service {\n public void execute(){\n System.out.println(\"Executing Service1\");\n }\n\n @Override\n public String getName() {\n return \"Service1\";\n }\n}"
},
{
"code": null,
"e": 4892,
"s": 4878,
"text": "Service2.java"
},
{
"code": null,
"e": 5089,
"s": 4892,
"text": "public class Service2 implements Service {\n public void execute(){\n System.out.println(\"Executing Service2\");\n }\n\n @Override\n public String getName() {\n return \"Service2\";\n }\n}"
},
{
"code": null,
"e": 5127,
"s": 5089,
"text": "Create InitialContext for JNDI lookup"
},
{
"code": null,
"e": 5147,
"s": 5127,
"text": "InitialContext.java"
},
{
"code": null,
"e": 5591,
"s": 5147,
"text": "public class InitialContext {\n public Object lookup(String jndiName){\n \n if(jndiName.equalsIgnoreCase(\"SERVICE1\")){\n System.out.println(\"Looking up and creating a new Service1 object\");\n return new Service1();\n }\n else if (jndiName.equalsIgnoreCase(\"SERVICE2\")){\n System.out.println(\"Looking up and creating a new Service2 object\");\n return new Service2();\n }\n return null;\t\t\n }\n}"
},
{
"code": null,
"e": 5604,
"s": 5591,
"text": "Create Cache"
},
{
"code": null,
"e": 5615,
"s": 5604,
"text": "Cache.java"
},
{
"code": null,
"e": 6413,
"s": 5615,
"text": "import java.util.ArrayList;\nimport java.util.List;\n\npublic class Cache {\n\n private List<Service> services;\n\n public Cache(){\n services = new ArrayList<Service>();\n }\n\n public Service getService(String serviceName){\n \n for (Service service : services) {\n if(service.getName().equalsIgnoreCase(serviceName)){\n System.out.println(\"Returning cached \" + serviceName + \" object\");\n return service;\n }\n }\n return null;\n }\n\n public void addService(Service newService){\n boolean exists = false;\n \n for (Service service : services) {\n if(service.getName().equalsIgnoreCase(newService.getName())){\n exists = true;\n }\n }\n if(!exists){\n services.add(newService);\n }\n }\n}"
},
{
"code": null,
"e": 6436,
"s": 6413,
"text": "Create Service Locator"
},
{
"code": null,
"e": 6456,
"s": 6436,
"text": "ServiceLocator.java"
},
{
"code": null,
"e": 6911,
"s": 6456,
"text": "public class ServiceLocator {\n private static Cache cache;\n\n static {\n cache = new Cache();\t\t\n }\n\n public static Service getService(String jndiName){\n\n Service service = cache.getService(jndiName);\n\n if(service != null){\n return service;\n }\n\n InitialContext context = new InitialContext();\n Service service1 = (Service)context.lookup(jndiName);\n cache.addService(service1);\n return service1;\n }\n}"
},
{
"code": null,
"e": 6981,
"s": 6911,
"text": "Use the ServiceLocator to demonstrate Service Locator Design Pattern."
},
{
"code": null,
"e": 7012,
"s": 6981,
"text": "ServiceLocatorPatternDemo.java"
},
{
"code": null,
"e": 7434,
"s": 7012,
"text": "public class ServiceLocatorPatternDemo {\n public static void main(String[] args) {\n Service service = ServiceLocator.getService(\"Service1\");\n service.execute();\n service = ServiceLocator.getService(\"Service2\");\n service.execute();\n service = ServiceLocator.getService(\"Service1\");\n service.execute();\n service = ServiceLocator.getService(\"Service2\");\n service.execute();\t\t\n }\n}"
},
{
"code": null,
"e": 7453,
"s": 7434,
"text": "Verify the output."
},
{
"code": null,
"e": 7690,
"s": 7453,
"text": "Looking up and creating a new Service1 object\nExecuting Service1\nLooking up and creating a new Service2 object\nExecuting Service2\nReturning cached Service1 object\nExecuting Service1\nReturning cached Service2 object\nExecuting Service2\n"
},
{
"code": null,
"e": 7725,
"s": 7690,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 7744,
"s": 7725,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7777,
"s": 7744,
"text": "\n 30 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 7796,
"s": 7777,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7829,
"s": 7796,
"text": "\n 31 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7848,
"s": 7829,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7883,
"s": 7848,
"text": "\n 43 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7896,
"s": 7883,
"text": " Manoj Kumar"
},
{
"code": null,
"e": 7928,
"s": 7896,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7941,
"s": 7928,
"text": " Zach Miller"
},
{
"code": null,
"e": 7974,
"s": 7941,
"text": "\n 54 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7988,
"s": 7974,
"text": " Sasha Miller"
},
{
"code": null,
"e": 7995,
"s": 7988,
"text": " Print"
},
{
"code": null,
"e": 8006,
"s": 7995,
"text": " Add Notes"
}
]
|
Comparing Pointers in Golang - GeeksforGeeks | 05 Sep, 2019
Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. Pointers in Golang are also termed as the special variables. The variables are used to store some data at a particular memory address in the system. The memory address is always found in hexadecimal format(starting with 0x like 0xFFAAF etc.).In Go language, you are allowed to compare two pointers with each other. Two pointers values are only equal when they point to the same value in the memory or if they are nil. You can perform a comparison on pointers with the help of == and != operators provided by the Go language:
1. == operator: This operator return true if both the pointer points to the same variable. Or return false if both the pointer points to different variables.
Syntax:
pointer_1 == pointer_2
Example:
// Go program to illustrate the// concept of comparing two pointerspackage main import "fmt" func main() { val1 := 2345 val2 := 567 // Creating and initializing pointers var p1 *int p1 = &val1 p2 := &val2 p3 := &val1 // Comparing pointers // with each other // Using == operator res1 := &p1 == &p2 fmt.Println("Is p1 pointer is equal to p2 pointer: ", res1) res2 := p1 == p2 fmt.Println("Is p1 pointer is equal to p2 pointer: ", res2) res3 := p1 == p3 fmt.Println("Is p1 pointer is equal to p3 pointer: ", res3) res4 := p2 == p3 fmt.Println("Is p2 pointer is equal to p3 pointer: ", res4) res5 := &p3 == &p1 fmt.Println("Is p3 pointer is equal to p1 pointer: ", res5)}
Output:
Is p1 pointer is equal to p2 pointer: false
Is p1 pointer is equal to p2 pointer: false
Is p1 pointer is equal to p3 pointer: true
Is p2 pointer is equal to p3 pointer: false
Is p3 pointer is equal to p1 pointer: false
2. != operator: This operator return false if both the pointer points to the same variable. Or return true if both the pointer points to different variables.
Syntax:
pointer_1 != pointer_2
Example:
// Go program to illustrate the // concept of comparing two pointerspackage main import "fmt" func main() { val1 := 2345 val2 := 567 // Creating and initializing pointers var p1 *int p1 = &val1 p2 := &val2 p3 := &val1 // Comparing pointers // with each other // Using != operator res1 := &p1 != &p2 fmt.Println("Is p1 pointer not equal to p2 pointer: ", res1) res2 := p1 != p2 fmt.Println("Is p1 pointer not equal to p2 pointer: ", res2) res3 := p1 != p3 fmt.Println("Is p1 pointer not equal to p3 pointer: ", res3) res4 := p2 != p3 fmt.Println("Is p2 pointer not equal to p3 pointer: ", res4) res5 := &p3 != &p1 fmt.Println("Is p3 pointer not equal to p1 pointer: ", res5)}
Output:
Is p1 pointer not equal to p2 pointer: true
Is p1 pointer not equal to p2 pointer: true
Is p1 pointer not equal to p3 pointer: false
Is p2 pointer not equal to p3 pointer: true
Is p3 pointer not equal to p1 pointer: true
Golang
Golang-Pointers
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to concatenate two strings in Golang
time.Sleep() Function in Golang With Examples
Time Formatting in Golang
strings.Contains Function in Golang with Examples
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Golang Maps
How to convert a string in lower case in Golang?
How to compare times in Golang?
Inheritance in GoLang | [
{
"code": null,
"e": 24906,
"s": 24878,
"text": "\n05 Sep, 2019"
},
{
"code": null,
"e": 25554,
"s": 24906,
"text": "Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. Pointers in Golang are also termed as the special variables. The variables are used to store some data at a particular memory address in the system. The memory address is always found in hexadecimal format(starting with 0x like 0xFFAAF etc.).In Go language, you are allowed to compare two pointers with each other. Two pointers values are only equal when they point to the same value in the memory or if they are nil. You can perform a comparison on pointers with the help of == and != operators provided by the Go language:"
},
{
"code": null,
"e": 25712,
"s": 25554,
"text": "1. == operator: This operator return true if both the pointer points to the same variable. Or return false if both the pointer points to different variables."
},
{
"code": null,
"e": 25720,
"s": 25712,
"text": "Syntax:"
},
{
"code": null,
"e": 25743,
"s": 25720,
"text": "pointer_1 == pointer_2"
},
{
"code": null,
"e": 25752,
"s": 25743,
"text": "Example:"
},
{
"code": "// Go program to illustrate the// concept of comparing two pointerspackage main import \"fmt\" func main() { val1 := 2345 val2 := 567 // Creating and initializing pointers var p1 *int p1 = &val1 p2 := &val2 p3 := &val1 // Comparing pointers // with each other // Using == operator res1 := &p1 == &p2 fmt.Println(\"Is p1 pointer is equal to p2 pointer: \", res1) res2 := p1 == p2 fmt.Println(\"Is p1 pointer is equal to p2 pointer: \", res2) res3 := p1 == p3 fmt.Println(\"Is p1 pointer is equal to p3 pointer: \", res3) res4 := p2 == p3 fmt.Println(\"Is p2 pointer is equal to p3 pointer: \", res4) res5 := &p3 == &p1 fmt.Println(\"Is p3 pointer is equal to p1 pointer: \", res5)}",
"e": 26498,
"s": 25752,
"text": null
},
{
"code": null,
"e": 26506,
"s": 26498,
"text": "Output:"
},
{
"code": null,
"e": 26731,
"s": 26506,
"text": "Is p1 pointer is equal to p2 pointer: false\nIs p1 pointer is equal to p2 pointer: false\nIs p1 pointer is equal to p3 pointer: true\nIs p2 pointer is equal to p3 pointer: false\nIs p3 pointer is equal to p1 pointer: false\n"
},
{
"code": null,
"e": 26891,
"s": 26733,
"text": "2. != operator: This operator return false if both the pointer points to the same variable. Or return true if both the pointer points to different variables."
},
{
"code": null,
"e": 26899,
"s": 26891,
"text": "Syntax:"
},
{
"code": null,
"e": 26922,
"s": 26899,
"text": "pointer_1 != pointer_2"
},
{
"code": null,
"e": 26931,
"s": 26922,
"text": "Example:"
},
{
"code": "// Go program to illustrate the // concept of comparing two pointerspackage main import \"fmt\" func main() { val1 := 2345 val2 := 567 // Creating and initializing pointers var p1 *int p1 = &val1 p2 := &val2 p3 := &val1 // Comparing pointers // with each other // Using != operator res1 := &p1 != &p2 fmt.Println(\"Is p1 pointer not equal to p2 pointer: \", res1) res2 := p1 != p2 fmt.Println(\"Is p1 pointer not equal to p2 pointer: \", res2) res3 := p1 != p3 fmt.Println(\"Is p1 pointer not equal to p3 pointer: \", res3) res4 := p2 != p3 fmt.Println(\"Is p2 pointer not equal to p3 pointer: \", res4) res5 := &p3 != &p1 fmt.Println(\"Is p3 pointer not equal to p1 pointer: \", res5)}",
"e": 27682,
"s": 26931,
"text": null
},
{
"code": null,
"e": 27690,
"s": 27682,
"text": "Output:"
},
{
"code": null,
"e": 27917,
"s": 27690,
"text": "Is p1 pointer not equal to p2 pointer: true\nIs p1 pointer not equal to p2 pointer: true\nIs p1 pointer not equal to p3 pointer: false\nIs p2 pointer not equal to p3 pointer: true\nIs p3 pointer not equal to p1 pointer: true\n"
},
{
"code": null,
"e": 27924,
"s": 27917,
"text": "Golang"
},
{
"code": null,
"e": 27940,
"s": 27924,
"text": "Golang-Pointers"
},
{
"code": null,
"e": 27952,
"s": 27940,
"text": "Go Language"
},
{
"code": null,
"e": 28050,
"s": 27952,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28102,
"s": 28050,
"text": "Different ways to concatenate two strings in Golang"
},
{
"code": null,
"e": 28148,
"s": 28102,
"text": "time.Sleep() Function in Golang With Examples"
},
{
"code": null,
"e": 28174,
"s": 28148,
"text": "Time Formatting in Golang"
},
{
"code": null,
"e": 28224,
"s": 28174,
"text": "strings.Contains Function in Golang with Examples"
},
{
"code": null,
"e": 28275,
"s": 28224,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 28322,
"s": 28275,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 28334,
"s": 28322,
"text": "Golang Maps"
},
{
"code": null,
"e": 28383,
"s": 28334,
"text": "How to convert a string in lower case in Golang?"
},
{
"code": null,
"e": 28415,
"s": 28383,
"text": "How to compare times in Golang?"
}
]
|
What is Quadrant Analysis & How to do it in Python | by Abhijith Chandradas | Towards Data Science | A Quadrant Analysis chart is a very common tool used for decision making especially in business setting.A Quadrant chart is technically a scatter plot that is divided into four sections or quadrants, hence the name. In a quadrant analysis, performance under two parameters are assessed for each entity. Depending on how an entity performs under either of the KPIs, the entity is grouped into either of the quadrants. After identifying which quadrant the entity belongs to, actions can be taken to improve performance under relevant KPIs.
Preparation of Quadrant Analysis in data visualization tools like Power BI and Tableau are very straight forward. However the process is not so straight-forward in python.
We will use some KPIs from Human Development Index published by the United Nations Development Program, the full kaggle dataset can be accessed here.
Our data set consists of the following data:i. Country : Country Nameii. hdi : Human Development Indexiii. life_ex : Life Expectancy at Birthiv. gni_pc: Gross National Income (GNI) per Capita
There are three components for a Quadrant Analysis Chart:
i. AxisThe parameters(KPIs) the data is plotted in the graph based on are defined in the X and Y-axes. We will perform a quadrant analysis on how the G-20 nations are performing with respect to two KPIs:i. Gross National Income (GNI) per Capitaii. Life Expectancy at BirthX-axis represents the Gross National Income (GNI) per Capita and Y-axis represents the Life Expectancy at Birth, the data will be plotted to the appropriate quadrant based on these two metrics.
ii. BenchmarkThe threshold limit for the X and Y-axes can be defined as the Benchmark.This splits the axis into four quadrants. When profitability, growth, improvement etc. are considered y-o-y basis, generally ‘0’ is used as an objective benchmark. In some situations where relative comparison is required, mean or median values can also be used as benchmark.We will use mean values of KPIs as benchmarks.
iii. GroupingGrouping specifies how you want to group the data that is measured on the X and Y-axes. In our example the only grouping possible is country-wise. If other data is available, viz- Continent wise, Language wise or some other specific category, it can also used for grouping depending on the use case.
Preparing scatter plot with Gross National Income (GNI) per Capita as X-axis and Life Expectancy at Birth as Y-axis.Country Labels are also added to the scatter plot.
You can refer the following article on how to add labels to a scatter plot.
towardsdatascience.com
plt.figure(figsize=(12,8))sns.scatterplot(data=hdi_df, x='gni_pc', y='life_ex')plt.title(f"G 20 Countries : {abbr['gni_pc']} vs {abbr['life_ex']}")plt.xlabel(abbr['gni_pc'])plt.ylabel(abbr['life_ex']) for i in range(hdi_df.shape[0]): plt.text(hdi_df.gni_pc[i], y=hdi_df.life_ex[i], s=hdi_df.Country[i], alpha=0.8)plt.show()
The scatter plot can be converted into a Quadrant Analysis chart by adding the benchmark lines which divide the chart into 4 quadrants. The quadrants as labelled as Q1, Q2, Q3 and Q4 for later reference.Vertical and Horizontal lines corresponding to the mean values of KPIs on x-axis and y-axis respectively are added to the scatter plot.
Once the data is grouped into 4 quadrants, the groups can be analyzed depending on the use case. It can be used to find the profitable products, most productive worker, backward states etc. Once the quadrant of the entity is determined, concrete action can be taken to improve its KPIs to desirable level.
G-20 countries are grouped into 4 quadrants as shown above.The horizontal dotted line represents mean Life expectancy and the vertical one represents mean Gross National Income per capita.
Q1: GNI per capita > mean and Life expectancy > meanQ2: GNI per capita < mean and Life expectancy > meanQ3: GNI per capita < mean and Life expectancy < meanQ4: GNI per capita > mean and Life expectancy < mean
Countries in Q1 are performing better than the rest under bot the KPIs. Every country’s aim should be to reach Q1. (Thats my assumption)Mexico, in Q2 has life expectancy better than the mean value, however the country has to improve the GNI per capita.Countries in Q3 lags behind under both the parameters, these countries have to take concrete steps to improve to the standards of developed Nations.Saudi Arabia in Q4 has high per capita income but fares below average in terms of life expectancy. The country has to identify the factors affecting its citizens life expectancy and address them to reach Q1.
The notebook for this article is available in my Git Repo.
I hope you like the article, I would highly recommend signing up for Medium Membership to read more articles by me or stories by thousands of other authors on variety of topics. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium.
towardsdatascience.com
medium.datadriveninvestor.com
medium.com
You can check out the following article from my EPL Prediction series where I have used Quadrant Analysis to compare football teams based of xG Scored and xG conceded | [
{
"code": null,
"e": 709,
"s": 171,
"text": "A Quadrant Analysis chart is a very common tool used for decision making especially in business setting.A Quadrant chart is technically a scatter plot that is divided into four sections or quadrants, hence the name. In a quadrant analysis, performance under two parameters are assessed for each entity. Depending on how an entity performs under either of the KPIs, the entity is grouped into either of the quadrants. After identifying which quadrant the entity belongs to, actions can be taken to improve performance under relevant KPIs."
},
{
"code": null,
"e": 881,
"s": 709,
"text": "Preparation of Quadrant Analysis in data visualization tools like Power BI and Tableau are very straight forward. However the process is not so straight-forward in python."
},
{
"code": null,
"e": 1031,
"s": 881,
"text": "We will use some KPIs from Human Development Index published by the United Nations Development Program, the full kaggle dataset can be accessed here."
},
{
"code": null,
"e": 1223,
"s": 1031,
"text": "Our data set consists of the following data:i. Country : Country Nameii. hdi : Human Development Indexiii. life_ex : Life Expectancy at Birthiv. gni_pc: Gross National Income (GNI) per Capita"
},
{
"code": null,
"e": 1281,
"s": 1223,
"text": "There are three components for a Quadrant Analysis Chart:"
},
{
"code": null,
"e": 1747,
"s": 1281,
"text": "i. AxisThe parameters(KPIs) the data is plotted in the graph based on are defined in the X and Y-axes. We will perform a quadrant analysis on how the G-20 nations are performing with respect to two KPIs:i. Gross National Income (GNI) per Capitaii. Life Expectancy at BirthX-axis represents the Gross National Income (GNI) per Capita and Y-axis represents the Life Expectancy at Birth, the data will be plotted to the appropriate quadrant based on these two metrics."
},
{
"code": null,
"e": 2154,
"s": 1747,
"text": "ii. BenchmarkThe threshold limit for the X and Y-axes can be defined as the Benchmark.This splits the axis into four quadrants. When profitability, growth, improvement etc. are considered y-o-y basis, generally ‘0’ is used as an objective benchmark. In some situations where relative comparison is required, mean or median values can also be used as benchmark.We will use mean values of KPIs as benchmarks."
},
{
"code": null,
"e": 2467,
"s": 2154,
"text": "iii. GroupingGrouping specifies how you want to group the data that is measured on the X and Y-axes. In our example the only grouping possible is country-wise. If other data is available, viz- Continent wise, Language wise or some other specific category, it can also used for grouping depending on the use case."
},
{
"code": null,
"e": 2634,
"s": 2467,
"text": "Preparing scatter plot with Gross National Income (GNI) per Capita as X-axis and Life Expectancy at Birth as Y-axis.Country Labels are also added to the scatter plot."
},
{
"code": null,
"e": 2710,
"s": 2634,
"text": "You can refer the following article on how to add labels to a scatter plot."
},
{
"code": null,
"e": 2733,
"s": 2710,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3075,
"s": 2733,
"text": "plt.figure(figsize=(12,8))sns.scatterplot(data=hdi_df, x='gni_pc', y='life_ex')plt.title(f\"G 20 Countries : {abbr['gni_pc']} vs {abbr['life_ex']}\")plt.xlabel(abbr['gni_pc'])plt.ylabel(abbr['life_ex']) for i in range(hdi_df.shape[0]): plt.text(hdi_df.gni_pc[i], y=hdi_df.life_ex[i], s=hdi_df.Country[i], alpha=0.8)plt.show()"
},
{
"code": null,
"e": 3414,
"s": 3075,
"text": "The scatter plot can be converted into a Quadrant Analysis chart by adding the benchmark lines which divide the chart into 4 quadrants. The quadrants as labelled as Q1, Q2, Q3 and Q4 for later reference.Vertical and Horizontal lines corresponding to the mean values of KPIs on x-axis and y-axis respectively are added to the scatter plot."
},
{
"code": null,
"e": 3720,
"s": 3414,
"text": "Once the data is grouped into 4 quadrants, the groups can be analyzed depending on the use case. It can be used to find the profitable products, most productive worker, backward states etc. Once the quadrant of the entity is determined, concrete action can be taken to improve its KPIs to desirable level."
},
{
"code": null,
"e": 3909,
"s": 3720,
"text": "G-20 countries are grouped into 4 quadrants as shown above.The horizontal dotted line represents mean Life expectancy and the vertical one represents mean Gross National Income per capita."
},
{
"code": null,
"e": 4118,
"s": 3909,
"text": "Q1: GNI per capita > mean and Life expectancy > meanQ2: GNI per capita < mean and Life expectancy > meanQ3: GNI per capita < mean and Life expectancy < meanQ4: GNI per capita > mean and Life expectancy < mean"
},
{
"code": null,
"e": 4726,
"s": 4118,
"text": "Countries in Q1 are performing better than the rest under bot the KPIs. Every country’s aim should be to reach Q1. (Thats my assumption)Mexico, in Q2 has life expectancy better than the mean value, however the country has to improve the GNI per capita.Countries in Q3 lags behind under both the parameters, these countries have to take concrete steps to improve to the standards of developed Nations.Saudi Arabia in Q4 has high per capita income but fares below average in terms of life expectancy. The country has to identify the factors affecting its citizens life expectancy and address them to reach Q1."
},
{
"code": null,
"e": 4785,
"s": 4726,
"text": "The notebook for this article is available in my Git Repo."
},
{
"code": null,
"e": 5086,
"s": 4785,
"text": "I hope you like the article, I would highly recommend signing up for Medium Membership to read more articles by me or stories by thousands of other authors on variety of topics. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium."
},
{
"code": null,
"e": 5109,
"s": 5086,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5139,
"s": 5109,
"text": "medium.datadriveninvestor.com"
},
{
"code": null,
"e": 5150,
"s": 5139,
"text": "medium.com"
}
]
|
Angular7 - Directives | Directives in Angular is a js class, which is declared as @directive. We have 3 directives in Angular. The directives are listed below −
These form the main class having details of how the component should be processed, instantiated and used at runtime.
A structure directive basically deals with manipulating the dom elements. Structural directives have a * sign before the directive. For example, *ngIf and *ngFor.
Attribute directives deal with changing the look and behavior of the dom element. You can create your own directives as explained in the below section.
In this section, we will discuss about Custom Directives to be used in components. Custom directives are created by us and are not standard.
Let us see how to create the custom directive. We will create the directive using the command line. The command to create the directive using the command line is as follows −
ng g directive nameofthedirective
e.g
ng g directive changeText
It appears in the command line as given in the below code −
C:\projectA7\angular7-app>ng g directive changeText
CREATE src/app/change-text.directive.spec.ts (241 bytes)
CREATE src/app/change-text.directive.ts (149 bytes)
UPDATE src/app/app.module.ts (565 bytes)
The above files, i.e., change-text.directive.spec.ts and change-text.directive.ts get created and the app.module.ts file is updated.
app.module.ts
import { BrowserModule } from'@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NewCmpComponent } from'./new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
@NgModule({
declarations: [
AppComponent,
NewCmpComponent,
ChangeTextDirective
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
The ChangeTextDirective class is included in the declarations in the above file. The class is also imported from the file given below −
change-text.directive
import { Directive } from '@angular/core';
@Directive({
selector: '[changeText]'
})
export class ChangeTextDirective {
constructor() { }
}
The above file has a directive and it also has a selector property. Whatever we define in the selector, the same has to match in the view, where we assign the custom directive.
In the app.component.html view, let us add the directive as follows −
<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
<h1> Welcome to {{title}}. </h1>
</div>
<div style = "text-align:center">
<span changeText >Welcome to {{title}}.</span>
</div>
We will write the changes in change-text.directive.ts file as follows −
change-text.directive.ts
import { Directive, ElementRef} from '@angular/core';
@Directive({
selector: '[changeText]'
})
export class ChangeTextDirective {
constructor(Element: ElementRef) {
console.log(Element);
Element.nativeElement.innerText = "Text is changed by changeText Directive.";
}
}
In the above file, there is a class called ChangeTextDirective and a constructor, which takes the element of type ElementRef, which is mandatory. The element has all the details to which the Change Text directive is applied.
We have added the console.log element. The output of the same can be seen in the browser console. The text of the element is also changed as shown above.
Now, the browser will show the following −
The details of the element on which the directive selector is given in the console. Since we have added the changeText directive to a span tag, the details of the span element is displayed.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2198,
"s": 2061,
"text": "Directives in Angular is a js class, which is declared as @directive. We have 3 directives in Angular. The directives are listed below −"
},
{
"code": null,
"e": 2315,
"s": 2198,
"text": "These form the main class having details of how the component should be processed, instantiated and used at runtime."
},
{
"code": null,
"e": 2478,
"s": 2315,
"text": "A structure directive basically deals with manipulating the dom elements. Structural directives have a * sign before the directive. For example, *ngIf and *ngFor."
},
{
"code": null,
"e": 2630,
"s": 2478,
"text": "Attribute directives deal with changing the look and behavior of the dom element. You can create your own directives as explained in the below section."
},
{
"code": null,
"e": 2771,
"s": 2630,
"text": "In this section, we will discuss about Custom Directives to be used in components. Custom directives are created by us and are not standard."
},
{
"code": null,
"e": 2946,
"s": 2771,
"text": "Let us see how to create the custom directive. We will create the directive using the command line. The command to create the directive using the command line is as follows −"
},
{
"code": null,
"e": 3013,
"s": 2946,
"text": "ng g directive nameofthedirective \ne.g \nng g directive changeText\n"
},
{
"code": null,
"e": 3073,
"s": 3013,
"text": "It appears in the command line as given in the below code −"
},
{
"code": null,
"e": 3279,
"s": 3073,
"text": "C:\\projectA7\\angular7-app>ng g directive changeText \nCREATE src/app/change-text.directive.spec.ts (241 bytes) \nCREATE src/app/change-text.directive.ts (149 bytes) \nUPDATE src/app/app.module.ts (565 bytes)\n"
},
{
"code": null,
"e": 3412,
"s": 3279,
"text": "The above files, i.e., change-text.directive.spec.ts and change-text.directive.ts get created and the app.module.ts file is updated."
},
{
"code": null,
"e": 3426,
"s": 3412,
"text": "app.module.ts"
},
{
"code": null,
"e": 4021,
"s": 3426,
"text": "import { BrowserModule } from'@angular/platform-browser'; \nimport { NgModule } from '@angular/core';\nimport { AppRoutingModule } from './app-routing.module'; \nimport { AppComponent } from './app.component'; \nimport { NewCmpComponent } from'./new-cmp/new-cmp.component'; \nimport { ChangeTextDirective } from './change-text.directive';\n\n@NgModule({ \n declarations: [ \n AppComponent, \n NewCmpComponent, \n ChangeTextDirective \n ], \n imports: [ \n BrowserModule, \n AppRoutingModule \n ], \n providers: [], \n bootstrap: [AppComponent] \n}) \nexport class AppModule { }"
},
{
"code": null,
"e": 4157,
"s": 4021,
"text": "The ChangeTextDirective class is included in the declarations in the above file. The class is also imported from the file given below −"
},
{
"code": null,
"e": 4179,
"s": 4157,
"text": "change-text.directive"
},
{
"code": null,
"e": 4325,
"s": 4179,
"text": "import { Directive } from '@angular/core';\n\n@Directive({\n selector: '[changeText]'\n})\nexport class ChangeTextDirective {\n constructor() { }\n}"
},
{
"code": null,
"e": 4502,
"s": 4325,
"text": "The above file has a directive and it also has a selector property. Whatever we define in the selector, the same has to match in the view, where we assign the custom directive."
},
{
"code": null,
"e": 4572,
"s": 4502,
"text": "In the app.component.html view, let us add the directive as follows −"
},
{
"code": null,
"e": 4813,
"s": 4572,
"text": "<!--The content below is only a placeholder and can be replaced.--> \n<div style = \"text-align:center\"> \n <h1> Welcome to {{title}}. </h1> \n</div>\n<div style = \"text-align:center\"> \n <span changeText >Welcome to {{title}}.</span> \n</div>"
},
{
"code": null,
"e": 4885,
"s": 4813,
"text": "We will write the changes in change-text.directive.ts file as follows −"
},
{
"code": null,
"e": 4910,
"s": 4885,
"text": "change-text.directive.ts"
},
{
"code": null,
"e": 5200,
"s": 4910,
"text": "import { Directive, ElementRef} from '@angular/core';\n@Directive({\n selector: '[changeText]'\n})\nexport class ChangeTextDirective {\n constructor(Element: ElementRef) {\n console.log(Element);\n Element.nativeElement.innerText = \"Text is changed by changeText Directive.\";\n }\n}"
},
{
"code": null,
"e": 5425,
"s": 5200,
"text": "In the above file, there is a class called ChangeTextDirective and a constructor, which takes the element of type ElementRef, which is mandatory. The element has all the details to which the Change Text directive is applied."
},
{
"code": null,
"e": 5579,
"s": 5425,
"text": "We have added the console.log element. The output of the same can be seen in the browser console. The text of the element is also changed as shown above."
},
{
"code": null,
"e": 5622,
"s": 5579,
"text": "Now, the browser will show the following −"
},
{
"code": null,
"e": 5812,
"s": 5622,
"text": "The details of the element on which the directive selector is given in the console. Since we have added the changeText directive to a span tag, the details of the span element is displayed."
},
{
"code": null,
"e": 5847,
"s": 5812,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5861,
"s": 5847,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5896,
"s": 5861,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5910,
"s": 5896,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5945,
"s": 5910,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5965,
"s": 5945,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 6000,
"s": 5965,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6017,
"s": 6000,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6050,
"s": 6017,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6062,
"s": 6050,
"text": " Senol Atac"
},
{
"code": null,
"e": 6097,
"s": 6062,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6109,
"s": 6097,
"text": " Senol Atac"
},
{
"code": null,
"e": 6116,
"s": 6109,
"text": " Print"
},
{
"code": null,
"e": 6127,
"s": 6116,
"text": " Add Notes"
}
]
|
QR Code Generator using HTML, CSS and jQuery - GeeksforGeeks | 03 Aug, 2021
A QR code generator is an application that stores any required textual data into a QR code which can be later scanned with a QR code scanner to reveal the stored information. This QR Code can be used anywhere, for example, on a poster or website to allow users to get additional information. This application will allow the user to type in the data required and save it a PNG or SVG image of the QR code.
Approach: To generate the QR code, we will use the Google Charts API. Using jQuery, the QR code image to be displayed is updated according to the image returned by the API.
The API endpoint that would be used is given below.
https://chart.googleapis.com/chart?chs=150×150&cht=qr&chl=Hello%20world
Explanation of the URL:
The root URL for Google Chart Infographics is https://chart.googleapis.com/chart. This can be specified with the required parameters to ger the desired output.
The chs parameter denotes the size of the QR code image in pixels.
The cht parameter denotes the type of the image to be created. The value “qr” will be used to generate a QR Code.
The chl parameter denotes the text or URL data to be encoded in the QR code.
Example:
HTML
<!DOCTYPE html><html> <head> <!-- Include Bootstrap for styling --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" /> <style> .qr-code { max-width: 200px; margin: 10px; } </style> <title>QR Code Generator</title></head> <body> <div class="container-fluid"> <div class="text-center"> <!-- Get a Placeholder image initially, this will change according to the data entered later --> <img src="https://chart.googleapis.com/chart?cht=qr&chl=Hello+World&chs=160x160&chld=L|0" class="qr-code img-thumbnail img-responsive" /> </div> <div class="form-horizontal"> <div class="form-group"> <label class="control-label col-sm-2" for="content"> Content: </label> <div class="col-sm-10"> <!-- Input box to enter the required data --> <input type="text" size="60" maxlength="60" class="form-control" id="content" placeholder="Enter content" /> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <!-- Button to generate QR Code for the entered data --> <button type="button" class= "btn btn-default" id="generate"> Generate </button> </div> </div> </div> </div> <script src= "https://code.jquery.com/jquery-3.5.1.js"> </script> <script> // Function to HTML encode the text // This creates a new hidden element, // inserts the given text into it // and outputs it out as HTML function htmlEncode(value) { return $('<div/>').text(value) .html(); } $(function () { // Specify an onclick function // for the generate button $('#generate').click(function () { // Generate the link that would be // used to generate the QR Code // with the given data let finalURL ='https://chart.googleapis.com/chart?cht=qr&chl=' + htmlEncode($('#content').val()) + '&chs=160x160&chld=L|0' // Replace the src of the image with // the QR code image $('.qr-code').attr('src', finalURL); }); }); </script></body> </html>
Output:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Misc
HTML-Misc
jQuery-Misc
CSS
HTML
JQuery
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
How to set space between the flexbox ?
How to Upload Image into Database and Display it using PHP ?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
HTML Cheat Sheet - A Basic Guide to HTML | [
{
"code": null,
"e": 26178,
"s": 26150,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 26584,
"s": 26178,
"text": "A QR code generator is an application that stores any required textual data into a QR code which can be later scanned with a QR code scanner to reveal the stored information. This QR Code can be used anywhere, for example, on a poster or website to allow users to get additional information. This application will allow the user to type in the data required and save it a PNG or SVG image of the QR code. "
},
{
"code": null,
"e": 26757,
"s": 26584,
"text": "Approach: To generate the QR code, we will use the Google Charts API. Using jQuery, the QR code image to be displayed is updated according to the image returned by the API."
},
{
"code": null,
"e": 26809,
"s": 26757,
"text": "The API endpoint that would be used is given below."
},
{
"code": null,
"e": 26881,
"s": 26809,
"text": "https://chart.googleapis.com/chart?chs=150×150&cht=qr&chl=Hello%20world"
},
{
"code": null,
"e": 26905,
"s": 26881,
"text": "Explanation of the URL:"
},
{
"code": null,
"e": 27065,
"s": 26905,
"text": "The root URL for Google Chart Infographics is https://chart.googleapis.com/chart. This can be specified with the required parameters to ger the desired output."
},
{
"code": null,
"e": 27132,
"s": 27065,
"text": "The chs parameter denotes the size of the QR code image in pixels."
},
{
"code": null,
"e": 27246,
"s": 27132,
"text": "The cht parameter denotes the type of the image to be created. The value “qr” will be used to generate a QR Code."
},
{
"code": null,
"e": 27323,
"s": 27246,
"text": "The chl parameter denotes the text or URL data to be encoded in the QR code."
},
{
"code": null,
"e": 27332,
"s": 27323,
"text": "Example:"
},
{
"code": null,
"e": 27337,
"s": 27332,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Include Bootstrap for styling --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css\" /> <style> .qr-code { max-width: 200px; margin: 10px; } </style> <title>QR Code Generator</title></head> <body> <div class=\"container-fluid\"> <div class=\"text-center\"> <!-- Get a Placeholder image initially, this will change according to the data entered later --> <img src=\"https://chart.googleapis.com/chart?cht=qr&chl=Hello+World&chs=160x160&chld=L|0\" class=\"qr-code img-thumbnail img-responsive\" /> </div> <div class=\"form-horizontal\"> <div class=\"form-group\"> <label class=\"control-label col-sm-2\" for=\"content\"> Content: </label> <div class=\"col-sm-10\"> <!-- Input box to enter the required data --> <input type=\"text\" size=\"60\" maxlength=\"60\" class=\"form-control\" id=\"content\" placeholder=\"Enter content\" /> </div> </div> <div class=\"form-group\"> <div class=\"col-sm-offset-2 col-sm-10\"> <!-- Button to generate QR Code for the entered data --> <button type=\"button\" class= \"btn btn-default\" id=\"generate\"> Generate </button> </div> </div> </div> </div> <script src= \"https://code.jquery.com/jquery-3.5.1.js\"> </script> <script> // Function to HTML encode the text // This creates a new hidden element, // inserts the given text into it // and outputs it out as HTML function htmlEncode(value) { return $('<div/>').text(value) .html(); } $(function () { // Specify an onclick function // for the generate button $('#generate').click(function () { // Generate the link that would be // used to generate the QR Code // with the given data let finalURL ='https://chart.googleapis.com/chart?cht=qr&chl=' + htmlEncode($('#content').val()) + '&chs=160x160&chld=L|0' // Replace the src of the image with // the QR code image $('.qr-code').attr('src', finalURL); }); }); </script></body> </html>",
"e": 29629,
"s": 27337,
"text": null
},
{
"code": null,
"e": 29637,
"s": 29629,
"text": "Output:"
},
{
"code": null,
"e": 29905,
"s": 29637,
"text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples."
},
{
"code": null,
"e": 30042,
"s": 29905,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 30051,
"s": 30042,
"text": "CSS-Misc"
},
{
"code": null,
"e": 30061,
"s": 30051,
"text": "HTML-Misc"
},
{
"code": null,
"e": 30073,
"s": 30061,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 30077,
"s": 30073,
"text": "CSS"
},
{
"code": null,
"e": 30082,
"s": 30077,
"text": "HTML"
},
{
"code": null,
"e": 30089,
"s": 30082,
"text": "JQuery"
},
{
"code": null,
"e": 30106,
"s": 30089,
"text": "Web Technologies"
},
{
"code": null,
"e": 30133,
"s": 30106,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30138,
"s": 30133,
"text": "HTML"
},
{
"code": null,
"e": 30236,
"s": 30138,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30284,
"s": 30236,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 30321,
"s": 30284,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 30385,
"s": 30321,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 30424,
"s": 30385,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 30485,
"s": 30424,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 30545,
"s": 30485,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 30593,
"s": 30545,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 30646,
"s": 30593,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 30707,
"s": 30646,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
]
|
How to Add and Customize Back Button of Action Bar in Android? - GeeksforGeeks | 23 Feb, 2021
The action bar (sometimes referred to as the app bar), if it exists for an activity, will be at the top of the activity’s content area, typically directly underneath the status bar. It is a menu bar that runs across the top of the activity screen in android. Android ActionBar can contain menu items that become visible when the user clicks the “menu” button. In general, an ActionBar composed of the following four components:
App Icon: App branding logo or icon will be shown here
View Control: A dedicated space to display the Application title. Also provides the option to switch between views by adding spinner or tabbed navigation
Action Buttons: Major actions of the app could be added here
Action Overflow: All unimportant action will be displayed as a menu
Below is a sample image to show where the Action Bar/Toolbar/App Bar is present on an android device.
The action bar is a primary toolbar inside an activity that can be used to display an activity title and other interactive items. One of the most used items is a Back Navigation Button. The back button is used to move backward from the previously visited screen by the user. Most Android devices have a dedicated back button still a back button on the action bar enhances the user experience.
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. There is no need to change anything in the activity_main.xml file. The only file we have to work with is Working with the MainActivity file.
Create action bar variable and call function getSupportActionBar() in the java/kotlin file.
Show back button using actionBar.setDisplayHomeAsUpEnabled(true) this will enable the back button.
Custom the back event at onOptionsItemSelected. This will enable the back function to the button on the press. See the below code for reference. We have provided both the java and kotlin code for MainActivity.
Java
Kotlin
import android.os.Bundle;import android.view.MenuItem;import androidx.annotation.NonNull;import androidx.appcompat.app.ActionBar;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // calling the action bar ActionBar actionBar = getSupportActionBar(); // showing the back button in action bar actionBar.setDisplayHomeAsUpEnabled(true); } // this event will enable the back // function to the button on press @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case android.R.id.home: this.finish(); return true; } return super.onOptionsItemSelected(item); }}
import android.os.Bundleimport android.view.MenuItemimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // calling the action bar var actionBar = getSupportActionBar() // showing the back button in action bar if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true) } } // this event will enable the back // function to the button on press override fun onContextItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() return true } } return super.onContextItemSelected(item) }}
We can easily Customize the Back Button by using the getSupportActionBar() library and setting the drawable file using setHomeAsUpIndicator in the java/kotlin file.
// Customize the back button
actionBar.setHomeAsUpIndicator(R.drawable.mybutton);
The complete code is given below.
Java
Kotlin
import android.os.Bundle;import android.view.MenuItem;import androidx.annotation.NonNull;import androidx.appcompat.app.ActionBar;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // calling the action bar ActionBar actionBar = getSupportActionBar(); // Customize the back button actionBar.setHomeAsUpIndicator(R.drawable.mybutton); // showing the back button in action bar actionBar.setDisplayHomeAsUpEnabled(true); } // this event will enable the back // function to the button on press @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case android.R.id.home: this.finish(); return true; } return super.onOptionsItemSelected(item); }}
import android.os.Bundleimport android.view.MenuItemimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // calling the action bar var actionBar = getSupportActionBar() if (actionBar != null) { // Customize the back button actionBar.setHomeAsUpIndicator(R.drawable.mybutton); // showing the back button in action bar actionBar.setDisplayHomeAsUpEnabled(true); } } // this event will enable the back // function to the button on press override fun onContextItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() return true } } return super.onContextItemSelected(item) }}
Android-Bars
Android
Java
Kotlin
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Flexbox-Layout in Android
How to Post Data to API using Retrofit in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Stream In Java
Object Oriented Programming (OOPs) Concept in Java | [
{
"code": null,
"e": 26365,
"s": 26337,
"text": "\n23 Feb, 2021"
},
{
"code": null,
"e": 26793,
"s": 26365,
"text": "The action bar (sometimes referred to as the app bar), if it exists for an activity, will be at the top of the activity’s content area, typically directly underneath the status bar. It is a menu bar that runs across the top of the activity screen in android. Android ActionBar can contain menu items that become visible when the user clicks the “menu” button. In general, an ActionBar composed of the following four components:"
},
{
"code": null,
"e": 26848,
"s": 26793,
"text": "App Icon: App branding logo or icon will be shown here"
},
{
"code": null,
"e": 27002,
"s": 26848,
"text": "View Control: A dedicated space to display the Application title. Also provides the option to switch between views by adding spinner or tabbed navigation"
},
{
"code": null,
"e": 27063,
"s": 27002,
"text": "Action Buttons: Major actions of the app could be added here"
},
{
"code": null,
"e": 27131,
"s": 27063,
"text": "Action Overflow: All unimportant action will be displayed as a menu"
},
{
"code": null,
"e": 27233,
"s": 27131,
"text": "Below is a sample image to show where the Action Bar/Toolbar/App Bar is present on an android device."
},
{
"code": null,
"e": 27626,
"s": 27233,
"text": "The action bar is a primary toolbar inside an activity that can be used to display an activity title and other interactive items. One of the most used items is a Back Navigation Button. The back button is used to move backward from the previously visited screen by the user. Most Android devices have a dedicated back button still a back button on the action bar enhances the user experience."
},
{
"code": null,
"e": 27878,
"s": 27626,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. There is no need to change anything in the activity_main.xml file. The only file we have to work with is Working with the MainActivity file."
},
{
"code": null,
"e": 27970,
"s": 27878,
"text": "Create action bar variable and call function getSupportActionBar() in the java/kotlin file."
},
{
"code": null,
"e": 28069,
"s": 27970,
"text": "Show back button using actionBar.setDisplayHomeAsUpEnabled(true) this will enable the back button."
},
{
"code": null,
"e": 28279,
"s": 28069,
"text": "Custom the back event at onOptionsItemSelected. This will enable the back function to the button on the press. See the below code for reference. We have provided both the java and kotlin code for MainActivity."
},
{
"code": null,
"e": 28284,
"s": 28279,
"text": "Java"
},
{
"code": null,
"e": 28291,
"s": 28284,
"text": "Kotlin"
},
{
"code": "import android.os.Bundle;import android.view.MenuItem;import androidx.annotation.NonNull;import androidx.appcompat.app.ActionBar;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // calling the action bar ActionBar actionBar = getSupportActionBar(); // showing the back button in action bar actionBar.setDisplayHomeAsUpEnabled(true); } // this event will enable the back // function to the button on press @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case android.R.id.home: this.finish(); return true; } return super.onOptionsItemSelected(item); }}",
"e": 29226,
"s": 28291,
"text": null
},
{
"code": "import android.os.Bundleimport android.view.MenuItemimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // calling the action bar var actionBar = getSupportActionBar() // showing the back button in action bar if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true) } } // this event will enable the back // function to the button on press override fun onContextItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() return true } } return super.onContextItemSelected(item) }}",
"e": 30102,
"s": 29226,
"text": null
},
{
"code": null,
"e": 30268,
"s": 30102,
"text": "We can easily Customize the Back Button by using the getSupportActionBar() library and setting the drawable file using setHomeAsUpIndicator in the java/kotlin file. "
},
{
"code": null,
"e": 30297,
"s": 30268,
"text": "// Customize the back button"
},
{
"code": null,
"e": 30350,
"s": 30297,
"text": "actionBar.setHomeAsUpIndicator(R.drawable.mybutton);"
},
{
"code": null,
"e": 30384,
"s": 30350,
"text": "The complete code is given below."
},
{
"code": null,
"e": 30389,
"s": 30384,
"text": "Java"
},
{
"code": null,
"e": 30396,
"s": 30389,
"text": "Kotlin"
},
{
"code": "import android.os.Bundle;import android.view.MenuItem;import androidx.annotation.NonNull;import androidx.appcompat.app.ActionBar;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // calling the action bar ActionBar actionBar = getSupportActionBar(); // Customize the back button actionBar.setHomeAsUpIndicator(R.drawable.mybutton); // showing the back button in action bar actionBar.setDisplayHomeAsUpEnabled(true); } // this event will enable the back // function to the button on press @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case android.R.id.home: this.finish(); return true; } return super.onOptionsItemSelected(item); }}",
"e": 31429,
"s": 30396,
"text": null
},
{
"code": "import android.os.Bundleimport android.view.MenuItemimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // calling the action bar var actionBar = getSupportActionBar() if (actionBar != null) { // Customize the back button actionBar.setHomeAsUpIndicator(R.drawable.mybutton); // showing the back button in action bar actionBar.setDisplayHomeAsUpEnabled(true); } } // this event will enable the back // function to the button on press override fun onContextItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() return true } } return super.onContextItemSelected(item) }}",
"e": 32438,
"s": 31429,
"text": null
},
{
"code": null,
"e": 32451,
"s": 32438,
"text": "Android-Bars"
},
{
"code": null,
"e": 32459,
"s": 32451,
"text": "Android"
},
{
"code": null,
"e": 32464,
"s": 32459,
"text": "Java"
},
{
"code": null,
"e": 32471,
"s": 32464,
"text": "Kotlin"
},
{
"code": null,
"e": 32476,
"s": 32471,
"text": "Java"
},
{
"code": null,
"e": 32484,
"s": 32476,
"text": "Android"
},
{
"code": null,
"e": 32582,
"s": 32484,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32620,
"s": 32582,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 32659,
"s": 32620,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 32709,
"s": 32659,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 32735,
"s": 32709,
"text": "Flexbox-Layout in Android"
},
{
"code": null,
"e": 32786,
"s": 32735,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 32801,
"s": 32786,
"text": "Arrays in Java"
},
{
"code": null,
"e": 32845,
"s": 32801,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 32867,
"s": 32845,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 32882,
"s": 32867,
"text": "Stream In Java"
}
]
|
Construct Turing Machine for incrementing Binary Number by 1 - GeeksforGeeks | 29 Sep, 2020
Prerequisite : Turing Machine
Task :We have to design a Turing Machine for incrementing the Binary Number by 1.
Examples –
Input: 10111
Output: 11000
Input: 1000
Output: 1001
Input: 10101011
Output: 10101100
Analysis :From the above three examples, we can get two conditions –
When the Rightmost digit is 0 :Here we can see that when we add something to a binary number having 0 as its rightmost digit, then the rightmost digit of the Binary number changes i.e. if the rightmost digit is 0 it will change to 1 and vice versa while all other digits remain the same and our machine will halt when we get Blank(B).
When the Rightmost digit is 1 :Here we can see that when we add something to a binary number having 1 as its rightmost digit, then all the 1’s changes to 0’s until we get a 0, and the 0 we get will change to 1 while all other digits after that will remain same and our machine will halt when we get Blank(B). Suppose we don’t have any 0 in a string for example 1111 then we move to the left until we get a Blank(B) changing all the 1’s to 0’s and change this Blank(B) to 1, and our machine halts.
Approach :
We have to scan the element from right to left. At first, our pointer is at the leftmost side. Therefore we have to shift the pointer to the rightmost side.To shift the pointer to the rightmost side we normally skip all 0’s and 1’s until we get a Blank(B).After this step, we can now move the pointer from left to right.If we get the first digit 1 then we change all the 1’s to 0’s until we get a 0 and change this 0 to 1. After this, all the digit remains the same, and our machine halts at Blank(B).If we get the first digit 1 then a condition arises that we don’t get any 0 for example 1111, then we move to the left until we get a Blank(B) changing all the 1’s to 0’s and change this Blank(B) to 1, and our machine halts.If we get the first digit as 0 then we have to change 0 as 1 and after that, all the digit remains the same and our machine will halt at Blank(B).
We have to scan the element from right to left. At first, our pointer is at the leftmost side. Therefore we have to shift the pointer to the rightmost side.
To shift the pointer to the rightmost side we normally skip all 0’s and 1’s until we get a Blank(B).
After this step, we can now move the pointer from left to right.
If we get the first digit 1 then we change all the 1’s to 0’s until we get a 0 and change this 0 to 1. After this, all the digit remains the same, and our machine halts at Blank(B).
If we get the first digit 1 then a condition arises that we don’t get any 0 for example 1111, then we move to the left until we get a Blank(B) changing all the 1’s to 0’s and change this Blank(B) to 1, and our machine halts.
If we get the first digit as 0 then we have to change 0 as 1 and after that, all the digit remains the same and our machine will halt at Blank(B).
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
NPDA for accepting the language L = {an bn | n>=1}
Construct Pushdown Automata for all length palindrome
NPDA for the language L ={w∈ {a,b}*| w contains equal no. of a's and b's}
NPDA for accepting the language L = {wwR | w ∈ (a,b)*}
Construct a Turing Machine for language L = {ww | w ∈ {0,1}}
Pushdown Automata Acceptance by Final State
Ambiguity in Context free Grammar and Context free Languages
Decidability and Undecidability in TOC
Decidable and Undecidable problems in Theory of Computation
Difference between Pushdown Automata and Finite Automata | [
{
"code": null,
"e": 26240,
"s": 26212,
"text": "\n29 Sep, 2020"
},
{
"code": null,
"e": 26270,
"s": 26240,
"text": "Prerequisite : Turing Machine"
},
{
"code": null,
"e": 26352,
"s": 26270,
"text": "Task :We have to design a Turing Machine for incrementing the Binary Number by 1."
},
{
"code": null,
"e": 26363,
"s": 26352,
"text": "Examples –"
},
{
"code": null,
"e": 26450,
"s": 26363,
"text": "Input: 10111\nOutput: 11000\n\nInput: 1000\nOutput: 1001\n\nInput: 10101011\nOutput: 10101100"
},
{
"code": null,
"e": 26519,
"s": 26450,
"text": "Analysis :From the above three examples, we can get two conditions –"
},
{
"code": null,
"e": 26854,
"s": 26519,
"text": "When the Rightmost digit is 0 :Here we can see that when we add something to a binary number having 0 as its rightmost digit, then the rightmost digit of the Binary number changes i.e. if the rightmost digit is 0 it will change to 1 and vice versa while all other digits remain the same and our machine will halt when we get Blank(B)."
},
{
"code": null,
"e": 27351,
"s": 26854,
"text": "When the Rightmost digit is 1 :Here we can see that when we add something to a binary number having 1 as its rightmost digit, then all the 1’s changes to 0’s until we get a 0, and the 0 we get will change to 1 while all other digits after that will remain same and our machine will halt when we get Blank(B). Suppose we don’t have any 0 in a string for example 1111 then we move to the left until we get a Blank(B) changing all the 1’s to 0’s and change this Blank(B) to 1, and our machine halts."
},
{
"code": null,
"e": 27362,
"s": 27351,
"text": "Approach :"
},
{
"code": null,
"e": 28234,
"s": 27362,
"text": "We have to scan the element from right to left. At first, our pointer is at the leftmost side. Therefore we have to shift the pointer to the rightmost side.To shift the pointer to the rightmost side we normally skip all 0’s and 1’s until we get a Blank(B).After this step, we can now move the pointer from left to right.If we get the first digit 1 then we change all the 1’s to 0’s until we get a 0 and change this 0 to 1. After this, all the digit remains the same, and our machine halts at Blank(B).If we get the first digit 1 then a condition arises that we don’t get any 0 for example 1111, then we move to the left until we get a Blank(B) changing all the 1’s to 0’s and change this Blank(B) to 1, and our machine halts.If we get the first digit as 0 then we have to change 0 as 1 and after that, all the digit remains the same and our machine will halt at Blank(B)."
},
{
"code": null,
"e": 28391,
"s": 28234,
"text": "We have to scan the element from right to left. At first, our pointer is at the leftmost side. Therefore we have to shift the pointer to the rightmost side."
},
{
"code": null,
"e": 28492,
"s": 28391,
"text": "To shift the pointer to the rightmost side we normally skip all 0’s and 1’s until we get a Blank(B)."
},
{
"code": null,
"e": 28557,
"s": 28492,
"text": "After this step, we can now move the pointer from left to right."
},
{
"code": null,
"e": 28739,
"s": 28557,
"text": "If we get the first digit 1 then we change all the 1’s to 0’s until we get a 0 and change this 0 to 1. After this, all the digit remains the same, and our machine halts at Blank(B)."
},
{
"code": null,
"e": 28964,
"s": 28739,
"text": "If we get the first digit 1 then a condition arises that we don’t get any 0 for example 1111, then we move to the left until we get a Blank(B) changing all the 1’s to 0’s and change this Blank(B) to 1, and our machine halts."
},
{
"code": null,
"e": 29111,
"s": 28964,
"text": "If we get the first digit as 0 then we have to change 0 as 1 and after that, all the digit remains the same and our machine will halt at Blank(B)."
},
{
"code": null,
"e": 29144,
"s": 29111,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 29242,
"s": 29144,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29293,
"s": 29242,
"text": "NPDA for accepting the language L = {an bn | n>=1}"
},
{
"code": null,
"e": 29347,
"s": 29293,
"text": "Construct Pushdown Automata for all length palindrome"
},
{
"code": null,
"e": 29421,
"s": 29347,
"text": "NPDA for the language L ={w∈ {a,b}*| w contains equal no. of a's and b's}"
},
{
"code": null,
"e": 29476,
"s": 29421,
"text": "NPDA for accepting the language L = {wwR | w ∈ (a,b)*}"
},
{
"code": null,
"e": 29537,
"s": 29476,
"text": "Construct a Turing Machine for language L = {ww | w ∈ {0,1}}"
},
{
"code": null,
"e": 29581,
"s": 29537,
"text": "Pushdown Automata Acceptance by Final State"
},
{
"code": null,
"e": 29642,
"s": 29581,
"text": "Ambiguity in Context free Grammar and Context free Languages"
},
{
"code": null,
"e": 29681,
"s": 29642,
"text": "Decidability and Undecidability in TOC"
},
{
"code": null,
"e": 29741,
"s": 29681,
"text": "Decidable and Undecidable problems in Theory of Computation"
}
]
|
MySQLi - WHERE Clause | We have seen the SQL SELECT command to fetch data from a MySQL table. We can use a conditional clause called the WHERE Clause to filter out the results. Using this WHERE clause, we can specify a selection criteria to select the required records from a table.
The following code block has a generic SQL syntax of the SELECT command with the WHERE clause to fetch data from the MySQL table −
SELECT field1, field2,...fieldN table_name1, table_name2...
[WHERE condition1 [AND [OR]] condition2.....
You can use one or more tables separated by a comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command.
You can use one or more tables separated by a comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command.
You can specify any condition using the WHERE clause.
You can specify any condition using the WHERE clause.
You can specify more than one condition using the AND or the OR operators.
You can specify more than one condition using the AND or the OR operators.
A WHERE clause can be used along with DELETE or UPDATE SQL command also to specify a condition.
A WHERE clause can be used along with DELETE or UPDATE SQL command also to specify a condition.
The WHERE clause works like an if condition in any programming language. This clause is used to compare the given value with the field value available in a MySQL table. If the given value from outside is equal to the available field value in the MySQL table, then it returns that row.
Here is the list of operators, which can be used with the WHERE clause.
Assume field A holds 10 and field B holds 20, then −
The WHERE clause is very useful when you want to fetch the selected rows from a table, especially when you use the MySQL Join. Joins are discussed in another chapter.
It is a common practice to search for records using the Primary Key to make the search faster.
If the given condition does not match any record in the table, then the query would not return any row.
This will use the SQL SELECT command with the WHERE clause to fetch the selected data from the MySQL table – tutorials_tbl.
The following example will return all the records from the tutorials_tbl table for which the author name is Sanjay.
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> SELECT * from tutorials_tbl WHERE tutorial_author = 'Sanjay';
+-------------+----------------+-----------------+-----------------+
| tutorial_id | tutorial_title | tutorial_author | submission_date |
+-------------+----------------+-----------------+-----------------+
| 3 | JAVA Tutorial | Sanjay | 2007-05-21 |
+-------------+----------------+-----------------+-----------------+
1 rows in set (0.01 sec)
mysql>
Unless performing a LIKE comparison on a string, the comparison is not case sensitive. You can make your search case sensitive by using the BINARY keyword as follows −
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> SELECT * from tutorials_tbl \
WHERE BINARY tutorial_author = 'sanjay';
Empty set (0.02 sec)
mysql>
PHP uses mysqli query() or mysql_query() function to select records in a MySQL table using where clause. This function takes two parameters and returns TRUE on success or FALSE on failure.
$mysqli→query($sql,$resultmode)
$sql
Required - SQL query to select records in a MySQL table using Where Clause.
$resultmode
Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used.
Try the following example to select a record using where clause in a table −
Copy and paste the following example as mysql_example.php −
<html>
<head>
<title>Using Where Clause</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root@123';
$dbname = 'TUTORIALS';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($mysqli→connect_errno ) {
printf("Connect failed: %s<br />", $mysqli→connect_error);
exit();
}
printf('Connected successfully.<br />');
$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl where tutorial_author = "Mahesh"';
$result = $mysqli→query($sql);
if ($result→num_rows > 0) {
while($row = $result→fetch_assoc()) {
printf("Id: %s, Title: %s, Author: %s, Date: %d <br />",
$row["tutorial_id"],
$row["tutorial_title"],
$row["tutorial_author"],
$row["submission_date"]);
}
} else {
printf('No record found.<br />');
}
mysqli_free_result($result);
$mysqli→close();
?>
</body>
</html>
Access the mysql_example.php deployed on apache web server and verify the output. Here we've entered multiple records in the table before running the select script.
Connected successfully.
Id: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021
Id: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021
Id: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021
14 Lectures
1.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2522,
"s": 2263,
"text": "We have seen the SQL SELECT command to fetch data from a MySQL table. We can use a conditional clause called the WHERE Clause to filter out the results. Using this WHERE clause, we can specify a selection criteria to select the required records from a table."
},
{
"code": null,
"e": 2653,
"s": 2522,
"text": "The following code block has a generic SQL syntax of the SELECT command with the WHERE clause to fetch data from the MySQL table −"
},
{
"code": null,
"e": 2759,
"s": 2653,
"text": "SELECT field1, field2,...fieldN table_name1, table_name2...\n[WHERE condition1 [AND [OR]] condition2.....\n"
},
{
"code": null,
"e": 2927,
"s": 2759,
"text": "You can use one or more tables separated by a comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command."
},
{
"code": null,
"e": 3095,
"s": 2927,
"text": "You can use one or more tables separated by a comma to include various conditions using a WHERE clause, but the WHERE clause is an optional part of the SELECT command."
},
{
"code": null,
"e": 3149,
"s": 3095,
"text": "You can specify any condition using the WHERE clause."
},
{
"code": null,
"e": 3203,
"s": 3149,
"text": "You can specify any condition using the WHERE clause."
},
{
"code": null,
"e": 3278,
"s": 3203,
"text": "You can specify more than one condition using the AND or the OR operators."
},
{
"code": null,
"e": 3353,
"s": 3278,
"text": "You can specify more than one condition using the AND or the OR operators."
},
{
"code": null,
"e": 3449,
"s": 3353,
"text": "A WHERE clause can be used along with DELETE or UPDATE SQL command also to specify a condition."
},
{
"code": null,
"e": 3545,
"s": 3449,
"text": "A WHERE clause can be used along with DELETE or UPDATE SQL command also to specify a condition."
},
{
"code": null,
"e": 3830,
"s": 3545,
"text": "The WHERE clause works like an if condition in any programming language. This clause is used to compare the given value with the field value available in a MySQL table. If the given value from outside is equal to the available field value in the MySQL table, then it returns that row."
},
{
"code": null,
"e": 3902,
"s": 3830,
"text": "Here is the list of operators, which can be used with the WHERE clause."
},
{
"code": null,
"e": 3955,
"s": 3902,
"text": "Assume field A holds 10 and field B holds 20, then −"
},
{
"code": null,
"e": 4122,
"s": 3955,
"text": "The WHERE clause is very useful when you want to fetch the selected rows from a table, especially when you use the MySQL Join. Joins are discussed in another chapter."
},
{
"code": null,
"e": 4217,
"s": 4122,
"text": "It is a common practice to search for records using the Primary Key to make the search faster."
},
{
"code": null,
"e": 4321,
"s": 4217,
"text": "If the given condition does not match any record in the table, then the query would not return any row."
},
{
"code": null,
"e": 4445,
"s": 4321,
"text": "This will use the SQL SELECT command with the WHERE clause to fetch the selected data from the MySQL table – tutorials_tbl."
},
{
"code": null,
"e": 4561,
"s": 4445,
"text": "The following example will return all the records from the tutorials_tbl table for which the author name is Sanjay."
},
{
"code": null,
"e": 5114,
"s": 4561,
"text": "root@host# mysql -u root -p password;\nEnter password:*******\nmysql> use TUTORIALS;\nDatabase changed\nmysql> SELECT * from tutorials_tbl WHERE tutorial_author = 'Sanjay';\n+-------------+----------------+-----------------+-----------------+\n| tutorial_id | tutorial_title | tutorial_author | submission_date |\n+-------------+----------------+-----------------+-----------------+\n| 3 | JAVA Tutorial | Sanjay | 2007-05-21 | \n+-------------+----------------+-----------------+-----------------+\n1 rows in set (0.01 sec)\n\nmysql>"
},
{
"code": null,
"e": 5282,
"s": 5114,
"text": "Unless performing a LIKE comparison on a string, the comparison is not case sensitive. You can make your search case sensitive by using the BINARY keyword as follows −"
},
{
"code": null,
"e": 5492,
"s": 5282,
"text": "root@host# mysql -u root -p password;\nEnter password:*******\nmysql> use TUTORIALS;\nDatabase changed\nmysql> SELECT * from tutorials_tbl \\\n WHERE BINARY tutorial_author = 'sanjay';\nEmpty set (0.02 sec)\n\nmysql>"
},
{
"code": null,
"e": 5681,
"s": 5492,
"text": "PHP uses mysqli query() or mysql_query() function to select records in a MySQL table using where clause. This function takes two parameters and returns TRUE on success or FALSE on failure."
},
{
"code": null,
"e": 5714,
"s": 5681,
"text": "$mysqli→query($sql,$resultmode)\n"
},
{
"code": null,
"e": 5719,
"s": 5714,
"text": "$sql"
},
{
"code": null,
"e": 5795,
"s": 5719,
"text": "Required - SQL query to select records in a MySQL table using Where Clause."
},
{
"code": null,
"e": 5807,
"s": 5795,
"text": "$resultmode"
},
{
"code": null,
"e": 5955,
"s": 5807,
"text": "Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used."
},
{
"code": null,
"e": 6032,
"s": 5955,
"text": "Try the following example to select a record using where clause in a table −"
},
{
"code": null,
"e": 6092,
"s": 6032,
"text": "Copy and paste the following example as mysql_example.php −"
},
{
"code": null,
"e": 7297,
"s": 6092,
"text": "<html>\n <head>\n <title>Using Where Clause</title>\n </head>\n <body>\n <?php\n $dbhost = 'localhost';\n $dbuser = 'root';\n $dbpass = 'root@123';\n $dbname = 'TUTORIALS';\n $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);\n \n if($mysqli→connect_errno ) {\n printf(\"Connect failed: %s<br />\", $mysqli→connect_error);\n exit();\n }\n printf('Connected successfully.<br />');\n \n $sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl where tutorial_author = \"Mahesh\"';\n\t\t \n $result = $mysqli→query($sql);\n \n if ($result→num_rows > 0) {\n while($row = $result→fetch_assoc()) {\n printf(\"Id: %s, Title: %s, Author: %s, Date: %d <br />\", \n $row[\"tutorial_id\"], \n $row[\"tutorial_title\"], \n $row[\"tutorial_author\"],\n $row[\"submission_date\"]); \n }\n } else {\n printf('No record found.<br />');\n }\n mysqli_free_result($result);\n $mysqli→close();\n ?>\n </body>\n</html>"
},
{
"code": null,
"e": 7462,
"s": 7297,
"text": "Access the mysql_example.php deployed on apache web server and verify the output. Here we've entered multiple records in the table before running the select script."
},
{
"code": null,
"e": 7655,
"s": 7462,
"text": "Connected successfully.\nId: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021\nId: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021\nId: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021\n"
},
{
"code": null,
"e": 7690,
"s": 7655,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7713,
"s": 7690,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 7720,
"s": 7713,
"text": " Print"
},
{
"code": null,
"e": 7731,
"s": 7720,
"text": " Add Notes"
}
]
|
Array getLong() Method in Java - GeeksforGeeks | 23 Jul, 2020
The java.lang.reflect.Array.getLong() is an inbuilt method in Java and is used to return an element at the given index from a specified Array as a long.
Syntax:
Array.getLong(Object []array, int index)
Parameters : This method accepts two mandatory parameters:
array: The object array whose index is to be returned.
index: The particular index of the given array. The element at ‘index’ in the given array is returned.
Return Value: This method returns the element of the array as long.
Exceptions: This method throws following exceptions:
NullPointerException – when the array is null.
IllegalArgumentException – when the given object array is not an Array.
ArrayIndexOutOfBoundsException – if the given index is not in the range of the size of the array.
Below programs illustrate the get() method of Array class:
Program 1:
import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // Declaring and defining an int array int a[] = { 1, 2, 3, 4, 5 }; // Traversing the array for (int i = 0; i < 5; i++) { // Array.getLong method long x = Array.getLong(a, i); // Printing the values System.out.print(x + " "); } }}
1 2 3 4 5
Program 2: To demonstrate ArrayIndexOutOfBoundsException.
import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // Declaring and defining an int array int a[] = { 1, 2, 3, 4, 5 }; try { // invalid index // Array.getLong method long x = Array.getLong(a, 6); System.out.println(x); } catch (Exception e) { // throws Exception System.out.println("Exception : " + e); } }}
Exception : java.lang.ArrayIndexOutOfBoundsException
Program 3: To demonstrate NullPointerException.
import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // Declaring an int array int a[]; // array to null a = null; try { // null Object array // Array.getLong method long x = Array.getLong(a, 6); System.out.println(x); } catch (Exception e) { // throws Exception System.out.println("Exception : " + e); } }}
Exception : java.lang.NullPointerException
Program 4: To demonstrate IllegalArgumentException.
import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // int (Not an array) int y = 0; try { // illegalArgument // Array.getLong method long x = Array.getLong(y, 6); System.out.println(x); } catch (Exception e) { // Throws exception System.out.println("Exception : " + e); } }}
Exception : java.lang.IllegalArgumentException: Argument is not an array
nidhi_biet
Java - util package
Java-Collections
Java-Functions
java-lang-reflect-package
java-reflection-array
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
StringBuilder Class in Java with Examples
HashMap get() Method in Java
Functional Interfaces in Java
Strings in Java | [
{
"code": null,
"e": 23868,
"s": 23840,
"text": "\n23 Jul, 2020"
},
{
"code": null,
"e": 24021,
"s": 23868,
"text": "The java.lang.reflect.Array.getLong() is an inbuilt method in Java and is used to return an element at the given index from a specified Array as a long."
},
{
"code": null,
"e": 24029,
"s": 24021,
"text": "Syntax:"
},
{
"code": null,
"e": 24071,
"s": 24029,
"text": "Array.getLong(Object []array, int index)\n"
},
{
"code": null,
"e": 24130,
"s": 24071,
"text": "Parameters : This method accepts two mandatory parameters:"
},
{
"code": null,
"e": 24185,
"s": 24130,
"text": "array: The object array whose index is to be returned."
},
{
"code": null,
"e": 24288,
"s": 24185,
"text": "index: The particular index of the given array. The element at ‘index’ in the given array is returned."
},
{
"code": null,
"e": 24356,
"s": 24288,
"text": "Return Value: This method returns the element of the array as long."
},
{
"code": null,
"e": 24409,
"s": 24356,
"text": "Exceptions: This method throws following exceptions:"
},
{
"code": null,
"e": 24456,
"s": 24409,
"text": "NullPointerException – when the array is null."
},
{
"code": null,
"e": 24528,
"s": 24456,
"text": "IllegalArgumentException – when the given object array is not an Array."
},
{
"code": null,
"e": 24626,
"s": 24528,
"text": "ArrayIndexOutOfBoundsException – if the given index is not in the range of the size of the array."
},
{
"code": null,
"e": 24685,
"s": 24626,
"text": "Below programs illustrate the get() method of Array class:"
},
{
"code": null,
"e": 24696,
"s": 24685,
"text": "Program 1:"
},
{
"code": "import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // Declaring and defining an int array int a[] = { 1, 2, 3, 4, 5 }; // Traversing the array for (int i = 0; i < 5; i++) { // Array.getLong method long x = Array.getLong(a, i); // Printing the values System.out.print(x + \" \"); } }}",
"e": 25132,
"s": 24696,
"text": null
},
{
"code": null,
"e": 25143,
"s": 25132,
"text": "1 2 3 4 5\n"
},
{
"code": null,
"e": 25201,
"s": 25143,
"text": "Program 2: To demonstrate ArrayIndexOutOfBoundsException."
},
{
"code": "import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // Declaring and defining an int array int a[] = { 1, 2, 3, 4, 5 }; try { // invalid index // Array.getLong method long x = Array.getLong(a, 6); System.out.println(x); } catch (Exception e) { // throws Exception System.out.println(\"Exception : \" + e); } }}",
"e": 25690,
"s": 25201,
"text": null
},
{
"code": null,
"e": 25744,
"s": 25690,
"text": "Exception : java.lang.ArrayIndexOutOfBoundsException\n"
},
{
"code": null,
"e": 25792,
"s": 25744,
"text": "Program 3: To demonstrate NullPointerException."
},
{
"code": "import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // Declaring an int array int a[]; // array to null a = null; try { // null Object array // Array.getLong method long x = Array.getLong(a, 6); System.out.println(x); } catch (Exception e) { // throws Exception System.out.println(\"Exception : \" + e); } }}",
"e": 26295,
"s": 25792,
"text": null
},
{
"code": null,
"e": 26339,
"s": 26295,
"text": "Exception : java.lang.NullPointerException\n"
},
{
"code": null,
"e": 26391,
"s": 26339,
"text": "Program 4: To demonstrate IllegalArgumentException."
},
{
"code": "import java.lang.reflect.Array; public class GfG { // main method public static void main(String[] args) { // int (Not an array) int y = 0; try { // illegalArgument // Array.getLong method long x = Array.getLong(y, 6); System.out.println(x); } catch (Exception e) { // Throws exception System.out.println(\"Exception : \" + e); } }}",
"e": 26847,
"s": 26391,
"text": null
},
{
"code": null,
"e": 26921,
"s": 26847,
"text": "Exception : java.lang.IllegalArgumentException: Argument is not an array\n"
},
{
"code": null,
"e": 26932,
"s": 26921,
"text": "nidhi_biet"
},
{
"code": null,
"e": 26952,
"s": 26932,
"text": "Java - util package"
},
{
"code": null,
"e": 26969,
"s": 26952,
"text": "Java-Collections"
},
{
"code": null,
"e": 26984,
"s": 26969,
"text": "Java-Functions"
},
{
"code": null,
"e": 27010,
"s": 26984,
"text": "java-lang-reflect-package"
},
{
"code": null,
"e": 27032,
"s": 27010,
"text": "java-reflection-array"
},
{
"code": null,
"e": 27037,
"s": 27032,
"text": "Java"
},
{
"code": null,
"e": 27042,
"s": 27037,
"text": "Java"
},
{
"code": null,
"e": 27059,
"s": 27042,
"text": "Java-Collections"
},
{
"code": null,
"e": 27157,
"s": 27059,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27166,
"s": 27157,
"text": "Comments"
},
{
"code": null,
"e": 27179,
"s": 27166,
"text": "Old Comments"
},
{
"code": null,
"e": 27225,
"s": 27179,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27246,
"s": 27225,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27261,
"s": 27246,
"text": "Stream In Java"
},
{
"code": null,
"e": 27280,
"s": 27261,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27297,
"s": 27280,
"text": "Generics in Java"
},
{
"code": null,
"e": 27340,
"s": 27297,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27382,
"s": 27340,
"text": "StringBuilder Class in Java with Examples"
},
{
"code": null,
"e": 27411,
"s": 27382,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 27441,
"s": 27411,
"text": "Functional Interfaces in Java"
}
]
|
GATE | GATE-CS-2015 (Set 2) | Question 65 - GeeksforGeeks | 11 Oct, 2021
Which one of the following well formed formulae is a tautology?
(A) A(B) B(C) C(D) DAnswer: (C)Explanation:
In logic, a tautology is a formula that is true in every possible interpretation.
All options here are based on order of application of quantifier.So, there are 2 rules:
The positions of the same type of quantifiers can be switched
The positions of different types of quantifiers cannot be switched.
Now, let’s see the Choices of the question:
Option (a)
Sign <-> represents “not equivalent”.
∀x∃y R( x, y ) is not equivalent to ∃Y ∀X R( X, Y )
Let R( X, Y ) represent X < Y for the set of numbers as the universe, for example.
Then ∀X ∃Y R( X, Y ) reads “for every number x, there is a number y that is greater than x”, which is true, while∃Y ∀X R( X, Y ) reads “there is a number that is greater than every (any) number”, which is not true. So this option is rejected.
Option (d)
Sign -> represents “euivalent”
∀X ∀Y R( X, Y ) is equivalent to ∀X ∀Y R( Y, X )
Let R( X, Y ) represent X < Y for the set of numbers as the universe, for example.
Then ∀X ∀Y R( X, Y ) reads “for every number X, there is every Y that is greater than x”,while ∀X ∀Y R( Y, X ) reads “for every number Y, there is every X that is greater than Y”.
And both can’t be equivalent (because at one time, one will be true and other one will be false) So this option isrejected.
Option (b) is clearly rejected as two predicate can’t be equivalent to one predicate only. So Option (c) is the correct one.Explanation for Pption (c) – as position of the quantifier is not changed and since LHS P -> R = ⌐P ᴠ R which is equal to RHS.Option c is tautology and correct answer too.
Note: For solving proposition logic question, always remember not to try with rules only. Just take an exampleand see if options are satisfying it or not. Because for a particular example, three options will give same result andone will be different. And different one is your answer.
For basics to this question, you can refer to:http://www.cs.odu.edu/~cs381/cs381content/logic/pred_logic/quantification/quantification.html
This explanation has been contributed by Nitika Bansal.
YouTubeGeeksforGeeks GATE Computer Science16.3K subscribersNested Quantifiers with Sakshi Singhal | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0021:49 / 40:44•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Yv-yu4gsWCs" 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 2)
GATE-GATE-CS-2015 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90 | [
{
"code": null,
"e": 25719,
"s": 25691,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 25783,
"s": 25719,
"text": "Which one of the following well formed formulae is a tautology?"
},
{
"code": null,
"e": 25829,
"s": 25783,
"text": "(A) A(B) B(C) C(D) DAnswer: (C)Explanation: "
},
{
"code": null,
"e": 25911,
"s": 25829,
"text": "In logic, a tautology is a formula that is true in every possible interpretation."
},
{
"code": null,
"e": 25999,
"s": 25911,
"text": "All options here are based on order of application of quantifier.So, there are 2 rules:"
},
{
"code": null,
"e": 26061,
"s": 25999,
"text": "The positions of the same type of quantifiers can be switched"
},
{
"code": null,
"e": 26129,
"s": 26061,
"text": "The positions of different types of quantifiers cannot be switched."
},
{
"code": null,
"e": 26173,
"s": 26129,
"text": "Now, let’s see the Choices of the question:"
},
{
"code": null,
"e": 26184,
"s": 26173,
"text": "Option (a)"
},
{
"code": null,
"e": 26222,
"s": 26184,
"text": "Sign <-> represents “not equivalent”."
},
{
"code": null,
"e": 26274,
"s": 26222,
"text": "∀x∃y R( x, y ) is not equivalent to ∃Y ∀X R( X, Y )"
},
{
"code": null,
"e": 26600,
"s": 26274,
"text": "Let R( X, Y ) represent X < Y for the set of numbers as the universe, for example.\nThen ∀X ∃Y R( X, Y ) reads “for every number x, there is a number y that is greater than x”, which is true, while∃Y ∀X R( X, Y ) reads “there is a number that is greater than every (any) number”, which is not true. So this option is rejected."
},
{
"code": null,
"e": 26611,
"s": 26600,
"text": "Option (d)"
},
{
"code": null,
"e": 26642,
"s": 26611,
"text": "Sign -> represents “euivalent”"
},
{
"code": null,
"e": 26692,
"s": 26642,
"text": " ∀X ∀Y R( X, Y ) is equivalent to ∀X ∀Y R( Y, X )"
},
{
"code": null,
"e": 26955,
"s": 26692,
"text": "Let R( X, Y ) represent X < Y for the set of numbers as the universe, for example.\nThen ∀X ∀Y R( X, Y ) reads “for every number X, there is every Y that is greater than x”,while ∀X ∀Y R( Y, X ) reads “for every number Y, there is every X that is greater than Y”."
},
{
"code": null,
"e": 27079,
"s": 26955,
"text": "And both can’t be equivalent (because at one time, one will be true and other one will be false) So this option isrejected."
},
{
"code": null,
"e": 27375,
"s": 27079,
"text": "Option (b) is clearly rejected as two predicate can’t be equivalent to one predicate only. So Option (c) is the correct one.Explanation for Pption (c) – as position of the quantifier is not changed and since LHS P -> R = ⌐P ᴠ R which is equal to RHS.Option c is tautology and correct answer too."
},
{
"code": null,
"e": 27660,
"s": 27375,
"text": "Note: For solving proposition logic question, always remember not to try with rules only. Just take an exampleand see if options are satisfying it or not. Because for a particular example, three options will give same result andone will be different. And different one is your answer."
},
{
"code": null,
"e": 27800,
"s": 27660,
"text": "For basics to this question, you can refer to:http://www.cs.odu.edu/~cs381/cs381content/logic/pred_logic/quantification/quantification.html"
},
{
"code": null,
"e": 27856,
"s": 27800,
"text": "This explanation has been contributed by Nitika Bansal."
},
{
"code": null,
"e": 28744,
"s": 27856,
"text": "YouTubeGeeksforGeeks GATE Computer Science16.3K subscribersNested Quantifiers with Sakshi Singhal | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0021:49 / 40:44•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Yv-yu4gsWCs\" 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": 28765,
"s": 28744,
"text": "GATE-CS-2015 (Set 2)"
},
{
"code": null,
"e": 28791,
"s": 28765,
"text": "GATE-GATE-CS-2015 (Set 2)"
},
{
"code": null,
"e": 28796,
"s": 28791,
"text": "GATE"
},
{
"code": null,
"e": 28894,
"s": 28796,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28928,
"s": 28894,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 28962,
"s": 28928,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 28996,
"s": 28962,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 29029,
"s": 28996,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 29065,
"s": 29029,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 29099,
"s": 29065,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 29135,
"s": 29099,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 29169,
"s": 29135,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 29203,
"s": 29169,
"text": "GATE | GATE-CS-2009 | Question 38"
}
]
|
Multidimensional Pointer Arithmetic in C/C++ - GeeksforGeeks | 28 Sep, 2018
In C/C++, arrays and pointers have similar semantics, except on type information.
As an example, given a 3D array
int buffer[5][7][6];
An element at location [2][1][2] can be accessed as “buffer[2][1][2]” or *( *( *(buffer + 2) + 1) + 2).
Observe the following declaration
T *p; // p is a pointer to an object of type T
When a pointer p is pointing to an object of type T, the expression *p is of type T. For example buffer is of type array of 5 two dimensional arrays. The type of the expression *buffer is “array of arrays (i.e. two dimensional array)”.
Based on the above concept translating the expression *( *( *(buffer + 2) + 1) + 2) step-by-step makes it more clear.
buffer – An array of 5 two dimensional arrays, i.e. its type is “array of 5 two dimensional arrays”.buffer + 2 – displacement for 3rd element in the array of 5 two dimensional arrays.*(buffer + 2) – dereferencing, i.e. its type is now two dimensional array.*(buffer + 2) + 1 – displacement to access 2nd element in the array of 7 one dimensional arrays.*( *(buffer + 2) + 1) – dereferencing (accessing), now the type of expression “*( *(buffer + 2) + 1)” is an array of integers.*( *(buffer + 2) + 1) + 2 – displacement to get element at 3rd position in the single dimension array of integers.*( *( *(buffer + 2) + 1) + 2) – accessing the element at 3rd position (the overall expression type is int now).
buffer – An array of 5 two dimensional arrays, i.e. its type is “array of 5 two dimensional arrays”.
buffer + 2 – displacement for 3rd element in the array of 5 two dimensional arrays.
*(buffer + 2) – dereferencing, i.e. its type is now two dimensional array.
*(buffer + 2) + 1 – displacement to access 2nd element in the array of 7 one dimensional arrays.
*( *(buffer + 2) + 1) – dereferencing (accessing), now the type of expression “*( *(buffer + 2) + 1)” is an array of integers.
*( *(buffer + 2) + 1) + 2 – displacement to get element at 3rd position in the single dimension array of integers.
*( *( *(buffer + 2) + 1) + 2) – accessing the element at 3rd position (the overall expression type is int now).
The compiler calculates an “offset” to access array element. The “offset” is calculated based on dimensions of the array. In the above case, offset = 2 * (7 * 6) + 1 * (6) + 2. Those in blue colour are dimensions, note that the higher dimension is not used in offset calculation. During compile time the compiler is aware of dimensions of array. Using offset we can access the element as shown below,
element_data = *( (int *)buffer + offset );
It is not always possible to declare dimensions of array at compile time. Sometimes we need to interpret a buffer as multidimensional array object. For instance, when we are processing 3D image whose dimensions are determined at run-time, usual array subscript rules can’t be used. It is due to lack of fixed dimensions during compile time. Consider the following example,
int *base;
Where base is pointing large image buffer that represents 3D image of dimension l x b x h where l, b and h are variables. If we want to access an element at location (2, 3, 4) we need to calculate offset of the element as
offset = 2 * (b x h) + 3 * (h) + 4 and the element located at base + offset.
Generalizing further, given start address (say base) of an array of size [l x b x h] dimensions, we can access the element at an arbitrary location (a, b, c) in the following way,
data = *(base + a * (b x h) + b * (h) + c); // Note that we haven’t used the higher dimension l.
The same concept can be applied to any number of dimensions. We don’t need the higher dimension to calculate offset of any element in the multidimensional array. It is the reason behind omitting the higher dimension when we pass multidimensional arrays to functions. The higher dimension is needed only when the programmer iterating over limited number of elements of higher dimension.
A C/C++ puzzle, predict the output of following program
int main(){ char arr[5][7][6]; char (*p)[5][7][6] = &arr; /* Hint: &arr - is of type const pointer to an array of 5 two dimensional arrays of size [7][6] */ printf("%d\n", (&arr + 1) - &arr); printf("%d\n", (char *)(&arr + 1) - (char *)&arr); printf("%d\n", (unsigned)(arr + 1) - (unsigned)arr); printf("%d\n", (unsigned)(p + 1) - (unsigned)p); return 0;}
Output:
1
210
42
210
Thanks to student for pointing an error.
— Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
pointer
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
'this' pointer in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Virtual Function in C++ | [
{
"code": null,
"e": 24332,
"s": 24304,
"text": "\n28 Sep, 2018"
},
{
"code": null,
"e": 24414,
"s": 24332,
"text": "In C/C++, arrays and pointers have similar semantics, except on type information."
},
{
"code": null,
"e": 24446,
"s": 24414,
"text": "As an example, given a 3D array"
},
{
"code": null,
"e": 24467,
"s": 24446,
"text": "int buffer[5][7][6];"
},
{
"code": null,
"e": 24571,
"s": 24467,
"text": "An element at location [2][1][2] can be accessed as “buffer[2][1][2]” or *( *( *(buffer + 2) + 1) + 2)."
},
{
"code": null,
"e": 24605,
"s": 24571,
"text": "Observe the following declaration"
},
{
"code": null,
"e": 24652,
"s": 24605,
"text": "T *p; // p is a pointer to an object of type T"
},
{
"code": null,
"e": 24888,
"s": 24652,
"text": "When a pointer p is pointing to an object of type T, the expression *p is of type T. For example buffer is of type array of 5 two dimensional arrays. The type of the expression *buffer is “array of arrays (i.e. two dimensional array)”."
},
{
"code": null,
"e": 25006,
"s": 24888,
"text": "Based on the above concept translating the expression *( *( *(buffer + 2) + 1) + 2) step-by-step makes it more clear."
},
{
"code": null,
"e": 25711,
"s": 25006,
"text": "buffer – An array of 5 two dimensional arrays, i.e. its type is “array of 5 two dimensional arrays”.buffer + 2 – displacement for 3rd element in the array of 5 two dimensional arrays.*(buffer + 2) – dereferencing, i.e. its type is now two dimensional array.*(buffer + 2) + 1 – displacement to access 2nd element in the array of 7 one dimensional arrays.*( *(buffer + 2) + 1) – dereferencing (accessing), now the type of expression “*( *(buffer + 2) + 1)” is an array of integers.*( *(buffer + 2) + 1) + 2 – displacement to get element at 3rd position in the single dimension array of integers.*( *( *(buffer + 2) + 1) + 2) – accessing the element at 3rd position (the overall expression type is int now)."
},
{
"code": null,
"e": 25812,
"s": 25711,
"text": "buffer – An array of 5 two dimensional arrays, i.e. its type is “array of 5 two dimensional arrays”."
},
{
"code": null,
"e": 25896,
"s": 25812,
"text": "buffer + 2 – displacement for 3rd element in the array of 5 two dimensional arrays."
},
{
"code": null,
"e": 25971,
"s": 25896,
"text": "*(buffer + 2) – dereferencing, i.e. its type is now two dimensional array."
},
{
"code": null,
"e": 26068,
"s": 25971,
"text": "*(buffer + 2) + 1 – displacement to access 2nd element in the array of 7 one dimensional arrays."
},
{
"code": null,
"e": 26195,
"s": 26068,
"text": "*( *(buffer + 2) + 1) – dereferencing (accessing), now the type of expression “*( *(buffer + 2) + 1)” is an array of integers."
},
{
"code": null,
"e": 26310,
"s": 26195,
"text": "*( *(buffer + 2) + 1) + 2 – displacement to get element at 3rd position in the single dimension array of integers."
},
{
"code": null,
"e": 26422,
"s": 26310,
"text": "*( *( *(buffer + 2) + 1) + 2) – accessing the element at 3rd position (the overall expression type is int now)."
},
{
"code": null,
"e": 26823,
"s": 26422,
"text": "The compiler calculates an “offset” to access array element. The “offset” is calculated based on dimensions of the array. In the above case, offset = 2 * (7 * 6) + 1 * (6) + 2. Those in blue colour are dimensions, note that the higher dimension is not used in offset calculation. During compile time the compiler is aware of dimensions of array. Using offset we can access the element as shown below,"
},
{
"code": null,
"e": 26867,
"s": 26823,
"text": "element_data = *( (int *)buffer + offset );"
},
{
"code": null,
"e": 27240,
"s": 26867,
"text": "It is not always possible to declare dimensions of array at compile time. Sometimes we need to interpret a buffer as multidimensional array object. For instance, when we are processing 3D image whose dimensions are determined at run-time, usual array subscript rules can’t be used. It is due to lack of fixed dimensions during compile time. Consider the following example,"
},
{
"code": null,
"e": 27251,
"s": 27240,
"text": "int *base;"
},
{
"code": null,
"e": 27473,
"s": 27251,
"text": "Where base is pointing large image buffer that represents 3D image of dimension l x b x h where l, b and h are variables. If we want to access an element at location (2, 3, 4) we need to calculate offset of the element as"
},
{
"code": null,
"e": 27550,
"s": 27473,
"text": "offset = 2 * (b x h) + 3 * (h) + 4 and the element located at base + offset."
},
{
"code": null,
"e": 27730,
"s": 27550,
"text": "Generalizing further, given start address (say base) of an array of size [l x b x h] dimensions, we can access the element at an arbitrary location (a, b, c) in the following way,"
},
{
"code": null,
"e": 27827,
"s": 27730,
"text": "data = *(base + a * (b x h) + b * (h) + c); // Note that we haven’t used the higher dimension l."
},
{
"code": null,
"e": 28213,
"s": 27827,
"text": "The same concept can be applied to any number of dimensions. We don’t need the higher dimension to calculate offset of any element in the multidimensional array. It is the reason behind omitting the higher dimension when we pass multidimensional arrays to functions. The higher dimension is needed only when the programmer iterating over limited number of elements of higher dimension."
},
{
"code": null,
"e": 28269,
"s": 28213,
"text": "A C/C++ puzzle, predict the output of following program"
},
{
"code": "int main(){ char arr[5][7][6]; char (*p)[5][7][6] = &arr; /* Hint: &arr - is of type const pointer to an array of 5 two dimensional arrays of size [7][6] */ printf(\"%d\\n\", (&arr + 1) - &arr); printf(\"%d\\n\", (char *)(&arr + 1) - (char *)&arr); printf(\"%d\\n\", (unsigned)(arr + 1) - (unsigned)arr); printf(\"%d\\n\", (unsigned)(p + 1) - (unsigned)p); return 0;}",
"e": 28661,
"s": 28269,
"text": null
},
{
"code": null,
"e": 28669,
"s": 28661,
"text": "Output:"
},
{
"code": null,
"e": 28671,
"s": 28669,
"text": "1"
},
{
"code": null,
"e": 28675,
"s": 28671,
"text": "210"
},
{
"code": null,
"e": 28678,
"s": 28675,
"text": "42"
},
{
"code": null,
"e": 28682,
"s": 28678,
"text": "210"
},
{
"code": null,
"e": 28723,
"s": 28682,
"text": "Thanks to student for pointing an error."
},
{
"code": null,
"e": 28857,
"s": 28723,
"text": "— Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 28865,
"s": 28857,
"text": "pointer"
},
{
"code": null,
"e": 28876,
"s": 28865,
"text": "C Language"
},
{
"code": null,
"e": 28880,
"s": 28876,
"text": "C++"
},
{
"code": null,
"e": 28884,
"s": 28880,
"text": "CPP"
},
{
"code": null,
"e": 28982,
"s": 28884,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29020,
"s": 28982,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 29046,
"s": 29020,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 29068,
"s": 29046,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 29088,
"s": 29068,
"text": "Multithreading in C"
},
{
"code": null,
"e": 29129,
"s": 29088,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 29147,
"s": 29129,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 29166,
"s": 29147,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29212,
"s": 29166,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 29255,
"s": 29212,
"text": "Map in C++ Standard Template Library (STL)"
}
]
|
Fill missing entries of a magic square - GeeksforGeeks | 28 May, 2021
Given a 3X3 matrix mat with it’s left diagonal elements missing (set to 0), considering the sum of every row, column and diagonal of the original matrix was equal, the task is to find the missing diagonal elements and print the original matrix.Examples:
Input: mat[][] = {{0, 7, 6}, {9, 0, 1}, {4, 3, 0}} Output: 2 7 6 9 5 1 4 3 8 Row sum = Column sum = Diagonal sum = 15Input: mat[][] = {{0, 1, 1}, {1, 0, 1}, {1, 1, 0}} Output: 1 1 1 1 1 1 1 1 1
Approach: Let Sum denote the total sum excluding the diagonal elements,
Sum = total sum of the given matrix – diagonalSum Sum = (3 * rowSum) – diagonalSum Sum = (2 * rowSum) [Since, columnSum = rowSum = diagonalSum] rowSum = Sum / 2
Hence, we can insert an element in every row such that the sum of the row is rowSumBelow is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to fill blanks with numbers#include <bits/stdc++.h>using namespace std; // Function to print the original matrixint printFilledDiagonal(int sq[][3]){ // Calculate the sum of all the elements // of the matrix int sum = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) sum += sq[i][j]; // Required sum of each row (from the approach) sum /= 2; for (int i = 0; i < 3; i++) { // Row sum excluding the diagonal element int rowSum = 0; for (int j = 0; j < 3; j++) rowSum += sq[i][j]; // Element that must be inserted at // diagonal element of the current row sq[i][i] = sum - rowSum; } // Print the updated matrix for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) cout << sq[i][j] << " "; cout << endl; }} // Driver Program to test above functionint main(){ int sq[3][3] = { { 0, 7, 6 }, { 9, 0, 1 }, { 4, 3, 0 } }; printFilledDiagonal(sq); return 0;}
// Java program to fill blanks with numbers import java.io.*; class GFG { // Function to print the original matrixstatic int printFilledDiagonal(int sq[][]){ // Calculate the sum of all the elements // of the matrix int sum = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) sum += sq[i][j]; // Required sum of each row (from the approach) sum /= 2; for (int i = 0; i < 3; i++) { // Row sum excluding the diagonal element int rowSum = 0; for (int j = 0; j < 3; j++) rowSum += sq[i][j]; // Element that must be inserted at // diagonal element of the current row sq[i][i] = sum - rowSum; } // Print the updated matrix for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) System.out.print( sq[i][j] + " "); System.out.println(); } return 0;} // Driver Program to test above function public static void main (String[] args) { int sq[][] = { { 0, 7, 6 }, { 9, 0, 1 }, { 4, 3, 0 } }; printFilledDiagonal(sq); } }// This code is contributed by anuj_67..
# Python3 program to fill blanks# with numbers # Function to print the original matrixdef printFilledDiagonal(sq): # Calculate the sum of all the # elements of the matrix Sum = 0 for i in range(0, 3): for j in range(0, 3): Sum += sq[i][j] # Required sum of each # row (from the approach) Sum = Sum//2 for i in range(0, 3): # Row sum excluding the # diagonal element rowSum = 0 for j in range(0, 3): rowSum += sq[i][j] # Element that must be inserted # at diagonal element of the # current row sq[i][i] = Sum - rowSum # Print the updated matrix for i in range(0, 3): for j in range(0, 3): print(sq[i][j], end = " ") print() # Driver Codeif __name__ == "__main__": sq = [[0, 7, 6], [9, 0, 1], [4, 3, 0]] printFilledDiagonal(sq) # This code is contributed# by Rituraj Jain
// C# program to fill blanks with numbers using System; class GFG { // Function to print the original matrixstatic int printFilledDiagonal(int [,]sq){ // Calculate the sum of all the elements // of the matrix int sum = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) sum += sq[i,j]; // Required sum of each row (from the approach) sum /= 2; for (int i = 0; i < 3; i++) { // Row sum excluding the diagonal element int rowSum = 0; for (int j = 0; j < 3; j++) rowSum += sq[i,j]; // Element that must be inserted at // diagonal element of the current row sq[i,i] = sum - rowSum; } // Print the updated matrix for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) Console.Write( sq[i,j] + " "); Console.WriteLine(); } return 0;} // Driver Program to test above function public static void Main () { int [,]sq = { { 0, 7, 6 }, { 9, 0, 1 }, { 4, 3, 0 } }; printFilledDiagonal(sq); } }// This code is contributed by inder_verma
<?php// PHP program to fill blanks with numbers // Function to print the original matrixfunction printFilledDiagonal($sq){ // Calculate the sum of all the // elements of the matrix $sum = 0; for ($i = 0; $i < 3; $i++) for ($j = 0; $j < 3; $j++) $sum += $sq[$i][$j]; // Required sum of each row // (from the approach) $sum = (int)($sum / 2); for ($i = 0; $i < 3; $i++) { // Row sum excluding the // diagonal element $rowSum = 0; for ($j = 0; $j < 3; $j++) $rowSum += $sq[$i][$j]; // Element that must be inserted at // diagonal element of the current row $sq[$i][$i] = $sum - $rowSum; } // Print the updated matrix for ($i = 0; $i < 3; $i++) { for ($j = 0; $j < 3; $j++) echo $sq[$i][$j] . " "; echo "\n"; }} // Driver Code$sq = array(array(0, 7, 6), array(9, 0, 1), array(4, 3, 0)); printFilledDiagonal($sq); // This code is contributed// by Akanksha Rai?>
<script> // Javascript program to fill blanks with numbers // Function to print the original matrix function printFilledDiagonal(sq) { // Calculate the sum of all the elements // of the matrix let sum = 0; for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) sum += sq[i][j]; // Required sum of each row (from the approach) sum /= 2; for (let i = 0; i < 3; i++) { // Row sum excluding the diagonal element let rowSum = 0; for (let j = 0; j < 3; j++) rowSum += sq[i][j]; // Element that must be inserted at // diagonal element of the current row sq[i][i] = sum - rowSum; } // Print the updated matrix for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) document.write(sq[i][j] + " "); document.write("</br>"); } return 0; } let sq = [ [ 0, 7, 6 ], [ 9, 0, 1 ], [ 4, 3, 0 ] ]; printFilledDiagonal(sq); </script>
2 7 6
9 5 1
4 3 8
vt_m
inderDuMCA
rituraj_jain
Akanksha_Rai
decode2207
magic-square
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sudoku | Backtracking-7
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Program to multiply two matrices
Inplace rotate square matrix by 90 degrees | Set 1
Count all possible paths from top left to bottom right of a mXn matrix
Efficiently compute sums of diagonals of a matrix
Printing all solutions in N-Queen Problem
Min Cost Path | DP-6
Python program to multiply two matrices
The Celebrity Problem | [
{
"code": null,
"e": 26075,
"s": 26047,
"text": "\n28 May, 2021"
},
{
"code": null,
"e": 26331,
"s": 26075,
"text": "Given a 3X3 matrix mat with it’s left diagonal elements missing (set to 0), considering the sum of every row, column and diagonal of the original matrix was equal, the task is to find the missing diagonal elements and print the original matrix.Examples: "
},
{
"code": null,
"e": 26527,
"s": 26331,
"text": "Input: mat[][] = {{0, 7, 6}, {9, 0, 1}, {4, 3, 0}} Output: 2 7 6 9 5 1 4 3 8 Row sum = Column sum = Diagonal sum = 15Input: mat[][] = {{0, 1, 1}, {1, 0, 1}, {1, 1, 0}} Output: 1 1 1 1 1 1 1 1 1 "
},
{
"code": null,
"e": 26603,
"s": 26529,
"text": "Approach: Let Sum denote the total sum excluding the diagonal elements, "
},
{
"code": null,
"e": 26766,
"s": 26603,
"text": "Sum = total sum of the given matrix – diagonalSum Sum = (3 * rowSum) – diagonalSum Sum = (2 * rowSum) [Since, columnSum = rowSum = diagonalSum] rowSum = Sum / 2 "
},
{
"code": null,
"e": 26902,
"s": 26766,
"text": "Hence, we can insert an element in every row such that the sum of the row is rowSumBelow is the implementation of the above approach: "
},
{
"code": null,
"e": 26906,
"s": 26902,
"text": "C++"
},
{
"code": null,
"e": 26911,
"s": 26906,
"text": "Java"
},
{
"code": null,
"e": 26919,
"s": 26911,
"text": "Python3"
},
{
"code": null,
"e": 26922,
"s": 26919,
"text": "C#"
},
{
"code": null,
"e": 26926,
"s": 26922,
"text": "PHP"
},
{
"code": null,
"e": 26937,
"s": 26926,
"text": "Javascript"
},
{
"code": "// C++ program to fill blanks with numbers#include <bits/stdc++.h>using namespace std; // Function to print the original matrixint printFilledDiagonal(int sq[][3]){ // Calculate the sum of all the elements // of the matrix int sum = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) sum += sq[i][j]; // Required sum of each row (from the approach) sum /= 2; for (int i = 0; i < 3; i++) { // Row sum excluding the diagonal element int rowSum = 0; for (int j = 0; j < 3; j++) rowSum += sq[i][j]; // Element that must be inserted at // diagonal element of the current row sq[i][i] = sum - rowSum; } // Print the updated matrix for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) cout << sq[i][j] << \" \"; cout << endl; }} // Driver Program to test above functionint main(){ int sq[3][3] = { { 0, 7, 6 }, { 9, 0, 1 }, { 4, 3, 0 } }; printFilledDiagonal(sq); return 0;}",
"e": 27984,
"s": 26937,
"text": null
},
{
"code": "// Java program to fill blanks with numbers import java.io.*; class GFG { // Function to print the original matrixstatic int printFilledDiagonal(int sq[][]){ // Calculate the sum of all the elements // of the matrix int sum = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) sum += sq[i][j]; // Required sum of each row (from the approach) sum /= 2; for (int i = 0; i < 3; i++) { // Row sum excluding the diagonal element int rowSum = 0; for (int j = 0; j < 3; j++) rowSum += sq[i][j]; // Element that must be inserted at // diagonal element of the current row sq[i][i] = sum - rowSum; } // Print the updated matrix for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) System.out.print( sq[i][j] + \" \"); System.out.println(); } return 0;} // Driver Program to test above function public static void main (String[] args) { int sq[][] = { { 0, 7, 6 }, { 9, 0, 1 }, { 4, 3, 0 } }; printFilledDiagonal(sq); } }// This code is contributed by anuj_67..",
"e": 29134,
"s": 27984,
"text": null
},
{
"code": "# Python3 program to fill blanks# with numbers # Function to print the original matrixdef printFilledDiagonal(sq): # Calculate the sum of all the # elements of the matrix Sum = 0 for i in range(0, 3): for j in range(0, 3): Sum += sq[i][j] # Required sum of each # row (from the approach) Sum = Sum//2 for i in range(0, 3): # Row sum excluding the # diagonal element rowSum = 0 for j in range(0, 3): rowSum += sq[i][j] # Element that must be inserted # at diagonal element of the # current row sq[i][i] = Sum - rowSum # Print the updated matrix for i in range(0, 3): for j in range(0, 3): print(sq[i][j], end = \" \") print() # Driver Codeif __name__ == \"__main__\": sq = [[0, 7, 6], [9, 0, 1], [4, 3, 0]] printFilledDiagonal(sq) # This code is contributed# by Rituraj Jain",
"e": 30084,
"s": 29134,
"text": null
},
{
"code": "// C# program to fill blanks with numbers using System; class GFG { // Function to print the original matrixstatic int printFilledDiagonal(int [,]sq){ // Calculate the sum of all the elements // of the matrix int sum = 0; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) sum += sq[i,j]; // Required sum of each row (from the approach) sum /= 2; for (int i = 0; i < 3; i++) { // Row sum excluding the diagonal element int rowSum = 0; for (int j = 0; j < 3; j++) rowSum += sq[i,j]; // Element that must be inserted at // diagonal element of the current row sq[i,i] = sum - rowSum; } // Print the updated matrix for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) Console.Write( sq[i,j] + \" \"); Console.WriteLine(); } return 0;} // Driver Program to test above function public static void Main () { int [,]sq = { { 0, 7, 6 }, { 9, 0, 1 }, { 4, 3, 0 } }; printFilledDiagonal(sq); } }// This code is contributed by inder_verma",
"e": 31212,
"s": 30084,
"text": null
},
{
"code": "<?php// PHP program to fill blanks with numbers // Function to print the original matrixfunction printFilledDiagonal($sq){ // Calculate the sum of all the // elements of the matrix $sum = 0; for ($i = 0; $i < 3; $i++) for ($j = 0; $j < 3; $j++) $sum += $sq[$i][$j]; // Required sum of each row // (from the approach) $sum = (int)($sum / 2); for ($i = 0; $i < 3; $i++) { // Row sum excluding the // diagonal element $rowSum = 0; for ($j = 0; $j < 3; $j++) $rowSum += $sq[$i][$j]; // Element that must be inserted at // diagonal element of the current row $sq[$i][$i] = $sum - $rowSum; } // Print the updated matrix for ($i = 0; $i < 3; $i++) { for ($j = 0; $j < 3; $j++) echo $sq[$i][$j] . \" \"; echo \"\\n\"; }} // Driver Code$sq = array(array(0, 7, 6), array(9, 0, 1), array(4, 3, 0)); printFilledDiagonal($sq); // This code is contributed// by Akanksha Rai?>",
"e": 32241,
"s": 31212,
"text": null
},
{
"code": "<script> // Javascript program to fill blanks with numbers // Function to print the original matrix function printFilledDiagonal(sq) { // Calculate the sum of all the elements // of the matrix let sum = 0; for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) sum += sq[i][j]; // Required sum of each row (from the approach) sum /= 2; for (let i = 0; i < 3; i++) { // Row sum excluding the diagonal element let rowSum = 0; for (let j = 0; j < 3; j++) rowSum += sq[i][j]; // Element that must be inserted at // diagonal element of the current row sq[i][i] = sum - rowSum; } // Print the updated matrix for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) document.write(sq[i][j] + \" \"); document.write(\"</br>\"); } return 0; } let sq = [ [ 0, 7, 6 ], [ 9, 0, 1 ], [ 4, 3, 0 ] ]; printFilledDiagonal(sq); </script>",
"e": 33379,
"s": 32241,
"text": null
},
{
"code": null,
"e": 33399,
"s": 33379,
"text": "2 7 6 \n9 5 1 \n4 3 8"
},
{
"code": null,
"e": 33406,
"s": 33401,
"text": "vt_m"
},
{
"code": null,
"e": 33417,
"s": 33406,
"text": "inderDuMCA"
},
{
"code": null,
"e": 33430,
"s": 33417,
"text": "rituraj_jain"
},
{
"code": null,
"e": 33443,
"s": 33430,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 33454,
"s": 33443,
"text": "decode2207"
},
{
"code": null,
"e": 33467,
"s": 33454,
"text": "magic-square"
},
{
"code": null,
"e": 33474,
"s": 33467,
"text": "Matrix"
},
{
"code": null,
"e": 33481,
"s": 33474,
"text": "Matrix"
},
{
"code": null,
"e": 33579,
"s": 33481,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33603,
"s": 33579,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 33665,
"s": 33603,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 33698,
"s": 33665,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 33749,
"s": 33698,
"text": "Inplace rotate square matrix by 90 degrees | Set 1"
},
{
"code": null,
"e": 33820,
"s": 33749,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 33870,
"s": 33820,
"text": "Efficiently compute sums of diagonals of a matrix"
},
{
"code": null,
"e": 33912,
"s": 33870,
"text": "Printing all solutions in N-Queen Problem"
},
{
"code": null,
"e": 33933,
"s": 33912,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 33973,
"s": 33933,
"text": "Python program to multiply two matrices"
}
]
|
Ruby | Array assoc() function - GeeksforGeeks | 09 Jan, 2020
The assoc() function in Ruby is used to search through an array of arrays whose first element is compared with the index of the function and return the contained array if match found otherwise return either nil or vacant.
Syntax: Array.assoc(Object)Here Array is the array of arrays.
Parameters:Object : It is an element which gets compared with the first element of the contained array.
Returns: the contained array if match found otherwise returns either nil or vacant.
Example 1:
# Initializing a array of elementsArray1 = ["Alphabets", "a", "b", "c", "d", "e"]Array2 = ["Names", "gfg", "Geeks", "Geek", "GeeksforGeeks"]Array3 = ["City", "Kolkata", "Mumbai", "Delhi", "Patna"] # Creating an array of above arraysArray = [Array1, Array2, Array3] # Calling assoc() functionA = Array.assoc("Alphabets")B = Array.assoc("City")C = Array.assoc("Names") # Printing the matched contained arrayputs "#{A}"puts "#{B}"puts "#{C}"
Output:
["Alphabets", "a", "b", "c", "d", "e"]
["City", "Kolkata", "Mumbai", "Delhi", "Patna"]
["Names", "gfg", "Geeks", "Geek", "GeeksforGeeks"]
Example 2:
# Initializing a array of elementsArray1 = ["Alphabets", "a", "b", "c", "d", "e"]Array2 = ["Names"]Array3 = "City" # Creating an array of above arraysArray = [Array1, Array2, Array3] # Calling assoc() functionA = Array.assoc("Alphabets")B = Array.assoc("City")C = Array.assoc("Names") # Printing the matched contained arrayputs "#{A}"puts "#{B}"puts "#{C}"
Output:
["Alphabets", "a", "b", "c", "d", "e"]
["Names"]
Reference: https://devdocs.io/ruby~2.5/array#method-i-assoc
Ruby Array-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Enumerator each_with_index function
Ruby For Beginners
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Ruby | Array collect() operation
Ruby | Array shift() function
Ruby Mixins
Ruby | Module
Instance Variables in Ruby
Ruby | Array reject() function
Ruby | String concat Method | [
{
"code": null,
"e": 24070,
"s": 24042,
"text": "\n09 Jan, 2020"
},
{
"code": null,
"e": 24292,
"s": 24070,
"text": "The assoc() function in Ruby is used to search through an array of arrays whose first element is compared with the index of the function and return the contained array if match found otherwise return either nil or vacant."
},
{
"code": null,
"e": 24354,
"s": 24292,
"text": "Syntax: Array.assoc(Object)Here Array is the array of arrays."
},
{
"code": null,
"e": 24458,
"s": 24354,
"text": "Parameters:Object : It is an element which gets compared with the first element of the contained array."
},
{
"code": null,
"e": 24542,
"s": 24458,
"text": "Returns: the contained array if match found otherwise returns either nil or vacant."
},
{
"code": null,
"e": 24553,
"s": 24542,
"text": "Example 1:"
},
{
"code": "# Initializing a array of elementsArray1 = [\"Alphabets\", \"a\", \"b\", \"c\", \"d\", \"e\"]Array2 = [\"Names\", \"gfg\", \"Geeks\", \"Geek\", \"GeeksforGeeks\"]Array3 = [\"City\", \"Kolkata\", \"Mumbai\", \"Delhi\", \"Patna\"] # Creating an array of above arraysArray = [Array1, Array2, Array3] # Calling assoc() functionA = Array.assoc(\"Alphabets\")B = Array.assoc(\"City\")C = Array.assoc(\"Names\") # Printing the matched contained arrayputs \"#{A}\"puts \"#{B}\"puts \"#{C}\"",
"e": 24995,
"s": 24553,
"text": null
},
{
"code": null,
"e": 25003,
"s": 24995,
"text": "Output:"
},
{
"code": null,
"e": 25142,
"s": 25003,
"text": "[\"Alphabets\", \"a\", \"b\", \"c\", \"d\", \"e\"]\n[\"City\", \"Kolkata\", \"Mumbai\", \"Delhi\", \"Patna\"]\n[\"Names\", \"gfg\", \"Geeks\", \"Geek\", \"GeeksforGeeks\"]\n"
},
{
"code": null,
"e": 25153,
"s": 25142,
"text": "Example 2:"
},
{
"code": "# Initializing a array of elementsArray1 = [\"Alphabets\", \"a\", \"b\", \"c\", \"d\", \"e\"]Array2 = [\"Names\"]Array3 = \"City\" # Creating an array of above arraysArray = [Array1, Array2, Array3] # Calling assoc() functionA = Array.assoc(\"Alphabets\")B = Array.assoc(\"City\")C = Array.assoc(\"Names\") # Printing the matched contained arrayputs \"#{A}\"puts \"#{B}\"puts \"#{C}\"",
"e": 25513,
"s": 25153,
"text": null
},
{
"code": null,
"e": 25521,
"s": 25513,
"text": "Output:"
},
{
"code": null,
"e": 25572,
"s": 25521,
"text": "[\"Alphabets\", \"a\", \"b\", \"c\", \"d\", \"e\"]\n\n[\"Names\"]\n"
},
{
"code": null,
"e": 25632,
"s": 25572,
"text": "Reference: https://devdocs.io/ruby~2.5/array#method-i-assoc"
},
{
"code": null,
"e": 25649,
"s": 25632,
"text": "Ruby Array-class"
},
{
"code": null,
"e": 25662,
"s": 25649,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 25667,
"s": 25662,
"text": "Ruby"
},
{
"code": null,
"e": 25765,
"s": 25667,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25808,
"s": 25765,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 25827,
"s": 25808,
"text": "Ruby For Beginners"
},
{
"code": null,
"e": 25895,
"s": 25827,
"text": "Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1"
},
{
"code": null,
"e": 25928,
"s": 25895,
"text": "Ruby | Array collect() operation"
},
{
"code": null,
"e": 25958,
"s": 25928,
"text": "Ruby | Array shift() function"
},
{
"code": null,
"e": 25970,
"s": 25958,
"text": "Ruby Mixins"
},
{
"code": null,
"e": 25984,
"s": 25970,
"text": "Ruby | Module"
},
{
"code": null,
"e": 26011,
"s": 25984,
"text": "Instance Variables in Ruby"
},
{
"code": null,
"e": 26042,
"s": 26011,
"text": "Ruby | Array reject() function"
}
]
|
Bash Scripting - How to check If variable is Set - GeeksforGeeks | 15 Feb, 2022
In BASH, we have the ability to check if a variable is set or not. We can use a couple of arguments in the conditional statements to check whether the variable has a value. In this article, we will see how to check if the variable has a set/empty value using certain options like -z, -v, and -n.
The -v option allows us to check if the variable is assigned or not. We can check the variable with the following syntax,
[ -v variable_name ]
We can embed the syntax in conditional statements wherever required, the -v option basically returns true if the variable provided to it has been declared earlier or not, irrespective of its value. We may explore the cases of a variable being non-empty, not declared, and empty in the following example script.
#!/bin/usr/env bash
k="Geek"
if [ -v k ];then
echo "Variable is set"
else
echo "Variable is not set"
if
As we can see in the above output the condition returns true if the variable is defined. Even if the variable might be an empty string, it will return true.
Now, in this example, the variable k was not declared. Hence the option -v returns false and we evaluate the condition accordingly.
In this last, example, we have declared the variable k as an empty string. And this time, as said, the -v option will return true if the variable was declared before, even if it was empty it will check if the variable was previously declared or not. Hence, we can conclude that the -v option returns true if the variable provided to it is declared irrespective of the value it contains.
The -z option allows us to check if the variable is of non-zero length or not. It returns true if the length of the value in the variable is zero (empty). Unlike, the -v option, it will return true if the string is empty. The syntax of this command is a little different and awkward than other options,
[ -z "${variable_name}" ]
OR
[[ -z ${variable_name} ]]
Both of the syntax-es work a bit differently in certain situations like you don’t have to double-quote the variable if parsing in conditional statements. The choice is dependent on the user if portability in BASH is your priority, then the “[[” syntax works very well. Let’s look at the examples for cases when the variable is non-empty, not declared, and empty in a sample BASH script.
#!/bin/usr/env bash
k="Geeks"
if [[ ! -z ${k} ]];then
echo "Variable is not empty"
else
echo "Variable is empty"
if
We have used “!” in front of -z so as to complement the condition, this is done to provide homogeneity in understanding different options and arguments.
Note: The -z options return true if the length of the value of the variable is zero, and the -v option returns true if the variable is declared earlier(i.e. it returns false for empty and non declared variables)
As we can see, the -z option returned false i.e the variable value is not empty and hence we print the same. Since we have used the “!” operator ( not operator) we get the opposite of the evaluated expression.
As said, the -z option returned true i.e the variable’s value is empty. As in the conditional statement, the not operator reverses the result and we echo out that the variable is empty.
In the above example, as the variable “k” is not defined or declared anywhere the -z option will return true as the variable itself doesn’t exist. Thus, we have seen the -z option returns true if the variable’s value is of length zero or is not defined.
The -n option is kind of a combination of the -v and -z options, the -n option returns true if the value of the variable provided is non-empty.
Unlike the -z option which returned false if the value of the variable is non-empty.
Like the -z option, the -n option returns false if the value is declared but is empty.
Unlike, the -v option, the -n option returns false if the variable is declared but has an empty value.
Like the -v option, the -n option returns true if the value of the variable is non-empty.
Let us see the syntax of the -n option.
[ -n "${variable_name}" ]
OR
[[ -n $variable_name ]]
The syntax is not as strict as said, but it is recommended for any critical bugs in certain situations.
Now, we will see the cases like non-empty, not declared, and empty values of the variables passed to the -n option in the sample BASH script.
#!/bin/usr/env bash
k="Geeks"
if [[ -n $k ]];then
echo "Variable is set"
else
echo "Variable is not set"
if
The -n option will return true if the value of the variable is non-zero. If the value is empty or the variable is not declared, it will return false.
As we can see that the condition returned true as the variable’s value(k) is non-empty.
In this example, as the variable (k) was not declared, the condition is evaluated as false and we echo out as the variable is not set.
In the above example, the variable(k) is empty and thus the condition using the -n option is evaluated to false and we echo out the context as per requirement.
From the above sets of examples, we were able to understand the different options like -z, -v, and -n to check if the variable is set/empty or not in a BASH script. The below table can be summarized for a clear understanding of the three options available.
We can have certain modifiers like +set and -unset to change the way the options evaluate the condition. We will look at them in short examples as below.
We can set the modifier +set to the -z option to only return true if the variable is not declared and return false to set and empty values.
[[ -z ${variable_name+set} ]]
We will apply the modifier in the example and evaluate the different result conditions generated because of the modifier attached to the -z option.
#!/bin/usr/env bash
k=""
if [[ ! -z ${k+set} ]];then
echo "Variable is not empty"
else
echo "Variable is empty"
if
We can see that the -z option along with the +set modifier returns false. As said earlier, we use the “!” operator to modify the condition and evaluate the results accordingly. Thus, the +set modifier only allows the set and empty values of the variable to be true and non-set values as false just like the -v option but in a reverse way.
Now, the +set modifier can also be applied to the -n option. This modifier will allow the empty set variable to return true instead of false.
[[ -n ${variable_name+set} ]]
We will apply the modifier in the example and evaluate the different result conditions generated because of the modifier attached to the -n option.
#!/bin/usr/env bash
k=""
if [[ -n ${k+set} ]];then
echo "Variable is set"
else
echo "Variable is not set"
if
The +set modifier is used with the -n option, this allows the empty set variable to evaluate the result as true. This modifies the -n option as the -v option which also accepts the empty string as true.
The other modifier is -unset, it allows the non-set values of variables to return true. The syntax of the -unset modifier with the -z option is as given below:
[[ -z ${variable_name-unset} ]]
We will use the same example to demonstrate the usage of the -unset modifier for the -z option.
#!/bin/usr/env bash
if [[ ! -z ${k-unset} ]];then
echo "Variable is not empty"
else
echo "Variable is empty"
if
The -unset modifier allows the -z option to accept the undeclared variable as false. This might not be very helpful but still is available if needed in certain situations.
We can even use the -unset modifier in -n option. The -unset modifier will allow the -n option to accept the not set or not declared variables to evaluate to true. The syntax is similar for the -n option with the -unset modifier.
[[ -n ${variable_name-unset} ]]
We will evaluate the modifier with the -n option with an example as given below:
#!/bin/usr/env bash
if [[ -n ${k-unset} ]];then
echo "Variable is set"
else
echo "Variable is not set"
if
As we can see, the -n option along with the -unset modifier allows the not set or not declared variable to return the condition as true. Thus this can be again an option to verify a condition provided with certain non-declared variable conditions and constraints.
Below is the modified chart to summarize the following options and modifiers.
rkbhola5
Bash-Script
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
chown command in Linux with Examples
Docker - COPY Instruction
nohup Command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Array Basics in Shell Scripting | Set 1 | [
{
"code": null,
"e": 24528,
"s": 24500,
"text": "\n15 Feb, 2022"
},
{
"code": null,
"e": 24825,
"s": 24528,
"text": "In BASH, we have the ability to check if a variable is set or not. We can use a couple of arguments in the conditional statements to check whether the variable has a value. In this article, we will see how to check if the variable has a set/empty value using certain options like -z, -v, and -n."
},
{
"code": null,
"e": 24947,
"s": 24825,
"text": "The -v option allows us to check if the variable is assigned or not. We can check the variable with the following syntax,"
},
{
"code": null,
"e": 24968,
"s": 24947,
"text": "[ -v variable_name ]"
},
{
"code": null,
"e": 25279,
"s": 24968,
"text": "We can embed the syntax in conditional statements wherever required, the -v option basically returns true if the variable provided to it has been declared earlier or not, irrespective of its value. We may explore the cases of a variable being non-empty, not declared, and empty in the following example script."
},
{
"code": null,
"e": 25393,
"s": 25279,
"text": "#!/bin/usr/env bash\n\nk=\"Geek\"\n\nif [ -v k ];then\n echo \"Variable is set\"\nelse\n echo \"Variable is not set\"\nif"
},
{
"code": null,
"e": 25550,
"s": 25393,
"text": "As we can see in the above output the condition returns true if the variable is defined. Even if the variable might be an empty string, it will return true."
},
{
"code": null,
"e": 25683,
"s": 25550,
"text": "Now, in this example, the variable k was not declared. Hence the option -v returns false and we evaluate the condition accordingly. "
},
{
"code": null,
"e": 26070,
"s": 25683,
"text": "In this last, example, we have declared the variable k as an empty string. And this time, as said, the -v option will return true if the variable was declared before, even if it was empty it will check if the variable was previously declared or not. Hence, we can conclude that the -v option returns true if the variable provided to it is declared irrespective of the value it contains."
},
{
"code": null,
"e": 26374,
"s": 26070,
"text": "The -z option allows us to check if the variable is of non-zero length or not. It returns true if the length of the value in the variable is zero (empty). Unlike, the -v option, it will return true if the string is empty. The syntax of this command is a little different and awkward than other options, "
},
{
"code": null,
"e": 26400,
"s": 26374,
"text": "[ -z \"${variable_name}\" ]"
},
{
"code": null,
"e": 26403,
"s": 26400,
"text": "OR"
},
{
"code": null,
"e": 26430,
"s": 26403,
"text": "[[ -z ${variable_name} ]] "
},
{
"code": null,
"e": 26817,
"s": 26430,
"text": "Both of the syntax-es work a bit differently in certain situations like you don’t have to double-quote the variable if parsing in conditional statements. The choice is dependent on the user if portability in BASH is your priority, then the “[[” syntax works very well. Let’s look at the examples for cases when the variable is non-empty, not declared, and empty in a sample BASH script."
},
{
"code": null,
"e": 26941,
"s": 26817,
"text": "#!/bin/usr/env bash\n\nk=\"Geeks\"\n\nif [[ ! -z ${k} ]];then\n echo \"Variable is not empty\"\nelse\n echo \"Variable is empty\"\nif"
},
{
"code": null,
"e": 27095,
"s": 26941,
"text": "We have used “!” in front of -z so as to complement the condition, this is done to provide homogeneity in understanding different options and arguments. "
},
{
"code": null,
"e": 27307,
"s": 27095,
"text": "Note: The -z options return true if the length of the value of the variable is zero, and the -v option returns true if the variable is declared earlier(i.e. it returns false for empty and non declared variables)"
},
{
"code": null,
"e": 27518,
"s": 27307,
"text": "As we can see, the -z option returned false i.e the variable value is not empty and hence we print the same. Since we have used the “!” operator ( not operator) we get the opposite of the evaluated expression. "
},
{
"code": null,
"e": 27705,
"s": 27518,
"text": "As said, the -z option returned true i.e the variable’s value is empty. As in the conditional statement, the not operator reverses the result and we echo out that the variable is empty. "
},
{
"code": null,
"e": 27960,
"s": 27705,
"text": "In the above example, as the variable “k” is not defined or declared anywhere the -z option will return true as the variable itself doesn’t exist. Thus, we have seen the -z option returns true if the variable’s value is of length zero or is not defined. "
},
{
"code": null,
"e": 28105,
"s": 27960,
"text": "The -n option is kind of a combination of the -v and -z options, the -n option returns true if the value of the variable provided is non-empty. "
},
{
"code": null,
"e": 28190,
"s": 28105,
"text": "Unlike the -z option which returned false if the value of the variable is non-empty."
},
{
"code": null,
"e": 28277,
"s": 28190,
"text": "Like the -z option, the -n option returns false if the value is declared but is empty."
},
{
"code": null,
"e": 28380,
"s": 28277,
"text": "Unlike, the -v option, the -n option returns false if the variable is declared but has an empty value."
},
{
"code": null,
"e": 28470,
"s": 28380,
"text": "Like the -v option, the -n option returns true if the value of the variable is non-empty."
},
{
"code": null,
"e": 28510,
"s": 28470,
"text": "Let us see the syntax of the -n option."
},
{
"code": null,
"e": 28536,
"s": 28510,
"text": "[ -n \"${variable_name}\" ]"
},
{
"code": null,
"e": 28539,
"s": 28536,
"text": "OR"
},
{
"code": null,
"e": 28564,
"s": 28539,
"text": "[[ -n $variable_name ]] "
},
{
"code": null,
"e": 28669,
"s": 28564,
"text": "The syntax is not as strict as said, but it is recommended for any critical bugs in certain situations. "
},
{
"code": null,
"e": 28811,
"s": 28669,
"text": "Now, we will see the cases like non-empty, not declared, and empty values of the variables passed to the -n option in the sample BASH script."
},
{
"code": null,
"e": 28929,
"s": 28811,
"text": "#!/bin/usr/env bash\n\nk=\"Geeks\"\n\nif [[ -n $k ]];then\n echo \"Variable is set\"\nelse\n echo \"Variable is not set\"\nif"
},
{
"code": null,
"e": 29079,
"s": 28929,
"text": "The -n option will return true if the value of the variable is non-zero. If the value is empty or the variable is not declared, it will return false."
},
{
"code": null,
"e": 29168,
"s": 29079,
"text": "As we can see that the condition returned true as the variable’s value(k) is non-empty. "
},
{
"code": null,
"e": 29303,
"s": 29168,
"text": "In this example, as the variable (k) was not declared, the condition is evaluated as false and we echo out as the variable is not set."
},
{
"code": null,
"e": 29464,
"s": 29303,
"text": "In the above example, the variable(k) is empty and thus the condition using the -n option is evaluated to false and we echo out the context as per requirement. "
},
{
"code": null,
"e": 29721,
"s": 29464,
"text": "From the above sets of examples, we were able to understand the different options like -z, -v, and -n to check if the variable is set/empty or not in a BASH script. The below table can be summarized for a clear understanding of the three options available."
},
{
"code": null,
"e": 29875,
"s": 29721,
"text": "We can have certain modifiers like +set and -unset to change the way the options evaluate the condition. We will look at them in short examples as below."
},
{
"code": null,
"e": 30016,
"s": 29875,
"text": "We can set the modifier +set to the -z option to only return true if the variable is not declared and return false to set and empty values. "
},
{
"code": null,
"e": 30046,
"s": 30016,
"text": "[[ -z ${variable_name+set} ]]"
},
{
"code": null,
"e": 30194,
"s": 30046,
"text": "We will apply the modifier in the example and evaluate the different result conditions generated because of the modifier attached to the -z option."
},
{
"code": null,
"e": 30319,
"s": 30194,
"text": "#!/bin/usr/env bash\n\nk=\"\"\n\nif [[ ! -z ${k+set} ]];then\n echo \"Variable is not empty\"\nelse\n echo \"Variable is empty\"\nif"
},
{
"code": null,
"e": 30659,
"s": 30319,
"text": "We can see that the -z option along with the +set modifier returns false. As said earlier, we use the “!” operator to modify the condition and evaluate the results accordingly. Thus, the +set modifier only allows the set and empty values of the variable to be true and non-set values as false just like the -v option but in a reverse way. "
},
{
"code": null,
"e": 30802,
"s": 30659,
"text": "Now, the +set modifier can also be applied to the -n option. This modifier will allow the empty set variable to return true instead of false. "
},
{
"code": null,
"e": 30833,
"s": 30802,
"text": "[[ -n ${variable_name+set} ]] "
},
{
"code": null,
"e": 30981,
"s": 30833,
"text": "We will apply the modifier in the example and evaluate the different result conditions generated because of the modifier attached to the -n option."
},
{
"code": null,
"e": 31100,
"s": 30981,
"text": "#!/bin/usr/env bash\n\nk=\"\"\n\nif [[ -n ${k+set} ]];then\n echo \"Variable is set\"\nelse\n echo \"Variable is not set\"\nif"
},
{
"code": null,
"e": 31303,
"s": 31100,
"text": "The +set modifier is used with the -n option, this allows the empty set variable to evaluate the result as true. This modifies the -n option as the -v option which also accepts the empty string as true."
},
{
"code": null,
"e": 31464,
"s": 31303,
"text": "The other modifier is -unset, it allows the non-set values of variables to return true. The syntax of the -unset modifier with the -z option is as given below:"
},
{
"code": null,
"e": 31496,
"s": 31464,
"text": "[[ -z ${variable_name-unset} ]]"
},
{
"code": null,
"e": 31592,
"s": 31496,
"text": "We will use the same example to demonstrate the usage of the -unset modifier for the -z option."
},
{
"code": null,
"e": 31713,
"s": 31592,
"text": "#!/bin/usr/env bash\n\nif [[ ! -z ${k-unset} ]];then\n echo \"Variable is not empty\"\nelse\n echo \"Variable is empty\"\nif"
},
{
"code": null,
"e": 31885,
"s": 31713,
"text": "The -unset modifier allows the -z option to accept the undeclared variable as false. This might not be very helpful but still is available if needed in certain situations."
},
{
"code": null,
"e": 32115,
"s": 31885,
"text": "We can even use the -unset modifier in -n option. The -unset modifier will allow the -n option to accept the not set or not declared variables to evaluate to true. The syntax is similar for the -n option with the -unset modifier."
},
{
"code": null,
"e": 32147,
"s": 32115,
"text": "[[ -n ${variable_name-unset} ]]"
},
{
"code": null,
"e": 32228,
"s": 32147,
"text": "We will evaluate the modifier with the -n option with an example as given below:"
},
{
"code": null,
"e": 32343,
"s": 32228,
"text": "#!/bin/usr/env bash\n\nif [[ -n ${k-unset} ]];then\n echo \"Variable is set\"\nelse\n echo \"Variable is not set\"\nif"
},
{
"code": null,
"e": 32607,
"s": 32343,
"text": "As we can see, the -n option along with the -unset modifier allows the not set or not declared variable to return the condition as true. Thus this can be again an option to verify a condition provided with certain non-declared variable conditions and constraints."
},
{
"code": null,
"e": 32685,
"s": 32607,
"text": "Below is the modified chart to summarize the following options and modifiers."
},
{
"code": null,
"e": 32694,
"s": 32685,
"text": "rkbhola5"
},
{
"code": null,
"e": 32706,
"s": 32694,
"text": "Bash-Script"
},
{
"code": null,
"e": 32713,
"s": 32706,
"text": "Picked"
},
{
"code": null,
"e": 32724,
"s": 32713,
"text": "Linux-Unix"
},
{
"code": null,
"e": 32822,
"s": 32724,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32857,
"s": 32822,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 32891,
"s": 32857,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 32928,
"s": 32891,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 32954,
"s": 32928,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 32991,
"s": 32954,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 33020,
"s": 32991,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 33062,
"s": 33020,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 33088,
"s": 33062,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 33124,
"s": 33088,
"text": "uniq Command in LINUX with examples"
}
]
|
p5.js createGraphics() Function - GeeksforGeeks | 15 Mar, 2021
The createGraphics() function in p5.js is used for creating an off-screen graphics buffer. It creates and returns a new p5.Renderer object.
Syntax:
createGraphics(w, h, [renderer])
Parameter: This function accepts three parameters as mentioned above and described below:
w: It is a number that sets the width of the off-screen graphics buffer.
h: It is a number that sets the height of the off-screen graphics buffer.
renderer: It is a constant that sets the mode to either P2D or WEBGL. It is an optional parameter. It defaults to P2D if undefined.
Return Value: It returns a p5.Graphics object that contains the off-screen graphics buffer.
The below example illustrates the createGraphics() function in p5.js:
Example 1:
Javascript
// Define the variable to store the graphicslet gfg; function setup() { // Set the canvas createCanvas(600, 600, WEBGL); // Create a new graphics renderer gfg = createGraphics(300, 300); // Change the properties of the // graphics buffer gfg.background(255, 100); gfg.textSize(64); gfg.fill("green"); gfg.textAlign(CENTER); gfg.text("GFG", 150, 50);} function draw() { background(0); // Add a point light to the scene pointLight(255, 255, 255, 0, -200, 200); noStroke(); rotateZ(frameCount * 0.02); rotateX(frameCount * 0.02); noStroke(); // Apply the graphics created // as a texture texture(gfg); // Use a box for the texture box(150);}
Output:
Example 2:
Javascript
// Define the variable to store the graphicslet graphics; function setup() { // Set the canvas createCanvas(600, 600, WEBGL); // Create a new graphics renderer graphics = createGraphics(200, 200); graphics.background(255);} function draw() { background(0); // Add the required objcets to the // graphics buffer graphics.line(0, 0, 200, 200); graphics.line(100, 0, 200, 200); graphics.line(100, 200, 200, 100); graphics.fill("green"); graphics.triangle(30, 75, 50, 20, 85, 70); ambientLight(150); // Add a point light to the scene pointLight(255, 255, 255, 0, -200, 200); rotateZ(frameCount * 0.02); rotateX(frameCount * 0.02); // Apply the graphics created // as a texture texture(graphics); // Use a box for the texture box(150);}
Output:
Reference:https://p5js.org/reference/#/p5/createGraphics
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
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Remove elements from a JavaScript Array
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25406,
"s": 25378,
"text": "\n15 Mar, 2021"
},
{
"code": null,
"e": 25546,
"s": 25406,
"text": "The createGraphics() function in p5.js is used for creating an off-screen graphics buffer. It creates and returns a new p5.Renderer object."
},
{
"code": null,
"e": 25554,
"s": 25546,
"text": "Syntax:"
},
{
"code": null,
"e": 25587,
"s": 25554,
"text": "createGraphics(w, h, [renderer])"
},
{
"code": null,
"e": 25677,
"s": 25587,
"text": "Parameter: This function accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 25750,
"s": 25677,
"text": "w: It is a number that sets the width of the off-screen graphics buffer."
},
{
"code": null,
"e": 25824,
"s": 25750,
"text": "h: It is a number that sets the height of the off-screen graphics buffer."
},
{
"code": null,
"e": 25956,
"s": 25824,
"text": "renderer: It is a constant that sets the mode to either P2D or WEBGL. It is an optional parameter. It defaults to P2D if undefined."
},
{
"code": null,
"e": 26048,
"s": 25956,
"text": "Return Value: It returns a p5.Graphics object that contains the off-screen graphics buffer."
},
{
"code": null,
"e": 26118,
"s": 26048,
"text": "The below example illustrates the createGraphics() function in p5.js:"
},
{
"code": null,
"e": 26129,
"s": 26118,
"text": "Example 1:"
},
{
"code": null,
"e": 26140,
"s": 26129,
"text": "Javascript"
},
{
"code": "// Define the variable to store the graphicslet gfg; function setup() { // Set the canvas createCanvas(600, 600, WEBGL); // Create a new graphics renderer gfg = createGraphics(300, 300); // Change the properties of the // graphics buffer gfg.background(255, 100); gfg.textSize(64); gfg.fill(\"green\"); gfg.textAlign(CENTER); gfg.text(\"GFG\", 150, 50);} function draw() { background(0); // Add a point light to the scene pointLight(255, 255, 255, 0, -200, 200); noStroke(); rotateZ(frameCount * 0.02); rotateX(frameCount * 0.02); noStroke(); // Apply the graphics created // as a texture texture(gfg); // Use a box for the texture box(150);}",
"e": 26816,
"s": 26140,
"text": null
},
{
"code": null,
"e": 26824,
"s": 26816,
"text": "Output:"
},
{
"code": null,
"e": 26835,
"s": 26824,
"text": "Example 2:"
},
{
"code": null,
"e": 26846,
"s": 26835,
"text": "Javascript"
},
{
"code": "// Define the variable to store the graphicslet graphics; function setup() { // Set the canvas createCanvas(600, 600, WEBGL); // Create a new graphics renderer graphics = createGraphics(200, 200); graphics.background(255);} function draw() { background(0); // Add the required objcets to the // graphics buffer graphics.line(0, 0, 200, 200); graphics.line(100, 0, 200, 200); graphics.line(100, 200, 200, 100); graphics.fill(\"green\"); graphics.triangle(30, 75, 50, 20, 85, 70); ambientLight(150); // Add a point light to the scene pointLight(255, 255, 255, 0, -200, 200); rotateZ(frameCount * 0.02); rotateX(frameCount * 0.02); // Apply the graphics created // as a texture texture(graphics); // Use a box for the texture box(150);}",
"e": 27621,
"s": 26846,
"text": null
},
{
"code": null,
"e": 27629,
"s": 27621,
"text": "Output:"
},
{
"code": null,
"e": 27686,
"s": 27629,
"text": "Reference:https://p5js.org/reference/#/p5/createGraphics"
},
{
"code": null,
"e": 27703,
"s": 27686,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 27714,
"s": 27703,
"text": "JavaScript"
},
{
"code": null,
"e": 27731,
"s": 27714,
"text": "Web Technologies"
},
{
"code": null,
"e": 27829,
"s": 27731,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27890,
"s": 27829,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27931,
"s": 27890,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27985,
"s": 27931,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28033,
"s": 27985,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 28073,
"s": 28033,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28115,
"s": 28073,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28148,
"s": 28115,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28191,
"s": 28148,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28253,
"s": 28191,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
]
|
How do we set the input type for an Android EditText programatically? | This example demonstrates how do I set the input type for an Android EditText programmatically.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_marginTop="30dp"
android:padding="4dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:onClick="SetInputTypeNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Here to set EditText input type to number" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
}
public void SetInputTypeNumber(View view) {
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
}
}
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": 1158,
"s": 1062,
"text": "This example demonstrates how do I set the input type for an Android EditText programmatically."
},
{
"code": null,
"e": 1287,
"s": 1158,
"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": 1352,
"s": 1287,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2132,
"s": 1352,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:gravity=\"center_horizontal\"\n android:layout_marginTop=\"30dp\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n <EditText\n android:id=\"@+id/editText\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"/>\n <Button\n android:onClick=\"SetInputTypeNumber\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Click Here to set EditText input type to number\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2189,
"s": 2132,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2749,
"s": 2189,
"text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.text.InputType;\nimport android.view.View;\nimport android.widget.EditText;\npublic class MainActivity extends AppCompatActivity {\n EditText editText;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n editText = findViewById(R.id.editText);\n }\n public void SetInputTypeNumber(View view) {\n editText.setInputType(InputType.TYPE_CLASS_NUMBER);\n }\n}"
},
{
"code": null,
"e": 2804,
"s": 2749,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3471,
"s": 2804,
"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": 3819,
"s": 3471,
"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": 3859,
"s": 3819,
"text": "Click here to download the project code"
}
]
|
How to Compare Strings in C#? - GeeksforGeeks | 24 Jan, 2022
A string is a collection of characters and is used to store plain text. Unlike C or C++, a string in C# is not terminated with a null character. The maximum size of a string object depends on the internal architecture of the system. A variable declared followed by “string” is actually an object of string class.
We can create an object of string class by using variable name followed by “string” keyword.
Syntax:
string myString;
We can also initialize a string object at the time of declaration.
Syntax:
string myString = “GeeksForGeeks”;
This article focuses upon how we can compare strings in C#. For example, we are given three strings “GeeksforGeeks”, “Geeks” and “GeeksforGeeks”. Clearly first and last strings are the same. There are numerous ways to compare strings in C# out of which five ways are explained below in detail.
The String class is specified in the .NET base class library. In other words, a String object is a sequential collection of System.Char objects which represent a string. The System.String class is immutable, that is once created its state we cannot make changes to it. String.Equals() method is a method of String class. This method takes two strings to be compared as parameters. It returns a logical value, true or false with the help of which we can determine whether the given strings are the same or not.
Syntax:
String.Equals(myString1, myString2)
Parameters: It takes two parameters myString1: First string and myString2: Second string
Return type: The return type of this method is Boolean. It will be true if both strings are equal and false if both strings are different
Example:
C#
// C# program to illustrate the working of // String.Equals() method to compare two stringsusing System; class GFG{ static public void Main(){ // Initialize a string string myString1 = "GeeksforGeeks"; // Initialize another string string myString2 = "Geeks"; // Initialize a string string myString3 = "GeeksforGeeks"; // If this method returns true // Print both string are same if (String.Equals(myString1, myString2)) Console.WriteLine($"{myString1} and {myString2} are same."); // If this method returns false // Print both string are different else Console.WriteLine($"{myString1} and {myString2} are different."); // If this method returns true // Print both string are same if (String.Equals(myString1, myString3)) Console.WriteLine($"{myString1} and {myString3} are same."); // If this method returns false // Print both string are different else Console.WriteLine($"{myString1} and {myString3} are different."); // If this method returns true // Print both string are same if (String.Equals(myString2, myString3)) Console.WriteLine($"{myString2} and {myString3} are same."); // If this method returns false // Print both string are different else Console.WriteLine($"{myString2} and {myString3} are different."); }}
GeeksforGeeks and Geeks are different.
GeeksforGeeks and GeeksforGeeks are same.
Geeks and GeeksforGeeks are different.
This method is also defined under the String class. This method also takes two strings to be compared as parameters. It returns a numeric value depending upon the strings passed to the method. This method provides detailed information about the comparison of strings, that is why it is advantageous over String.equals() method.
Syntax:
String.Compare(myString1, myString2)
Parameters: It takes two parameters myString1: First string and myString2: Second string
Return type: The return type of this method is Integer. It will be:
Less than zero: If the first string is lexicographically smaller than the second string.
zero: If both strings are equal.
Greater than zero: If the first string is lexicographically greater than the second string.
Example:
C#
// C# program to illustrate the working of// String.Compare() method to compare two stringsusing System; class GFG{ static public void Main(){ // Initialize a string string myString1 = "GeeksforGeeks"; // Initialize another string string myString2 = "Geeks"; // Initialize another string string myString3 = "GeeksforGeeks"; // If value returned by this method is equal to 0 // Print both string are same if (String.Compare(myString1, myString2) == 0) Console.WriteLine($"{myString1} and {myString2} are same."); // If value returned by this method is less than 0 // Then print first string is smaller than the second string else if(String.Compare(myString1, myString2) < 0) Console.WriteLine( $"{myString1} is lexicographically smaller than {myString2}."); // If value returned by the method is greater than 0 // Then print first string is greater than the second string else Console.WriteLine( $"{myString1} is lexicographically greater than {myString2}."); // If value returned by this method is equal to 0 // Print both string are same if (String.Compare(myString1, myString3) == 0) Console.WriteLine($"{myString1} and {myString3} are same."); // If value returned by this method is less than 0 // Then print first string is smaller than the second string else if (String.Compare(myString1, myString3) < 0) Console.WriteLine( $"{myString1} is lexicographically smaller than {myString3}."); // If value returned by the method is greater than 0 // Then print first string is greater than the second string else Console.WriteLine( $"{myString1} is lexicographically greater than {myString3}."); // If value returned by this method is equal to 0 // Print both string are same if (String.Compare(myString2, myString3) == 0) Console.WriteLine($"{myString2} and {myString3} are same."); // If value returned by this method is less than 0 // Then print first string is smaller than the second string else if (String.Compare(myString2, myString3) < 0) Console.WriteLine( $"{myString2} is lexicographically smaller than {myString3}."); // If value returned by the method is greater than 0 // Then print first string is greater than the second string else Console.WriteLine( $"{myString2} is lexicographically greater than {myString3}."); }}
GeeksforGeeks is lexicographically greater than Geeks.
GeeksforGeeks and GeeksforGeeks are same.
Geeks is lexicographically smaller than GeeksforGeeks.
This is an instance method defined under the String class and it is applied directly to a string or a string object. It returns a numeric value depending on the strings to be compared. This method provides detailed information about the comparison of strings, that is why it is advantageous over String.equals() method.
Syntax:
myString1.CompareTo(myString2)
Parameters: It takes one parameter that is myString2: Second string
Return type: The return type of this method is Integer. It will be:
Less than zero: If the first string is lexicographically smaller than the second string.
zero: If both strings are equal.
Greater than zero: If the first string is lexicographically greater than the second string.
Example:
C#
// C# program to illustrate the working of// CompareTo() method to compare two stringsusing System; class GFG{ static public void Main(){ // Initialize a string string myString1 = "GeeksforGeeks"; // Initialize another string string myString2 = "Geeks"; // Initialize another string string myString3 = "GeeksforGeeks"; // If value returned by this method is equal to 0 // Then display both strings are equal if (myString1.CompareTo(myString2) == 0) Console.WriteLine($"{myString1} and {myString2} are same."); // If value returned by this method is less than 0 // Then print the first string is smaller than the second string else if (myString1.CompareTo(myString2) < 0) Console.WriteLine( $"{myString1} is lexicographically smaller than {myString2}."); // If value returned by this method is greater than 0 // Then print the first string is greater than the second string else Console.WriteLine( $"{myString1} is lexicographically greater than {myString2}."); // If value returned by this method is equal to 0 // Then print both strings are equal if (myString1.CompareTo(myString2) == 0) Console.WriteLine($"{myString1} and {myString3} are same."); // If value returned by this method is less than 0 // Then print the first string is smaller than the second string else if(myString1.CompareTo(myString2) < 0) Console.WriteLine( $"{myString1} is lexicographically smaller than {myString3}."); // If value returned by this method is greater than 0 // Then print the first string is greater than the second string else Console.WriteLine( $"{myString1} is lexicographically greater than {myString3}."); // If value returned by this method is equal to 0 // Then display both strings are equal if (myString1.CompareTo(myString2) == 0) Console.WriteLine($"{myString1} and {myString2} are same."); // If value returned by this method is less than 0 // Then print the first string is smaller than the second string else if (myString1.CompareTo(myString2) < 0) Console.WriteLine( $"{myString2} is lexicographically smaller than {myString3}."); // If value returned by this method is greater than 0 // Then print the first string is greater than the second string else Console.WriteLine( $"{myString2} is lexicographically greater than {myString3}."); }}
GeeksforGeeks is lexicographically greater than Geeks.
GeeksforGeeks is lexicographically greater than GeeksforGeeks.
Geeks is lexicographically greater than GeeksforGeeks.
This method is defined under the StringComparer class. We can create an object of this class with the help of which we can use Compare() method to compare two strings. This method provides detailed information about the comparison of strings, that is why it is advantageous over String.equals() method.
Syntax:
StringComparer myComparer = StringComparer.OrdinalIgnoreCase;
myComparer.Compare(myString1, myString2);
Parameters: It takes two parameters myString1: First string and myString2: Second string
Return type: The return type of this method is Integer. It will be:
Less than zero: If the first string is lexicographically smaller than the second string.
zero: If both strings are equal.
Greater than zero: If the first string is lexicographically greater than the second string.
Example:
C#
// C# program to illustrate the working of Compare() method // of StringComparer class to compare two stringsusing System; class GFG{ static public void Main(){ // Declare an object of class StringComparer StringComparer myComparer = StringComparer.OrdinalIgnoreCase; // Initialize a string string myString1 = "GeeksforGeeks"; // Initialize another string string myString2 = "Geeks"; // Initialize another string string myString3 = "GeeksforGeeks"; // Compare strings using Compare method // on the instantiated object // If this method returns 0 // Print both strings are same if (myComparer.Compare(myString1, myString2) == 0) Console.WriteLine($"{myString1} and {myString2} are same."); // If value returned by this method is smaller than 0 // Then print the first string is smaller than the second string else if (myComparer.Compare(myString1, myString2) < 0) Console.WriteLine( $"{myString1} is lexicographically smaller than {myString2}."); // If value returned by this method is smaller than 0 // Then print the first string is smaller than the second string else Console.WriteLine( $"{myString1} is lexicographically greater than {myString2}."); // If this method returns 0 // Print both strings are same if (myComparer.Compare(myString1, myString3) == 0) Console.WriteLine($"{myString1} and {myString3} are same."); // If value returned by this method is smaller than 0 // Then print the first string is smaller than the second string else if (myComparer.Compare(myString1, myString3) < 0) Console.WriteLine( $"{myString1} is lexicographically smaller than {myString3}."); // If value returned by this method is smaller than 0 // Then print the first string is smaller than the second string else Console.WriteLine( $"{myString1} is lexicographically greater than {myString3}."); // If this method returns 0 // Print both strings are same if (myComparer.Compare(myString2, myString3) == 0) Console.WriteLine($"{myString2} and {myString3} are same."); // If value returned by this method is smaller than 0 // Then print the first string is smaller than the second string else if (myComparer.Compare(myString2, myString3) < 0) Console.WriteLine( $"{myString2} is lexicographically smaller than {myString3}."); // If value returned by this method is greater than 0 // Then print the first string is greater than the second string else Console.WriteLine( $"{myString2} is lexicographically greater than {myString3}."); }}
GeeksforGeeks is lexicographically greater than Geeks.
GeeksforGeeks and GeeksforGeeks are same.
Geeks is lexicographically smaller than GeeksforGeeks.
Strings can be compared character by character. Follow the steps below to compare two strings by using a custom compare method.
Declare a static method Compare outside of the main method. Set the return type of this method as int.Initialize a variable len as the minimum of the lengths of both the strings.Iterate over index = 0 to index = len – 1 using a for loop. At each iteration compare corresponding characters of strings.If the first unmatched character of the first string at index is less than the character of the second string at index, then we will return -1.If the first unmatched character of the first string at index is less than the character of the second string at index, then we will return 1.After the end of the for-loop, if lengths of both strings are equal then return 0. If the length of the first string is less than the second string return -1 otherwise return 1.Call Compare() function from the main function by passing strings to be compared as parameters. If Compare() function returns 0 then print the first string is the same as the second string. If Compare() function returns -1 then the print first string is smaller than the second string else print first string is greater than the second string.
Declare a static method Compare outside of the main method. Set the return type of this method as int.
Initialize a variable len as the minimum of the lengths of both the strings.
Iterate over index = 0 to index = len – 1 using a for loop. At each iteration compare corresponding characters of strings.
If the first unmatched character of the first string at index is less than the character of the second string at index, then we will return -1.
If the first unmatched character of the first string at index is less than the character of the second string at index, then we will return 1.
After the end of the for-loop, if lengths of both strings are equal then return 0. If the length of the first string is less than the second string return -1 otherwise return 1.
Call Compare() function from the main function by passing strings to be compared as parameters. If Compare() function returns 0 then print the first string is the same as the second string. If Compare() function returns -1 then the print first string is smaller than the second string else print first string is greater than the second string.
Example:
C#
// C# program to illustrate the working of// custom Compare() method to compare two strings using System; class GFG{ // Compare method to compare two stringsstatic public int Compare(string myString1, string myString2){ // len stores minimum of two string lengths int len = Math.Min(myString1.Length, myString2.Length); // Iterate over all characters for(int index = 0; index < len; index++) { // If the first not matched character of first // string is smaller than the second string then // return -1 if (myString1[index] < myString2[index]) return -1; // If the first not matched character of first // string is greater than the second string then // return 1 else if (myString1[index] > myString2[index]) return 1; } // If lengths are equal // Return 0 if (myString1.Length == myString2.Length) return 0; // If length of first string is smaller than the second string // then return -1 // If length of first string is greater than the second string // then return 1 return ((myString1.Length < myString2.Length) ? -1 : 1); } // Driver codestatic public void Main(){ // Initialize a string string myString1 = "GeeksforGeeks"; // Initialize another string string myString2 = "Geeks"; // Initialize another string string myString3 = "GeeksforGeeks"; // If value returned by this method is equal to 0 // Then print both strings are same if (Compare(myString1, myString2) == 0) Console.WriteLine($"{myString1} and {myString2} are same."); // If value returned by this method is smaller than 0 // Then print the first string is smaller than the second string else if (Compare(myString1, myString3) < 0) Console.WriteLine( $"{myString1} is lexicographically smaller than {myString2}."); // If value returned by this method is greater than 0 // Then print the first string is greater than the second string else Console.WriteLine( $"{myString1} is lexicographically greater than {myString2}."); // If value returned by this method is equal to 0 // Then print both strings are same if (Compare(myString1, myString3) == 0) Console.WriteLine($"{myString1} and {myString3} are same."); // If value returned by this method is smaller than 0 // Then print the first string is smaller than the second string else if (Compare(myString1, myString3) < 0) Console.WriteLine( $"{myString1} is lexicographically smaller than {myString3}."); // If value returned by this method is greater than 0 // Then print the first string is greater than the second string else Console.WriteLine( $"{myString1} is lexicographically greater than {myString3}."); // If value returned by this method is equal to 0 // Then print both strings are same if (Compare(myString2, myString3) == 0) Console.WriteLine($"{myString2} and {myString3} are same."); // If value returned by this method is smaller than 0 // Then print the first string is smaller than the second string else if (Compare(myString2, myString3) < 0) Console.WriteLine( $"{myString2} is lexicographically smaller than {myString3}."); // If value returned by this method is greater than 0 // Then print the first string is greater than the second string else Console.WriteLine( $"{myString2} is lexicographically greater than {myString3}.");}}
GeeksforGeeks is lexicographically greater than Geeks.
GeeksforGeeks and GeeksforGeeks are same.
Geeks is lexicographically smaller than GeeksforGeeks.
sweetyty
simmytarika5
CSharp-string
CSharp-Strings-Programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | Inheritance
Partial Classes in C#
C# | List Class
Lambda Expressions in C#
Difference between Hashtable and Dictionary in C#
Convert String to Character Array in C# | [
{
"code": null,
"e": 24328,
"s": 24300,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 24641,
"s": 24328,
"text": "A string is a collection of characters and is used to store plain text. Unlike C or C++, a string in C# is not terminated with a null character. The maximum size of a string object depends on the internal architecture of the system. A variable declared followed by “string” is actually an object of string class."
},
{
"code": null,
"e": 24735,
"s": 24641,
"text": "We can create an object of string class by using variable name followed by “string” keyword. "
},
{
"code": null,
"e": 24743,
"s": 24735,
"text": "Syntax:"
},
{
"code": null,
"e": 24760,
"s": 24743,
"text": "string myString;"
},
{
"code": null,
"e": 24827,
"s": 24760,
"text": "We can also initialize a string object at the time of declaration."
},
{
"code": null,
"e": 24835,
"s": 24827,
"text": "Syntax:"
},
{
"code": null,
"e": 24870,
"s": 24835,
"text": "string myString = “GeeksForGeeks”;"
},
{
"code": null,
"e": 25164,
"s": 24870,
"text": "This article focuses upon how we can compare strings in C#. For example, we are given three strings “GeeksforGeeks”, “Geeks” and “GeeksforGeeks”. Clearly first and last strings are the same. There are numerous ways to compare strings in C# out of which five ways are explained below in detail."
},
{
"code": null,
"e": 25675,
"s": 25164,
"text": "The String class is specified in the .NET base class library. In other words, a String object is a sequential collection of System.Char objects which represent a string. The System.String class is immutable, that is once created its state we cannot make changes to it. String.Equals() method is a method of String class. This method takes two strings to be compared as parameters. It returns a logical value, true or false with the help of which we can determine whether the given strings are the same or not. "
},
{
"code": null,
"e": 25683,
"s": 25675,
"text": "Syntax:"
},
{
"code": null,
"e": 25719,
"s": 25683,
"text": "String.Equals(myString1, myString2)"
},
{
"code": null,
"e": 25809,
"s": 25719,
"text": "Parameters: It takes two parameters myString1: First string and myString2: Second string "
},
{
"code": null,
"e": 25947,
"s": 25809,
"text": "Return type: The return type of this method is Boolean. It will be true if both strings are equal and false if both strings are different"
},
{
"code": null,
"e": 25957,
"s": 25947,
"text": "Example: "
},
{
"code": null,
"e": 25960,
"s": 25957,
"text": "C#"
},
{
"code": "// C# program to illustrate the working of // String.Equals() method to compare two stringsusing System; class GFG{ static public void Main(){ // Initialize a string string myString1 = \"GeeksforGeeks\"; // Initialize another string string myString2 = \"Geeks\"; // Initialize a string string myString3 = \"GeeksforGeeks\"; // If this method returns true // Print both string are same if (String.Equals(myString1, myString2)) Console.WriteLine($\"{myString1} and {myString2} are same.\"); // If this method returns false // Print both string are different else Console.WriteLine($\"{myString1} and {myString2} are different.\"); // If this method returns true // Print both string are same if (String.Equals(myString1, myString3)) Console.WriteLine($\"{myString1} and {myString3} are same.\"); // If this method returns false // Print both string are different else Console.WriteLine($\"{myString1} and {myString3} are different.\"); // If this method returns true // Print both string are same if (String.Equals(myString2, myString3)) Console.WriteLine($\"{myString2} and {myString3} are same.\"); // If this method returns false // Print both string are different else Console.WriteLine($\"{myString2} and {myString3} are different.\"); }}",
"e": 27392,
"s": 25960,
"text": null
},
{
"code": null,
"e": 27512,
"s": 27392,
"text": "GeeksforGeeks and Geeks are different.\nGeeksforGeeks and GeeksforGeeks are same.\nGeeks and GeeksforGeeks are different."
},
{
"code": null,
"e": 27840,
"s": 27512,
"text": "This method is also defined under the String class. This method also takes two strings to be compared as parameters. It returns a numeric value depending upon the strings passed to the method. This method provides detailed information about the comparison of strings, that is why it is advantageous over String.equals() method."
},
{
"code": null,
"e": 27848,
"s": 27840,
"text": "Syntax:"
},
{
"code": null,
"e": 27885,
"s": 27848,
"text": "String.Compare(myString1, myString2)"
},
{
"code": null,
"e": 27975,
"s": 27885,
"text": "Parameters: It takes two parameters myString1: First string and myString2: Second string "
},
{
"code": null,
"e": 28043,
"s": 27975,
"text": "Return type: The return type of this method is Integer. It will be:"
},
{
"code": null,
"e": 28132,
"s": 28043,
"text": "Less than zero: If the first string is lexicographically smaller than the second string."
},
{
"code": null,
"e": 28165,
"s": 28132,
"text": "zero: If both strings are equal."
},
{
"code": null,
"e": 28257,
"s": 28165,
"text": "Greater than zero: If the first string is lexicographically greater than the second string."
},
{
"code": null,
"e": 28266,
"s": 28257,
"text": "Example:"
},
{
"code": null,
"e": 28269,
"s": 28266,
"text": "C#"
},
{
"code": "// C# program to illustrate the working of// String.Compare() method to compare two stringsusing System; class GFG{ static public void Main(){ // Initialize a string string myString1 = \"GeeksforGeeks\"; // Initialize another string string myString2 = \"Geeks\"; // Initialize another string string myString3 = \"GeeksforGeeks\"; // If value returned by this method is equal to 0 // Print both string are same if (String.Compare(myString1, myString2) == 0) Console.WriteLine($\"{myString1} and {myString2} are same.\"); // If value returned by this method is less than 0 // Then print first string is smaller than the second string else if(String.Compare(myString1, myString2) < 0) Console.WriteLine( $\"{myString1} is lexicographically smaller than {myString2}.\"); // If value returned by the method is greater than 0 // Then print first string is greater than the second string else Console.WriteLine( $\"{myString1} is lexicographically greater than {myString2}.\"); // If value returned by this method is equal to 0 // Print both string are same if (String.Compare(myString1, myString3) == 0) Console.WriteLine($\"{myString1} and {myString3} are same.\"); // If value returned by this method is less than 0 // Then print first string is smaller than the second string else if (String.Compare(myString1, myString3) < 0) Console.WriteLine( $\"{myString1} is lexicographically smaller than {myString3}.\"); // If value returned by the method is greater than 0 // Then print first string is greater than the second string else Console.WriteLine( $\"{myString1} is lexicographically greater than {myString3}.\"); // If value returned by this method is equal to 0 // Print both string are same if (String.Compare(myString2, myString3) == 0) Console.WriteLine($\"{myString2} and {myString3} are same.\"); // If value returned by this method is less than 0 // Then print first string is smaller than the second string else if (String.Compare(myString2, myString3) < 0) Console.WriteLine( $\"{myString2} is lexicographically smaller than {myString3}.\"); // If value returned by the method is greater than 0 // Then print first string is greater than the second string else Console.WriteLine( $\"{myString2} is lexicographically greater than {myString3}.\"); }}",
"e": 30860,
"s": 28269,
"text": null
},
{
"code": null,
"e": 31012,
"s": 30860,
"text": "GeeksforGeeks is lexicographically greater than Geeks.\nGeeksforGeeks and GeeksforGeeks are same.\nGeeks is lexicographically smaller than GeeksforGeeks."
},
{
"code": null,
"e": 31332,
"s": 31012,
"text": "This is an instance method defined under the String class and it is applied directly to a string or a string object. It returns a numeric value depending on the strings to be compared. This method provides detailed information about the comparison of strings, that is why it is advantageous over String.equals() method."
},
{
"code": null,
"e": 31340,
"s": 31332,
"text": "Syntax:"
},
{
"code": null,
"e": 31371,
"s": 31340,
"text": "myString1.CompareTo(myString2)"
},
{
"code": null,
"e": 31440,
"s": 31371,
"text": "Parameters: It takes one parameter that is myString2: Second string "
},
{
"code": null,
"e": 31508,
"s": 31440,
"text": "Return type: The return type of this method is Integer. It will be:"
},
{
"code": null,
"e": 31597,
"s": 31508,
"text": "Less than zero: If the first string is lexicographically smaller than the second string."
},
{
"code": null,
"e": 31630,
"s": 31597,
"text": "zero: If both strings are equal."
},
{
"code": null,
"e": 31722,
"s": 31630,
"text": "Greater than zero: If the first string is lexicographically greater than the second string."
},
{
"code": null,
"e": 31731,
"s": 31722,
"text": "Example:"
},
{
"code": null,
"e": 31734,
"s": 31731,
"text": "C#"
},
{
"code": "// C# program to illustrate the working of// CompareTo() method to compare two stringsusing System; class GFG{ static public void Main(){ // Initialize a string string myString1 = \"GeeksforGeeks\"; // Initialize another string string myString2 = \"Geeks\"; // Initialize another string string myString3 = \"GeeksforGeeks\"; // If value returned by this method is equal to 0 // Then display both strings are equal if (myString1.CompareTo(myString2) == 0) Console.WriteLine($\"{myString1} and {myString2} are same.\"); // If value returned by this method is less than 0 // Then print the first string is smaller than the second string else if (myString1.CompareTo(myString2) < 0) Console.WriteLine( $\"{myString1} is lexicographically smaller than {myString2}.\"); // If value returned by this method is greater than 0 // Then print the first string is greater than the second string else Console.WriteLine( $\"{myString1} is lexicographically greater than {myString2}.\"); // If value returned by this method is equal to 0 // Then print both strings are equal if (myString1.CompareTo(myString2) == 0) Console.WriteLine($\"{myString1} and {myString3} are same.\"); // If value returned by this method is less than 0 // Then print the first string is smaller than the second string else if(myString1.CompareTo(myString2) < 0) Console.WriteLine( $\"{myString1} is lexicographically smaller than {myString3}.\"); // If value returned by this method is greater than 0 // Then print the first string is greater than the second string else Console.WriteLine( $\"{myString1} is lexicographically greater than {myString3}.\"); // If value returned by this method is equal to 0 // Then display both strings are equal if (myString1.CompareTo(myString2) == 0) Console.WriteLine($\"{myString1} and {myString2} are same.\"); // If value returned by this method is less than 0 // Then print the first string is smaller than the second string else if (myString1.CompareTo(myString2) < 0) Console.WriteLine( $\"{myString2} is lexicographically smaller than {myString3}.\"); // If value returned by this method is greater than 0 // Then print the first string is greater than the second string else Console.WriteLine( $\"{myString2} is lexicographically greater than {myString3}.\"); }}",
"e": 34338,
"s": 31734,
"text": null
},
{
"code": null,
"e": 34511,
"s": 34338,
"text": "GeeksforGeeks is lexicographically greater than Geeks.\nGeeksforGeeks is lexicographically greater than GeeksforGeeks.\nGeeks is lexicographically greater than GeeksforGeeks."
},
{
"code": null,
"e": 34814,
"s": 34511,
"text": "This method is defined under the StringComparer class. We can create an object of this class with the help of which we can use Compare() method to compare two strings. This method provides detailed information about the comparison of strings, that is why it is advantageous over String.equals() method."
},
{
"code": null,
"e": 34822,
"s": 34814,
"text": "Syntax:"
},
{
"code": null,
"e": 34886,
"s": 34822,
"text": "StringComparer myComparer = StringComparer.OrdinalIgnoreCase; "
},
{
"code": null,
"e": 34930,
"s": 34886,
"text": "myComparer.Compare(myString1, myString2); "
},
{
"code": null,
"e": 35020,
"s": 34930,
"text": "Parameters: It takes two parameters myString1: First string and myString2: Second string "
},
{
"code": null,
"e": 35088,
"s": 35020,
"text": "Return type: The return type of this method is Integer. It will be:"
},
{
"code": null,
"e": 35177,
"s": 35088,
"text": "Less than zero: If the first string is lexicographically smaller than the second string."
},
{
"code": null,
"e": 35210,
"s": 35177,
"text": "zero: If both strings are equal."
},
{
"code": null,
"e": 35302,
"s": 35210,
"text": "Greater than zero: If the first string is lexicographically greater than the second string."
},
{
"code": null,
"e": 35311,
"s": 35302,
"text": "Example:"
},
{
"code": null,
"e": 35314,
"s": 35311,
"text": "C#"
},
{
"code": "// C# program to illustrate the working of Compare() method // of StringComparer class to compare two stringsusing System; class GFG{ static public void Main(){ // Declare an object of class StringComparer StringComparer myComparer = StringComparer.OrdinalIgnoreCase; // Initialize a string string myString1 = \"GeeksforGeeks\"; // Initialize another string string myString2 = \"Geeks\"; // Initialize another string string myString3 = \"GeeksforGeeks\"; // Compare strings using Compare method // on the instantiated object // If this method returns 0 // Print both strings are same if (myComparer.Compare(myString1, myString2) == 0) Console.WriteLine($\"{myString1} and {myString2} are same.\"); // If value returned by this method is smaller than 0 // Then print the first string is smaller than the second string else if (myComparer.Compare(myString1, myString2) < 0) Console.WriteLine( $\"{myString1} is lexicographically smaller than {myString2}.\"); // If value returned by this method is smaller than 0 // Then print the first string is smaller than the second string else Console.WriteLine( $\"{myString1} is lexicographically greater than {myString2}.\"); // If this method returns 0 // Print both strings are same if (myComparer.Compare(myString1, myString3) == 0) Console.WriteLine($\"{myString1} and {myString3} are same.\"); // If value returned by this method is smaller than 0 // Then print the first string is smaller than the second string else if (myComparer.Compare(myString1, myString3) < 0) Console.WriteLine( $\"{myString1} is lexicographically smaller than {myString3}.\"); // If value returned by this method is smaller than 0 // Then print the first string is smaller than the second string else Console.WriteLine( $\"{myString1} is lexicographically greater than {myString3}.\"); // If this method returns 0 // Print both strings are same if (myComparer.Compare(myString2, myString3) == 0) Console.WriteLine($\"{myString2} and {myString3} are same.\"); // If value returned by this method is smaller than 0 // Then print the first string is smaller than the second string else if (myComparer.Compare(myString2, myString3) < 0) Console.WriteLine( $\"{myString2} is lexicographically smaller than {myString3}.\"); // If value returned by this method is greater than 0 // Then print the first string is greater than the second string else Console.WriteLine( $\"{myString2} is lexicographically greater than {myString3}.\"); }}",
"e": 38133,
"s": 35314,
"text": null
},
{
"code": null,
"e": 38285,
"s": 38133,
"text": "GeeksforGeeks is lexicographically greater than Geeks.\nGeeksforGeeks and GeeksforGeeks are same.\nGeeks is lexicographically smaller than GeeksforGeeks."
},
{
"code": null,
"e": 38413,
"s": 38285,
"text": "Strings can be compared character by character. Follow the steps below to compare two strings by using a custom compare method."
},
{
"code": null,
"e": 39519,
"s": 38413,
"text": "Declare a static method Compare outside of the main method. Set the return type of this method as int.Initialize a variable len as the minimum of the lengths of both the strings.Iterate over index = 0 to index = len – 1 using a for loop. At each iteration compare corresponding characters of strings.If the first unmatched character of the first string at index is less than the character of the second string at index, then we will return -1.If the first unmatched character of the first string at index is less than the character of the second string at index, then we will return 1.After the end of the for-loop, if lengths of both strings are equal then return 0. If the length of the first string is less than the second string return -1 otherwise return 1.Call Compare() function from the main function by passing strings to be compared as parameters. If Compare() function returns 0 then print the first string is the same as the second string. If Compare() function returns -1 then the print first string is smaller than the second string else print first string is greater than the second string."
},
{
"code": null,
"e": 39622,
"s": 39519,
"text": "Declare a static method Compare outside of the main method. Set the return type of this method as int."
},
{
"code": null,
"e": 39699,
"s": 39622,
"text": "Initialize a variable len as the minimum of the lengths of both the strings."
},
{
"code": null,
"e": 39822,
"s": 39699,
"text": "Iterate over index = 0 to index = len – 1 using a for loop. At each iteration compare corresponding characters of strings."
},
{
"code": null,
"e": 39966,
"s": 39822,
"text": "If the first unmatched character of the first string at index is less than the character of the second string at index, then we will return -1."
},
{
"code": null,
"e": 40109,
"s": 39966,
"text": "If the first unmatched character of the first string at index is less than the character of the second string at index, then we will return 1."
},
{
"code": null,
"e": 40287,
"s": 40109,
"text": "After the end of the for-loop, if lengths of both strings are equal then return 0. If the length of the first string is less than the second string return -1 otherwise return 1."
},
{
"code": null,
"e": 40631,
"s": 40287,
"text": "Call Compare() function from the main function by passing strings to be compared as parameters. If Compare() function returns 0 then print the first string is the same as the second string. If Compare() function returns -1 then the print first string is smaller than the second string else print first string is greater than the second string."
},
{
"code": null,
"e": 40640,
"s": 40631,
"text": "Example:"
},
{
"code": null,
"e": 40643,
"s": 40640,
"text": "C#"
},
{
"code": "// C# program to illustrate the working of// custom Compare() method to compare two strings using System; class GFG{ // Compare method to compare two stringsstatic public int Compare(string myString1, string myString2){ // len stores minimum of two string lengths int len = Math.Min(myString1.Length, myString2.Length); // Iterate over all characters for(int index = 0; index < len; index++) { // If the first not matched character of first // string is smaller than the second string then // return -1 if (myString1[index] < myString2[index]) return -1; // If the first not matched character of first // string is greater than the second string then // return 1 else if (myString1[index] > myString2[index]) return 1; } // If lengths are equal // Return 0 if (myString1.Length == myString2.Length) return 0; // If length of first string is smaller than the second string // then return -1 // If length of first string is greater than the second string // then return 1 return ((myString1.Length < myString2.Length) ? -1 : 1); } // Driver codestatic public void Main(){ // Initialize a string string myString1 = \"GeeksforGeeks\"; // Initialize another string string myString2 = \"Geeks\"; // Initialize another string string myString3 = \"GeeksforGeeks\"; // If value returned by this method is equal to 0 // Then print both strings are same if (Compare(myString1, myString2) == 0) Console.WriteLine($\"{myString1} and {myString2} are same.\"); // If value returned by this method is smaller than 0 // Then print the first string is smaller than the second string else if (Compare(myString1, myString3) < 0) Console.WriteLine( $\"{myString1} is lexicographically smaller than {myString2}.\"); // If value returned by this method is greater than 0 // Then print the first string is greater than the second string else Console.WriteLine( $\"{myString1} is lexicographically greater than {myString2}.\"); // If value returned by this method is equal to 0 // Then print both strings are same if (Compare(myString1, myString3) == 0) Console.WriteLine($\"{myString1} and {myString3} are same.\"); // If value returned by this method is smaller than 0 // Then print the first string is smaller than the second string else if (Compare(myString1, myString3) < 0) Console.WriteLine( $\"{myString1} is lexicographically smaller than {myString3}.\"); // If value returned by this method is greater than 0 // Then print the first string is greater than the second string else Console.WriteLine( $\"{myString1} is lexicographically greater than {myString3}.\"); // If value returned by this method is equal to 0 // Then print both strings are same if (Compare(myString2, myString3) == 0) Console.WriteLine($\"{myString2} and {myString3} are same.\"); // If value returned by this method is smaller than 0 // Then print the first string is smaller than the second string else if (Compare(myString2, myString3) < 0) Console.WriteLine( $\"{myString2} is lexicographically smaller than {myString3}.\"); // If value returned by this method is greater than 0 // Then print the first string is greater than the second string else Console.WriteLine( $\"{myString2} is lexicographically greater than {myString3}.\");}}",
"e": 44388,
"s": 40643,
"text": null
},
{
"code": null,
"e": 44540,
"s": 44388,
"text": "GeeksforGeeks is lexicographically greater than Geeks.\nGeeksforGeeks and GeeksforGeeks are same.\nGeeks is lexicographically smaller than GeeksforGeeks."
},
{
"code": null,
"e": 44549,
"s": 44540,
"text": "sweetyty"
},
{
"code": null,
"e": 44562,
"s": 44549,
"text": "simmytarika5"
},
{
"code": null,
"e": 44576,
"s": 44562,
"text": "CSharp-string"
},
{
"code": null,
"e": 44600,
"s": 44576,
"text": "CSharp-Strings-Programs"
},
{
"code": null,
"e": 44607,
"s": 44600,
"text": "Picked"
},
{
"code": null,
"e": 44610,
"s": 44607,
"text": "C#"
},
{
"code": null,
"e": 44708,
"s": 44610,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44717,
"s": 44708,
"text": "Comments"
},
{
"code": null,
"e": 44730,
"s": 44717,
"text": "Old Comments"
},
{
"code": null,
"e": 44753,
"s": 44730,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 44781,
"s": 44753,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 44821,
"s": 44781,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 44864,
"s": 44821,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 44881,
"s": 44864,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 44903,
"s": 44881,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 44919,
"s": 44903,
"text": "C# | List Class"
},
{
"code": null,
"e": 44944,
"s": 44919,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 44994,
"s": 44944,
"text": "Difference between Hashtable and Dictionary in C#"
}
]
|
Creating Python Virtual Environments | by Wei-Meng Lee | Towards Data Science | In Python, a virtual environment is an isolated environment for running your Python programs. Using a virtual environment allows your program to have its own dependencies (different versions of packages). For example, Program A uses a specific version of packageX, while Program B uses an older version of packageX. Here is the problem visually:
If you put the two program into the same default environment, you will run into problem with packageX — if you try to install a specific version of packageX, it will override the other version.
A better solution is to create two isolated environments— aka virtual environments. Each virtual environment will then host the specific versions of packageX that each program needs, like this:
In this article, I will show you how you can create virtual environments using the conda package manager. In addition, I will also show you how you can obtain a list of packages that you have installed in your environment (through the pip command) and perform the same installation on another virtual environment using the requirements.txt file.
Conda is an open source package and environment management system that runs on Windows, Mac OS and Linux.
This article assumes that you have Anaconda (https://www.anaconda.com/products/individual-d) installed on your computer.
To create a new virtual environment, use the conda command with the following options:
conda create --name Project1 python=3.9
The above command creates a virtual environment named Project1, with the Python version set at 3.9:
Once the virtual environment is created, you can view the list of virtual environments you have on your computer using the following command:
conda info --envs
You should see something like the following:
(base) weimenglee@Wei-Mengs-Mini ~ % conda info --envs# conda environments:#base * /Users/weimenglee/miniforge3Project1 /Users/weimenglee/miniforge3/envs/Project1
With the new virtual environment created, it is time to activate it:
(base) weimenglee@Wei-Mengs-Mini ~ % conda activate Project1(Project1) weimenglee@Wei-Mengs-Mini ~ %
As you can see above, once the Project1 virtual environment is activated, you will see the name of the virtual environment (Project1) in front of the command prompt:
(Project1) weimenglee@Wei-Mengs-Mini ~ %
To know what are the packages currently installed in your virtual environment, use the pip freeze command:
(Project1) weimenglee@Wei-Mengs-Mini ~ % pip freeze
This command will return you a list of packages installed in the current environment, together with their version numbers. Here is an example of the output of my Project1 virtual environment:
certifi==2021.5.30
Occasionally the pip freeze command will include direct references for distributions installed from direct URL references, such as the following:
certifi==2021.5.30chardet @ file:///Users/runner/miniforge3/conda-bld/chardet_1610093454858/work
To prevent this from happening, use the following alternative command for pip freeze:
pip list --format=freeze
This will ensure that the result will always be in this format:
<package_name>==<version_number>
Let’s now try to install some additional packages in our Project1 virtual environment using the pip install command:
(Project1) weimenglee@Wei-Mengs-Mini ~ % pip install pandas numpy matplotlib
The above command installs the following packages:
Pandas
NumPy
Matplotlib
You can now use the pip freeze command (or pip list —-format=freeze) to view the list of packages you have, including the ones that you have just installed.
(Project1) weimenglee@Wei-Mengs-Mini ~ % pip freezecertifi==2021.5.30cycler==0.10.0kiwisolver==1.3.2matplotlib==3.4.3numpy==1.21.2pandas==1.3.2Pillow==8.3.2pyparsing==2.4.7python-dateutil==2.8.2pytz==2021.1six==1.16.0
In addition, you will also save the list to a file named requirements.txt:
(Project1) weimenglee@Wei-Mengs-Mini ~ % pip freeze > requirements.txt
The requirements.txt file contains the list of packages that are installed in the current environment. You will make use of it later to reinstall all the packages in another virtual environment.
Key takeaway — whatever packages you install in this virtual environment stays in this virtual environment. It will not conflict with other similar packages you install in another virtual environment.
You can now test to see if the environment works correctly. Type the following command to start the Python interpreter:
(Project1) weimenglee@Wei-Mengs-Mini ~ % python
Then, import the Pandas package and print out its version:
>>> import pandas>>> print(pandas.__version__)
If you are able to see the output above, the packages are installed correctly.
Type exit() to exit from the Python interpreter.
When you are done with the environment, you can use the conda deactivate command to bring you back to the base environment:
(Project1) weimenglee@Wei-Mengs-Mini ~ % conda deactivate
After you are done with your project and have no more need for the environment, you can remove the environment using the following command:
(base) weimenglee@Wei-Mengs-Mini ~ % conda env remove --name Project1Remove all packages in environment /Users/weimenglee/miniforge3/envs/Project1:
Let’s now create another virtual environment and call it, say Project2:
(base) weimenglee@Wei-Mengs-Mini ~ % conda create --name Project2 python=3.9
Once created, activate the new virtual environment:
(base) weimenglee@Wei-Mengs-Mini ~ % conda activate Project2(Project2) weimenglee@Wei-Mengs-Mini ~ %
Let’s try the Python interpreter and see if the Pandas module is available:
(Project2) weimenglee@Wei-Mengs-Mini ~ % pythonPython 3.9.6 (default, Aug 16 2021, 12:43:27)[Clang 12.0.0 ] :: Anaconda, Inc. on darwinType "help", "copyright", "credits" or "license" for more information.>>> import pandasTraceback (most recent call last):File "<stdin>", line 1, in <module>ModuleNotFoundError: No module named 'pandas'>>> exit()
As predicted, Pandas is not installed by default. If you want to install the set of packages that you have installed in the Project1 virtual environment, you can now make use of the requirements.txt file you created earlier:
(Project2) weimenglee@Wei-Mengs-Mini ~ % pip install -r requirements.txtRequirement already satisfied: certifi==2021.5.30 in ./miniforge3/envs/Project2/lib/python3.9/site-packages (from -r requirements.txt (line 1)) (2021.5.30)Collecting cycler==0.10.0...Collecting matplotlib==3.4.3Using cached matplotlib-3.4.3-cp39-cp39-macosx_11_0_arm64.whlCollecting numpy==1.21.2Using cached numpy-1.21.2-cp39-cp39-macosx_11_0_arm64.whl (12.4 MB)Collecting pandas==1.3.2Using cached pandas-1.3.2-cp39-cp39-macosx_11_0_arm64.whl...Installing collected packages: six, pytz, python-dateutil, pyparsing, Pillow, numpy, kiwisolver, cycler, pandas, matplotlibSuccessfully installed Pillow-8.3.2 cycler-0.10.0 kiwisolver-1.3.2 matplotlib-3.4.3 numpy-1.21.2 pandas-1.3.2 pyparsing-2.4.7 python-dateutil-2.8.2 pytz-2021.1 six-1.16.0
All the packages specified in the requirements.txt file will now be installed in the Project2 virtual environment.
Using the requirements.txt file is a good way to specify the dependencies of your Python program. In this file, you put all the packages names (as well as their specific version numbers) that your application needs so that whoever runs your program simply needs to perform a pip install using the requirements.txt file. | [
{
"code": null,
"e": 393,
"s": 47,
"text": "In Python, a virtual environment is an isolated environment for running your Python programs. Using a virtual environment allows your program to have its own dependencies (different versions of packages). For example, Program A uses a specific version of packageX, while Program B uses an older version of packageX. Here is the problem visually:"
},
{
"code": null,
"e": 587,
"s": 393,
"text": "If you put the two program into the same default environment, you will run into problem with packageX — if you try to install a specific version of packageX, it will override the other version."
},
{
"code": null,
"e": 781,
"s": 587,
"text": "A better solution is to create two isolated environments— aka virtual environments. Each virtual environment will then host the specific versions of packageX that each program needs, like this:"
},
{
"code": null,
"e": 1127,
"s": 781,
"text": "In this article, I will show you how you can create virtual environments using the conda package manager. In addition, I will also show you how you can obtain a list of packages that you have installed in your environment (through the pip command) and perform the same installation on another virtual environment using the requirements.txt file."
},
{
"code": null,
"e": 1233,
"s": 1127,
"text": "Conda is an open source package and environment management system that runs on Windows, Mac OS and Linux."
},
{
"code": null,
"e": 1354,
"s": 1233,
"text": "This article assumes that you have Anaconda (https://www.anaconda.com/products/individual-d) installed on your computer."
},
{
"code": null,
"e": 1441,
"s": 1354,
"text": "To create a new virtual environment, use the conda command with the following options:"
},
{
"code": null,
"e": 1481,
"s": 1441,
"text": "conda create --name Project1 python=3.9"
},
{
"code": null,
"e": 1581,
"s": 1481,
"text": "The above command creates a virtual environment named Project1, with the Python version set at 3.9:"
},
{
"code": null,
"e": 1723,
"s": 1581,
"text": "Once the virtual environment is created, you can view the list of virtual environments you have on your computer using the following command:"
},
{
"code": null,
"e": 1741,
"s": 1723,
"text": "conda info --envs"
},
{
"code": null,
"e": 1786,
"s": 1741,
"text": "You should see something like the following:"
},
{
"code": null,
"e": 1979,
"s": 1786,
"text": "(base) weimenglee@Wei-Mengs-Mini ~ % conda info --envs# conda environments:#base * /Users/weimenglee/miniforge3Project1 /Users/weimenglee/miniforge3/envs/Project1"
},
{
"code": null,
"e": 2048,
"s": 1979,
"text": "With the new virtual environment created, it is time to activate it:"
},
{
"code": null,
"e": 2149,
"s": 2048,
"text": "(base) weimenglee@Wei-Mengs-Mini ~ % conda activate Project1(Project1) weimenglee@Wei-Mengs-Mini ~ %"
},
{
"code": null,
"e": 2315,
"s": 2149,
"text": "As you can see above, once the Project1 virtual environment is activated, you will see the name of the virtual environment (Project1) in front of the command prompt:"
},
{
"code": null,
"e": 2356,
"s": 2315,
"text": "(Project1) weimenglee@Wei-Mengs-Mini ~ %"
},
{
"code": null,
"e": 2463,
"s": 2356,
"text": "To know what are the packages currently installed in your virtual environment, use the pip freeze command:"
},
{
"code": null,
"e": 2515,
"s": 2463,
"text": "(Project1) weimenglee@Wei-Mengs-Mini ~ % pip freeze"
},
{
"code": null,
"e": 2707,
"s": 2515,
"text": "This command will return you a list of packages installed in the current environment, together with their version numbers. Here is an example of the output of my Project1 virtual environment:"
},
{
"code": null,
"e": 2726,
"s": 2707,
"text": "certifi==2021.5.30"
},
{
"code": null,
"e": 2872,
"s": 2726,
"text": "Occasionally the pip freeze command will include direct references for distributions installed from direct URL references, such as the following:"
},
{
"code": null,
"e": 2969,
"s": 2872,
"text": "certifi==2021.5.30chardet @ file:///Users/runner/miniforge3/conda-bld/chardet_1610093454858/work"
},
{
"code": null,
"e": 3055,
"s": 2969,
"text": "To prevent this from happening, use the following alternative command for pip freeze:"
},
{
"code": null,
"e": 3080,
"s": 3055,
"text": "pip list --format=freeze"
},
{
"code": null,
"e": 3144,
"s": 3080,
"text": "This will ensure that the result will always be in this format:"
},
{
"code": null,
"e": 3177,
"s": 3144,
"text": "<package_name>==<version_number>"
},
{
"code": null,
"e": 3294,
"s": 3177,
"text": "Let’s now try to install some additional packages in our Project1 virtual environment using the pip install command:"
},
{
"code": null,
"e": 3371,
"s": 3294,
"text": "(Project1) weimenglee@Wei-Mengs-Mini ~ % pip install pandas numpy matplotlib"
},
{
"code": null,
"e": 3422,
"s": 3371,
"text": "The above command installs the following packages:"
},
{
"code": null,
"e": 3429,
"s": 3422,
"text": "Pandas"
},
{
"code": null,
"e": 3435,
"s": 3429,
"text": "NumPy"
},
{
"code": null,
"e": 3446,
"s": 3435,
"text": "Matplotlib"
},
{
"code": null,
"e": 3603,
"s": 3446,
"text": "You can now use the pip freeze command (or pip list —-format=freeze) to view the list of packages you have, including the ones that you have just installed."
},
{
"code": null,
"e": 3821,
"s": 3603,
"text": "(Project1) weimenglee@Wei-Mengs-Mini ~ % pip freezecertifi==2021.5.30cycler==0.10.0kiwisolver==1.3.2matplotlib==3.4.3numpy==1.21.2pandas==1.3.2Pillow==8.3.2pyparsing==2.4.7python-dateutil==2.8.2pytz==2021.1six==1.16.0"
},
{
"code": null,
"e": 3896,
"s": 3821,
"text": "In addition, you will also save the list to a file named requirements.txt:"
},
{
"code": null,
"e": 3967,
"s": 3896,
"text": "(Project1) weimenglee@Wei-Mengs-Mini ~ % pip freeze > requirements.txt"
},
{
"code": null,
"e": 4162,
"s": 3967,
"text": "The requirements.txt file contains the list of packages that are installed in the current environment. You will make use of it later to reinstall all the packages in another virtual environment."
},
{
"code": null,
"e": 4363,
"s": 4162,
"text": "Key takeaway — whatever packages you install in this virtual environment stays in this virtual environment. It will not conflict with other similar packages you install in another virtual environment."
},
{
"code": null,
"e": 4483,
"s": 4363,
"text": "You can now test to see if the environment works correctly. Type the following command to start the Python interpreter:"
},
{
"code": null,
"e": 4531,
"s": 4483,
"text": "(Project1) weimenglee@Wei-Mengs-Mini ~ % python"
},
{
"code": null,
"e": 4590,
"s": 4531,
"text": "Then, import the Pandas package and print out its version:"
},
{
"code": null,
"e": 4637,
"s": 4590,
"text": ">>> import pandas>>> print(pandas.__version__)"
},
{
"code": null,
"e": 4716,
"s": 4637,
"text": "If you are able to see the output above, the packages are installed correctly."
},
{
"code": null,
"e": 4765,
"s": 4716,
"text": "Type exit() to exit from the Python interpreter."
},
{
"code": null,
"e": 4889,
"s": 4765,
"text": "When you are done with the environment, you can use the conda deactivate command to bring you back to the base environment:"
},
{
"code": null,
"e": 4947,
"s": 4889,
"text": "(Project1) weimenglee@Wei-Mengs-Mini ~ % conda deactivate"
},
{
"code": null,
"e": 5087,
"s": 4947,
"text": "After you are done with your project and have no more need for the environment, you can remove the environment using the following command:"
},
{
"code": null,
"e": 5235,
"s": 5087,
"text": "(base) weimenglee@Wei-Mengs-Mini ~ % conda env remove --name Project1Remove all packages in environment /Users/weimenglee/miniforge3/envs/Project1:"
},
{
"code": null,
"e": 5307,
"s": 5235,
"text": "Let’s now create another virtual environment and call it, say Project2:"
},
{
"code": null,
"e": 5384,
"s": 5307,
"text": "(base) weimenglee@Wei-Mengs-Mini ~ % conda create --name Project2 python=3.9"
},
{
"code": null,
"e": 5436,
"s": 5384,
"text": "Once created, activate the new virtual environment:"
},
{
"code": null,
"e": 5537,
"s": 5436,
"text": "(base) weimenglee@Wei-Mengs-Mini ~ % conda activate Project2(Project2) weimenglee@Wei-Mengs-Mini ~ %"
},
{
"code": null,
"e": 5613,
"s": 5537,
"text": "Let’s try the Python interpreter and see if the Pandas module is available:"
},
{
"code": null,
"e": 5960,
"s": 5613,
"text": "(Project2) weimenglee@Wei-Mengs-Mini ~ % pythonPython 3.9.6 (default, Aug 16 2021, 12:43:27)[Clang 12.0.0 ] :: Anaconda, Inc. on darwinType \"help\", \"copyright\", \"credits\" or \"license\" for more information.>>> import pandasTraceback (most recent call last):File \"<stdin>\", line 1, in <module>ModuleNotFoundError: No module named 'pandas'>>> exit()"
},
{
"code": null,
"e": 6185,
"s": 5960,
"text": "As predicted, Pandas is not installed by default. If you want to install the set of packages that you have installed in the Project1 virtual environment, you can now make use of the requirements.txt file you created earlier:"
},
{
"code": null,
"e": 6998,
"s": 6185,
"text": "(Project2) weimenglee@Wei-Mengs-Mini ~ % pip install -r requirements.txtRequirement already satisfied: certifi==2021.5.30 in ./miniforge3/envs/Project2/lib/python3.9/site-packages (from -r requirements.txt (line 1)) (2021.5.30)Collecting cycler==0.10.0...Collecting matplotlib==3.4.3Using cached matplotlib-3.4.3-cp39-cp39-macosx_11_0_arm64.whlCollecting numpy==1.21.2Using cached numpy-1.21.2-cp39-cp39-macosx_11_0_arm64.whl (12.4 MB)Collecting pandas==1.3.2Using cached pandas-1.3.2-cp39-cp39-macosx_11_0_arm64.whl...Installing collected packages: six, pytz, python-dateutil, pyparsing, Pillow, numpy, kiwisolver, cycler, pandas, matplotlibSuccessfully installed Pillow-8.3.2 cycler-0.10.0 kiwisolver-1.3.2 matplotlib-3.4.3 numpy-1.21.2 pandas-1.3.2 pyparsing-2.4.7 python-dateutil-2.8.2 pytz-2021.1 six-1.16.0"
},
{
"code": null,
"e": 7113,
"s": 6998,
"text": "All the packages specified in the requirements.txt file will now be installed in the Project2 virtual environment."
}
]
|
SQL Tutorial | SQL is a standard language for storing, manipulating and retrieving data
in databases.
Our SQL tutorial will teach you how to use SQL in:
MySQL, SQL Server, MS Access, Oracle, Sybase, Informix, Postgres, and other database systems.
With our online SQL editor, you can edit the SQL statements, and click on a button to view the result.
Click on the "Try it Yourself" button to see how it works.
Insert the missing statement to get all the columns from the Customers table.
* FROM Customers;
Start the Exercise
Learn by examples! This tutorial supplements all explanations with clarifying examples.
See All SQL Examples
Test your SQL skills at W3Schools!
Start SQL Quiz!
At W3Schools you will find a complete reference for keywords and function:
SQL Keyword Reference
MYSQL Functions
SQLServer Functions
MS Access Functions
SQL Quick Reference
Data types and ranges for Microsoft Access, MySQL and SQL Server.
SQL Data Types
Get certified by completing the SQL course
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 88,
"s": 0,
"text": "SQL is a standard language for storing, manipulating and retrieving data \nin databases."
},
{
"code": null,
"e": 233,
"s": 88,
"text": "Our SQL tutorial will teach you how to use SQL in:\nMySQL, SQL Server, MS Access, Oracle, Sybase, Informix, Postgres, and other database systems."
},
{
"code": null,
"e": 336,
"s": 233,
"text": "With our online SQL editor, you can edit the SQL statements, and click on a button to view the result."
},
{
"code": null,
"e": 395,
"s": 336,
"text": "Click on the \"Try it Yourself\" button to see how it works."
},
{
"code": null,
"e": 473,
"s": 395,
"text": "Insert the missing statement to get all the columns from the Customers table."
},
{
"code": null,
"e": 493,
"s": 473,
"text": " * FROM Customers;\n"
},
{
"code": null,
"e": 512,
"s": 493,
"text": "Start the Exercise"
},
{
"code": null,
"e": 600,
"s": 512,
"text": "Learn by examples! This tutorial supplements all explanations with clarifying examples."
},
{
"code": null,
"e": 621,
"s": 600,
"text": "See All SQL Examples"
},
{
"code": null,
"e": 656,
"s": 621,
"text": "Test your SQL skills at W3Schools!"
},
{
"code": null,
"e": 672,
"s": 656,
"text": "Start SQL Quiz!"
},
{
"code": null,
"e": 747,
"s": 672,
"text": "At W3Schools you will find a complete reference for keywords and function:"
},
{
"code": null,
"e": 769,
"s": 747,
"text": "SQL Keyword Reference"
},
{
"code": null,
"e": 785,
"s": 769,
"text": "MYSQL Functions"
},
{
"code": null,
"e": 805,
"s": 785,
"text": "SQLServer Functions"
},
{
"code": null,
"e": 825,
"s": 805,
"text": "MS Access Functions"
},
{
"code": null,
"e": 845,
"s": 825,
"text": "SQL Quick Reference"
},
{
"code": null,
"e": 911,
"s": 845,
"text": "Data types and ranges for Microsoft Access, MySQL and SQL Server."
},
{
"code": null,
"e": 926,
"s": 911,
"text": "SQL Data Types"
},
{
"code": null,
"e": 969,
"s": 926,
"text": "Get certified by completing the SQL course"
},
{
"code": null,
"e": 1002,
"s": 969,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1044,
"s": 1002,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1151,
"s": 1044,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1170,
"s": 1151,
"text": "[email protected]"
}
]
|
Maximum of sum and product of digits until number is reduced to a single digit - GeeksforGeeks | 26 Apr, 2021
Given a number N, the task is to print the maximum between the sum and multiplication of the digits of the given number until the number is reduced to a single digit. Note: Sum and multiplication of digits to be done until the number is reduced to a single digit.
Let’s take an example where N = 19,
19 breaks into 1+9=10 then 10 breaks into 1+0=1. 1 is a single digit sum. Also, 19 breaks into 1*9 = 9. 9 is a single digit multiplication. So, output is 9 i.e. maximum of 9 and 1.
Input: N = 631
Output: 8
Input: 110
Output: 2
Approach:
Check if a number is less than 10 then the sum and product will be the same. So, return that number.Else,Find the sum of digits repeatedly using Method 2 of Finding sum of digits of a number until sum becomes single digit.And, Find the product of digits repeatedly using Method 1 of Finding sum of digits of a number until sum becomes single digit.Return the maximum of both.
Check if a number is less than 10 then the sum and product will be the same. So, return that number.
Else,Find the sum of digits repeatedly using Method 2 of Finding sum of digits of a number until sum becomes single digit.And, Find the product of digits repeatedly using Method 1 of Finding sum of digits of a number until sum becomes single digit.
Find the sum of digits repeatedly using Method 2 of Finding sum of digits of a number until sum becomes single digit.
And, Find the product of digits repeatedly using Method 1 of Finding sum of digits of a number until sum becomes single digit.
Return the maximum of both.
Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// CPP implementation of above approach#include<bits/stdc++.h>using namespace std; // Function to sum the digits until it // becomes a single digit long repeatedSum(long n) { if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9); } // Function to product the digits until it // becomes a single digit long repeatedProduct(long n) { long prod = 1; // Loop to do sum while // sum is not less than // or equal to 9 while (n > 0 || prod > 9) { if (n == 0) { n = prod; prod = 1; } prod *= n % 10; n /= 10; } return prod; } // Function to find the maximum among // repeated sum and repeated product long maxSumProduct(long N) { if (N < 10) return N; return max(repeatedSum(N), repeatedProduct(N)); } // Driver code int main() { long n = 631; cout << maxSumProduct(n)<<endl; return 0; }// This code is contributed by mits
// Java implementation of above approachimport java.util.*;import java.lang.*;import java.io.*; class GFG { // Function to sum the digits until it // becomes a single digit public static long repeatedSum(long n) { if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9); } // Function to product the digits until it // becomes a single digit public static long repeatedProduct(long n) { long prod = 1; // Loop to do sum while // sum is not less than // or equal to 9 while (n > 0 || prod > 9) { if (n == 0) { n = prod; prod = 1; } prod *= n % 10; n /= 10; } return prod; } // Function to find the maximum among // repeated sum and repeated product public static long maxSumProduct(long N) { if (N < 10) return N; return Math.max(repeatedSum(N), repeatedProduct(N)); } // Driver code public static void main(String[] args) { long n = 631; System.out.println(maxSumProduct(n)); }}
# Python 3 implementation of above approach # Function to sum the digits until# it becomes a single digitdef repeatedSum(n): if (n == 0): return 0 return 9 if(n % 9 == 0) else (n % 9) # Function to product the digits# until it becomes a single digitdef repeatedProduct(n): prod = 1 # Loop to do sum while # sum is not less than # or equal to 9 while (n > 0 or prod > 9) : if (n == 0) : n = prod prod = 1 prod *= n % 10 n //= 10 return prod # Function to find the maximum among# repeated sum and repeated productdef maxSumProduct(N): if (N < 10): return N return max(repeatedSum(N), repeatedProduct(N)) # Driver codeif __name__ == "__main__": n = 631 print(maxSumProduct(n)) # This code is contributed# by ChitraNayal
// C# implementation of// above approachusing System;class GFG{ // Function to sum the digits// until it becomes a single digitpublic static long repeatedSum(long n){ if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9);} // Function to product the digits// until it becomes a single digitpublic static long repeatedProduct(long n){ long prod = 1; // Loop to do sum while // sum is not less than // or equal to 9 while (n > 0 || prod > 9) { if (n == 0) { n = prod; prod = 1; } prod *= n % 10; n /= 10; } return prod;} // Function to find the maximum among// repeated sum and repeated productpublic static long maxSumProduct(long N){ if (N < 10) return N; return Math.Max(repeatedSum(N), repeatedProduct(N));} // Driver codepublic static void Main(){ long n = 631; Console.WriteLine(maxSumProduct(n));}} // This code is contributed// by inder_verma
<script>// javascript implementation of above approach // Function to sum the digits until it // becomes a single digit function repeatedSum(n) { if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9); } // Function to product the digits until it // becomes a single digit function repeatedProduct(n) { var prod = 1; // Loop to do sum while // sum is not less than // or equal to 9 while (n > 0 || prod > 9) { if (n == 0) { n = prod; prod = 1; } prod *= n % 10; n = parseInt(n/10); } return prod; } // Function to find the maximum among // repeated sum and repeated product function maxSumProduct(N) { if (N < 10) return N; return Math.max(repeatedSum(N), repeatedProduct(N)); } // Driver code var n = 631; document.write(maxSumProduct(n)); // This code contributed by aashish1995</script>
8
inderDuMCA
ukasp
Mithun Kumar
aashish1995
number-digits
number-theory
Mathematical
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Fizz Buzz Implementation
Program to multiply two matrices
Modular multiplicative inverse
Check if a number is Palindrome
Find first and last digits of a number
Count ways to reach the n'th stair
Find Union and Intersection of two unsorted arrays
Program to convert a given number to words | [
{
"code": null,
"e": 24692,
"s": 24664,
"text": "\n26 Apr, 2021"
},
{
"code": null,
"e": 24958,
"s": 24692,
"text": "Given a number N, the task is to print the maximum between the sum and multiplication of the digits of the given number until the number is reduced to a single digit. Note: Sum and multiplication of digits to be done until the number is reduced to a single digit. "
},
{
"code": null,
"e": 24994,
"s": 24958,
"text": "Let’s take an example where N = 19,"
},
{
"code": null,
"e": 25177,
"s": 24994,
"text": "19 breaks into 1+9=10 then 10 breaks into 1+0=1. 1 is a single digit sum. Also, 19 breaks into 1*9 = 9. 9 is a single digit multiplication. So, output is 9 i.e. maximum of 9 and 1. "
},
{
"code": null,
"e": 25224,
"s": 25177,
"text": "Input: N = 631\nOutput: 8\n\nInput: 110\nOutput: 2"
},
{
"code": null,
"e": 25236,
"s": 25224,
"text": "Approach: "
},
{
"code": null,
"e": 25612,
"s": 25236,
"text": "Check if a number is less than 10 then the sum and product will be the same. So, return that number.Else,Find the sum of digits repeatedly using Method 2 of Finding sum of digits of a number until sum becomes single digit.And, Find the product of digits repeatedly using Method 1 of Finding sum of digits of a number until sum becomes single digit.Return the maximum of both."
},
{
"code": null,
"e": 25713,
"s": 25612,
"text": "Check if a number is less than 10 then the sum and product will be the same. So, return that number."
},
{
"code": null,
"e": 25962,
"s": 25713,
"text": "Else,Find the sum of digits repeatedly using Method 2 of Finding sum of digits of a number until sum becomes single digit.And, Find the product of digits repeatedly using Method 1 of Finding sum of digits of a number until sum becomes single digit."
},
{
"code": null,
"e": 26080,
"s": 25962,
"text": "Find the sum of digits repeatedly using Method 2 of Finding sum of digits of a number until sum becomes single digit."
},
{
"code": null,
"e": 26207,
"s": 26080,
"text": "And, Find the product of digits repeatedly using Method 1 of Finding sum of digits of a number until sum becomes single digit."
},
{
"code": null,
"e": 26235,
"s": 26207,
"text": "Return the maximum of both."
},
{
"code": null,
"e": 26284,
"s": 26235,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 26288,
"s": 26284,
"text": "C++"
},
{
"code": null,
"e": 26293,
"s": 26288,
"text": "Java"
},
{
"code": null,
"e": 26301,
"s": 26293,
"text": "Python3"
},
{
"code": null,
"e": 26304,
"s": 26301,
"text": "C#"
},
{
"code": null,
"e": 26315,
"s": 26304,
"text": "Javascript"
},
{
"code": "// CPP implementation of above approach#include<bits/stdc++.h>using namespace std; // Function to sum the digits until it // becomes a single digit long repeatedSum(long n) { if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9); } // Function to product the digits until it // becomes a single digit long repeatedProduct(long n) { long prod = 1; // Loop to do sum while // sum is not less than // or equal to 9 while (n > 0 || prod > 9) { if (n == 0) { n = prod; prod = 1; } prod *= n % 10; n /= 10; } return prod; } // Function to find the maximum among // repeated sum and repeated product long maxSumProduct(long N) { if (N < 10) return N; return max(repeatedSum(N), repeatedProduct(N)); } // Driver code int main() { long n = 631; cout << maxSumProduct(n)<<endl; return 0; }// This code is contributed by mits",
"e": 27390,
"s": 26315,
"text": null
},
{
"code": "// Java implementation of above approachimport java.util.*;import java.lang.*;import java.io.*; class GFG { // Function to sum the digits until it // becomes a single digit public static long repeatedSum(long n) { if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9); } // Function to product the digits until it // becomes a single digit public static long repeatedProduct(long n) { long prod = 1; // Loop to do sum while // sum is not less than // or equal to 9 while (n > 0 || prod > 9) { if (n == 0) { n = prod; prod = 1; } prod *= n % 10; n /= 10; } return prod; } // Function to find the maximum among // repeated sum and repeated product public static long maxSumProduct(long N) { if (N < 10) return N; return Math.max(repeatedSum(N), repeatedProduct(N)); } // Driver code public static void main(String[] args) { long n = 631; System.out.println(maxSumProduct(n)); }}",
"e": 28521,
"s": 27390,
"text": null
},
{
"code": "# Python 3 implementation of above approach # Function to sum the digits until# it becomes a single digitdef repeatedSum(n): if (n == 0): return 0 return 9 if(n % 9 == 0) else (n % 9) # Function to product the digits# until it becomes a single digitdef repeatedProduct(n): prod = 1 # Loop to do sum while # sum is not less than # or equal to 9 while (n > 0 or prod > 9) : if (n == 0) : n = prod prod = 1 prod *= n % 10 n //= 10 return prod # Function to find the maximum among# repeated sum and repeated productdef maxSumProduct(N): if (N < 10): return N return max(repeatedSum(N), repeatedProduct(N)) # Driver codeif __name__ == \"__main__\": n = 631 print(maxSumProduct(n)) # This code is contributed# by ChitraNayal",
"e": 29367,
"s": 28521,
"text": null
},
{
"code": "// C# implementation of// above approachusing System;class GFG{ // Function to sum the digits// until it becomes a single digitpublic static long repeatedSum(long n){ if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9);} // Function to product the digits// until it becomes a single digitpublic static long repeatedProduct(long n){ long prod = 1; // Loop to do sum while // sum is not less than // or equal to 9 while (n > 0 || prod > 9) { if (n == 0) { n = prod; prod = 1; } prod *= n % 10; n /= 10; } return prod;} // Function to find the maximum among// repeated sum and repeated productpublic static long maxSumProduct(long N){ if (N < 10) return N; return Math.Max(repeatedSum(N), repeatedProduct(N));} // Driver codepublic static void Main(){ long n = 631; Console.WriteLine(maxSumProduct(n));}} // This code is contributed// by inder_verma",
"e": 30374,
"s": 29367,
"text": null
},
{
"code": "<script>// javascript implementation of above approach // Function to sum the digits until it // becomes a single digit function repeatedSum(n) { if (n == 0) return 0; return (n % 9 == 0) ? 9 : (n % 9); } // Function to product the digits until it // becomes a single digit function repeatedProduct(n) { var prod = 1; // Loop to do sum while // sum is not less than // or equal to 9 while (n > 0 || prod > 9) { if (n == 0) { n = prod; prod = 1; } prod *= n % 10; n = parseInt(n/10); } return prod; } // Function to find the maximum among // repeated sum and repeated product function maxSumProduct(N) { if (N < 10) return N; return Math.max(repeatedSum(N), repeatedProduct(N)); } // Driver code var n = 631; document.write(maxSumProduct(n)); // This code contributed by aashish1995</script>",
"e": 31403,
"s": 30374,
"text": null
},
{
"code": null,
"e": 31405,
"s": 31403,
"text": "8"
},
{
"code": null,
"e": 31418,
"s": 31407,
"text": "inderDuMCA"
},
{
"code": null,
"e": 31424,
"s": 31418,
"text": "ukasp"
},
{
"code": null,
"e": 31437,
"s": 31424,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 31449,
"s": 31437,
"text": "aashish1995"
},
{
"code": null,
"e": 31463,
"s": 31449,
"text": "number-digits"
},
{
"code": null,
"e": 31477,
"s": 31463,
"text": "number-theory"
},
{
"code": null,
"e": 31490,
"s": 31477,
"text": "Mathematical"
},
{
"code": null,
"e": 31504,
"s": 31490,
"text": "number-theory"
},
{
"code": null,
"e": 31517,
"s": 31504,
"text": "Mathematical"
},
{
"code": null,
"e": 31615,
"s": 31517,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31647,
"s": 31615,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 31691,
"s": 31647,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 31716,
"s": 31691,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 31749,
"s": 31716,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 31780,
"s": 31749,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 31812,
"s": 31780,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 31851,
"s": 31812,
"text": "Find first and last digits of a number"
},
{
"code": null,
"e": 31886,
"s": 31851,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 31937,
"s": 31886,
"text": "Find Union and Intersection of two unsorted arrays"
}
]
|
Functions in Java - GeeksQuiz | 03 Dec, 2021
ab cd
ef gh
ij kl
ab
cd;ef
gh;ij
kl
hashCode of object1 is equal to object2
value of object1 is equal to object2
hashCode of object1 is equal to object2
memory address of object1 is same as object2
value of object1 is equal to object2
memory address of object1 is same as object2
value of object1 is equal to object2
obj1.a = 10
obj2.a = 20
obj1.a = 20
obj2.a = 20
obj1.a = 10
obj2.a = 10
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
Microsoft Interview Experience for Internship (Via Engage)
Difference between var, let and const keywords in JavaScript
Find number of rectangles that can be formed from a given set of coordinates
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
Infosys DSE Interview Experience | On-Campus 2021 | [
{
"code": null,
"e": 27219,
"s": 27191,
"text": "\n03 Dec, 2021"
},
{
"code": null,
"e": 27237,
"s": 27219,
"text": "ab cd\nef gh\nij kl"
},
{
"code": null,
"e": 27255,
"s": 27237,
"text": "ab\ncd;ef\ngh;ij\nkl"
},
{
"code": null,
"e": 27332,
"s": 27255,
"text": "hashCode of object1 is equal to object2\nvalue of object1 is equal to object2"
},
{
"code": null,
"e": 27454,
"s": 27332,
"text": "hashCode of object1 is equal to object2\nmemory address of object1 is same as object2\nvalue of object1 is equal to object2"
},
{
"code": null,
"e": 27536,
"s": 27454,
"text": "memory address of object1 is same as object2\nvalue of object1 is equal to object2"
},
{
"code": null,
"e": 27560,
"s": 27536,
"text": "obj1.a = 10\nobj2.a = 20"
},
{
"code": null,
"e": 27584,
"s": 27560,
"text": "obj1.a = 20\nobj2.a = 20"
},
{
"code": null,
"e": 27608,
"s": 27584,
"text": "obj1.a = 10\nobj2.a = 10"
},
{
"code": null,
"e": 27706,
"s": 27608,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 27715,
"s": 27706,
"text": "Comments"
},
{
"code": null,
"e": 27728,
"s": 27715,
"text": "Old Comments"
},
{
"code": null,
"e": 27781,
"s": 27728,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 27840,
"s": 27781,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 27901,
"s": 27840,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27978,
"s": 27901,
"text": "Find number of rectangles that can be formed from a given set of coordinates"
},
{
"code": null,
"e": 28016,
"s": 27978,
"text": "Array of Objects in C++ with Examples"
},
{
"code": null,
"e": 28078,
"s": 28016,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 28119,
"s": 28078,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 28162,
"s": 28119,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 28198,
"s": 28162,
"text": "How to Read Text Files with Pandas?"
}
]
|
File.AppendText() Method in C# with Examples - GeeksforGeeks | 20 Jun, 2021
File.AppendText() is an inbuilt File class method which is used to create a StreamWriter that appends UTF-8 encoded text to an existing file else it creates a new file if the specified file does not exist.Syntax:
public static System.IO.StreamWriter AppendText (string path);
Parameter: This function accepts a parameter which is illustrated below:
path: This is the file where UTF-8 encoded texts are going to be appended. The file is created if it doesn’t already exist.
Exceptions
UnauthorizedAccessException: The caller does not have the required permission.
ArgumentException: The path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.
ArgumentNullException: The path is null.
PathTooLongException: The given path, file name, or both exceed the system-defined maximum length.
DirectoryNotFoundException: The given path is invalid i.e, the directory doesn’t exist or it is on an unmapped drive.
NotSupportedException: The path is in an invalid format.
Return Value: Returns a stream writer that appends specified UTF-8 encoded texts to the specified file or to a new file.Below are the programs to illustrate the File.AppendText() method.Program 1: Before running the below code, a file file.txt is created with some contents which is shown below:
CSharp
// C# program to illustrate the usage// of File.AppendText() method // Using System, System.IO namespacesusing System;using System.IO; class GFG { // Main method public static void Main() { // Creating a file string myfile = @"file.txt"; // Appending the given texts using(StreamWriter sw = File.AppendText(myfile)) { sw.WriteLine("Gfg"); sw.WriteLine("GFG"); sw.WriteLine("GeeksforGeeks"); } // Opening the file for reading using(StreamReader sr = File.OpenText(myfile)) { string s = ""; while ((s = sr.ReadLine()) != null) { Console.WriteLine(s); } } }}
Executing:
mcs -out:main.exe main.cs
mono main.exe
Geeks
Gfg
GFG
GeeksforGeeks
After running the above code, above output is shown and the existing file file.txt becomes like below:
Program 2: Initially, no file is created and hence below code itself create a file named as file.txt
CSharp
// C# program to illustrate the usage// of File.AppendText() method // Using System, System.IO namespacesusing System;using System.IO; class GFG { // Main method public static void Main() { // Creating a file string myfile = @"file.txt"; // Checking the above file if (!File.Exists(myfile)) { // Creating the same file if it doesn't exist using(StreamWriter sw = File.CreateText(myfile)) { sw.WriteLine("GeeksforGeeks"); sw.WriteLine("is"); sw.WriteLine("a"); } } // Appending the given texts using(StreamWriter sw = File.AppendText(myfile)) { sw.WriteLine("computer"); sw.WriteLine("science"); sw.WriteLine("portal."); } // Opening the file for reading using(StreamReader sr = File.OpenText(myfile)) { string s = ""; while ((s = sr.ReadLine()) != null) { Console.WriteLine(s); } } }}
Executing:
mcs -out:main.exe main.cs
mono main.exe
GeeksforGeeks
is
a
computer
science
portal.
After running the above code, a new file file.txt is created which is shown below:
sweetyty
CSharp-File-Handling
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Method Overriding
C# | Class and Object
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
C# | Constructors
C# | Delegates
Introduction to .NET Framework
Difference between Ref and Out keywords in C#
C# | Data Types
Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework | [
{
"code": null,
"e": 24790,
"s": 24762,
"text": "\n20 Jun, 2021"
},
{
"code": null,
"e": 25005,
"s": 24790,
"text": "File.AppendText() is an inbuilt File class method which is used to create a StreamWriter that appends UTF-8 encoded text to an existing file else it creates a new file if the specified file does not exist.Syntax: "
},
{
"code": null,
"e": 25068,
"s": 25005,
"text": "public static System.IO.StreamWriter AppendText (string path);"
},
{
"code": null,
"e": 25143,
"s": 25068,
"text": "Parameter: This function accepts a parameter which is illustrated below: "
},
{
"code": null,
"e": 25267,
"s": 25143,
"text": "path: This is the file where UTF-8 encoded texts are going to be appended. The file is created if it doesn’t already exist."
},
{
"code": null,
"e": 25280,
"s": 25267,
"text": "Exceptions "
},
{
"code": null,
"e": 25359,
"s": 25280,
"text": "UnauthorizedAccessException: The caller does not have the required permission."
},
{
"code": null,
"e": 25514,
"s": 25359,
"text": "ArgumentException: The path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars."
},
{
"code": null,
"e": 25555,
"s": 25514,
"text": "ArgumentNullException: The path is null."
},
{
"code": null,
"e": 25654,
"s": 25555,
"text": "PathTooLongException: The given path, file name, or both exceed the system-defined maximum length."
},
{
"code": null,
"e": 25772,
"s": 25654,
"text": "DirectoryNotFoundException: The given path is invalid i.e, the directory doesn’t exist or it is on an unmapped drive."
},
{
"code": null,
"e": 25829,
"s": 25772,
"text": "NotSupportedException: The path is in an invalid format."
},
{
"code": null,
"e": 26126,
"s": 25829,
"text": "Return Value: Returns a stream writer that appends specified UTF-8 encoded texts to the specified file or to a new file.Below are the programs to illustrate the File.AppendText() method.Program 1: Before running the below code, a file file.txt is created with some contents which is shown below: "
},
{
"code": null,
"e": 26135,
"s": 26128,
"text": "CSharp"
},
{
"code": "// C# program to illustrate the usage// of File.AppendText() method // Using System, System.IO namespacesusing System;using System.IO; class GFG { // Main method public static void Main() { // Creating a file string myfile = @\"file.txt\"; // Appending the given texts using(StreamWriter sw = File.AppendText(myfile)) { sw.WriteLine(\"Gfg\"); sw.WriteLine(\"GFG\"); sw.WriteLine(\"GeeksforGeeks\"); } // Opening the file for reading using(StreamReader sr = File.OpenText(myfile)) { string s = \"\"; while ((s = sr.ReadLine()) != null) { Console.WriteLine(s); } } }}",
"e": 26856,
"s": 26135,
"text": null
},
{
"code": null,
"e": 26869,
"s": 26856,
"text": "Executing: "
},
{
"code": null,
"e": 26937,
"s": 26869,
"text": "mcs -out:main.exe main.cs\nmono main.exe\nGeeks\nGfg\nGFG\nGeeksforGeeks"
},
{
"code": null,
"e": 27042,
"s": 26937,
"text": "After running the above code, above output is shown and the existing file file.txt becomes like below: "
},
{
"code": null,
"e": 27144,
"s": 27042,
"text": "Program 2: Initially, no file is created and hence below code itself create a file named as file.txt "
},
{
"code": null,
"e": 27151,
"s": 27144,
"text": "CSharp"
},
{
"code": "// C# program to illustrate the usage// of File.AppendText() method // Using System, System.IO namespacesusing System;using System.IO; class GFG { // Main method public static void Main() { // Creating a file string myfile = @\"file.txt\"; // Checking the above file if (!File.Exists(myfile)) { // Creating the same file if it doesn't exist using(StreamWriter sw = File.CreateText(myfile)) { sw.WriteLine(\"GeeksforGeeks\"); sw.WriteLine(\"is\"); sw.WriteLine(\"a\"); } } // Appending the given texts using(StreamWriter sw = File.AppendText(myfile)) { sw.WriteLine(\"computer\"); sw.WriteLine(\"science\"); sw.WriteLine(\"portal.\"); } // Opening the file for reading using(StreamReader sr = File.OpenText(myfile)) { string s = \"\"; while ((s = sr.ReadLine()) != null) { Console.WriteLine(s); } } }}",
"e": 28212,
"s": 27151,
"text": null
},
{
"code": null,
"e": 28225,
"s": 28212,
"text": "Executing: "
},
{
"code": null,
"e": 28309,
"s": 28225,
"text": "mcs -out:main.exe main.cs\nmono main.exe\nGeeksforGeeks\nis\na\ncomputer\nscience\nportal."
},
{
"code": null,
"e": 28393,
"s": 28309,
"text": "After running the above code, a new file file.txt is created which is shown below: "
},
{
"code": null,
"e": 28404,
"s": 28395,
"text": "sweetyty"
},
{
"code": null,
"e": 28425,
"s": 28404,
"text": "CSharp-File-Handling"
},
{
"code": null,
"e": 28428,
"s": 28425,
"text": "C#"
},
{
"code": null,
"e": 28526,
"s": 28428,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28535,
"s": 28526,
"text": "Comments"
},
{
"code": null,
"e": 28548,
"s": 28535,
"text": "Old Comments"
},
{
"code": null,
"e": 28571,
"s": 28548,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 28593,
"s": 28571,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 28633,
"s": 28593,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 28656,
"s": 28633,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28674,
"s": 28656,
"text": "C# | Constructors"
},
{
"code": null,
"e": 28689,
"s": 28674,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28720,
"s": 28689,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 28766,
"s": 28720,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 28782,
"s": 28766,
"text": "C# | Data Types"
}
]
|
How to create a clickable dropdown menu with CSS and JavaScript? | Following is the code to create a clickable dropdown menu using CSS and JavaScript −
Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
.menu-btn {
background-color: #7e32d4;
color: white;
padding: 16px;
font-size: 20px;
font-weight: bolder;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
border: none;
}
.dropdown-menu {
position: relative;
display: inline-block;
}
.menu-content {
display: none;
position: absolute;
background-color: #017575;
min-width: 160px;
z-index: 1;
}
.links {
color: rgb(255, 255, 255);
padding: 12px 16px;
text-decoration: none;
display: block;
font-size: 18px;
font-weight: bold;
border-bottom: 1px solid black;
}
.links:hover {
background-color: rgb(8, 107, 46);
}
.dropdown-menu:hover .menu-btn {
background-color: #3e8e41;
}
</style>
</head>
<body>
<h2>Click on the below dropdown button to open/close dropdown menu</h2>
<div class="dropdown-menu">
<button class="menu-btn">Open <</button>
<div class="menu-content">
<a class="links" href="#">Contact Us</a>
<a class="links" href="#">Visit Us</a>
<a class="links" href="#">About Us</a>
</div>
</div>
<script>
let dropdownBtn = document.querySelector('.menu-btn');
let menuContent = document.querySelector('.menu-content');
dropdownBtn.addEventListener('click',()=>{
if(menuContent.style.display===""){
menuContent.style.display="block";
} else {
menuContent.style.display="";
}
})
</script>
</body>
</html>
The above code will produce the following output −
On clicking the open button − | [
{
"code": null,
"e": 1147,
"s": 1062,
"text": "Following is the code to create a clickable dropdown menu using CSS and JavaScript −"
},
{
"code": null,
"e": 1158,
"s": 1147,
"text": " Live Demo"
},
{
"code": null,
"e": 2624,
"s": 1158,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\n.menu-btn {\n background-color: #7e32d4;\n color: white;\n padding: 16px;\n font-size: 20px;\n font-weight: bolder;\n font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n border: none;\n}\n.dropdown-menu {\n position: relative;\n display: inline-block;\n}\n.menu-content {\n display: none;\n position: absolute;\n background-color: #017575;\n min-width: 160px;\n z-index: 1;\n}\n.links {\n color: rgb(255, 255, 255);\n padding: 12px 16px;\n text-decoration: none;\n display: block;\n font-size: 18px;\n font-weight: bold;\n border-bottom: 1px solid black;\n}\n.links:hover {\n background-color: rgb(8, 107, 46);\n}\n.dropdown-menu:hover .menu-btn {\n background-color: #3e8e41;\n}\n</style>\n</head>\n<body>\n<h2>Click on the below dropdown button to open/close dropdown menu</h2>\n<div class=\"dropdown-menu\">\n<button class=\"menu-btn\">Open <</button>\n<div class=\"menu-content\">\n<a class=\"links\" href=\"#\">Contact Us</a>\n<a class=\"links\" href=\"#\">Visit Us</a>\n<a class=\"links\" href=\"#\">About Us</a>\n</div>\n</div>\n<script>\nlet dropdownBtn = document.querySelector('.menu-btn');\nlet menuContent = document.querySelector('.menu-content');\ndropdownBtn.addEventListener('click',()=>{\n if(menuContent.style.display===\"\"){\n menuContent.style.display=\"block\";\n } else {\n menuContent.style.display=\"\";\n }\n})\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2675,
"s": 2624,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2705,
"s": 2675,
"text": "On clicking the open button −"
}
]
|
How to Index Data in Pandas with Python | by Luay Matalka | Towards Data Science | Indexing a dataframe in pandas is an extremely important skill to have and master. Indexing just means selecting specific rows and/or columns in a dataframe or series. In this tutorial, we will cover the loc and iloc methods, which are two of the most common ways of indexing a dataframe in pandas. I will be working with the ufo sightings dataset found here in jupyter notebook.
Before we start, let’s read in our data into a dataframe and take a look at the top 5 rows of our ufo dataframe:
And let’s take a look at some other information about our dataframe:
We used the shape and columns attributes to get the shape of our dataframe (number of rows, number of columns) and the column names, respectively.
Probably the most versatile method to index a dataframe is the loc method. loc is both a dataframe and series method, meaning you can call the loc method on either of those pandas objects. When using the loc method on a dataframe, we specify which rows and which columns we want using the following format: dataframe.loc[specified rows: specified columns]. There are different ways to specify which rows and columns we want to select. For example, we can pass in a single label, a list or array of labels, a slice object with labels, or a boolean array. Let’s go over each of these ways!
One way we can specify which rows and/or columns we want is by using labels. For rows, the label is the index value of that row, and for columns, the column name is the label. For example, in our ufo dataframe, if we want the fifth row only along with all the columns, we would use the following:
ufo.loc[4, :]
So we specified which rows we want by using the label of that specific row, which is 4, and since we wanted all of the columns, we would just use a colon.
Note: We could have left out the colon and we would have gotten the same output, however, it is better for code readability to leave the colon in to explicitly show we want all columns.
Let’s say we want multiple rows and/or columns. How would we specify that? Well, with using labels, we can either enter a list of labels, or use something similar to the slice notation that you may be familiar with.
Let’s start with the list of labels:
Note how we can just specify the row and column labels with a list of labels.
betterprogramming.pub
We can also use slice notation with this format: start label: stop label. However, in contrast to using slice notation with lists or strings, both the start AND stop labels are included in our output as shown below:
Note how row labels 3, 4, AND 5 were included in our output dataframe. Also note how the City, Colors Reported, and Shape Reported columns were included, even though we stopped at Shape Reported with our slice object. Remember, ufo.columns returned a list with the order of City, Colors Reported, Shape Reported, State, and Time. We are including everything from the City label to the Shape Reported label, which includes the Colors Reported label as well.
towardsdatascience.com
Lastly, we can use an array of boolean values. However, this array of boolean values must have the same length as the axis we are using it on. For example, our ufo dataframe has a shape of (18241, 5) according to the shape attribute we used above, meaning it has 18241 rows and 5 columns. So if we want to use a boolean array to specify our rows, then it would need to have a length of 18241 elements. If we want to use a boolean array to specify our columns, it would need to have a length of 5 elements. The most common way of creating this boolean array is by using a conditional.
For example, let’s say we wanted to select only the rows that included Abilene as the city in which the ufo sightings took place. We can start with the following condition:
ufo.City == ‘Abilene’
Note how this returns a pandas series (or array like object) that has a length of 18241 and is made up of boolean values (True or False). This is the exact number of values we need to be able to use this boolean array to specify our rows using the loc method. Imagine you are overlaying this series of True and False values over the index of our ufo dataframe. Wherever there is a True boolean value in this series, that specific row will be selected and will show up in our dataframe. Here we can see that the index or label of 3 is True (in the 4th row), which means that the first row we will see once we use this array of boolean values with our loc method is the row with the label 3 (or 4th row in our ufo dataframe).
ufo.loc[ufo.City == ‘Abilene’, :]
And that is exactly what we see! We have specified the rows we want using an array of boolean values with a length equal to the number of rows in our original dataframe.
Remember, we can combine these different ways of specifying rows and columns, meaning we can use one way of indexing on the rows and a different way on the columns. For example:
ufo.loc[ufo.City == ‘Abilene’, ‘City’:’State’]
Note how we used a condition that returns an array of boolean values to specify the rows and the slice object using labels to specify the columns.
towardsdatascience.com
The iloc method is also both a dataframe and series method that can be used to index a dataframe (or series). The i in iloc stands for integer, since instead of labels we are using integer-location based indexing based on the position of the rows and columns. Just like with the loc method, we can input an integer or list of integers, a slice object with integer locations, or a boolean array. Let’s just look at one key difference between the loc and iloc methods:
In our ufo dataframe, we did not change the index, so the default index of our dataframe is just the integer location of our rows. However, let’s try using the slice object to specify our rows using the iloc method:
ufo.iloc[3:5, :]
Note how when using the slice object with the iloc method, the stop integer location is NOT included in our dataframe. So we are only seeing rows 3 and 4, but not row 5. This is in contrast with the loc method where both the start and stop labels are included in our dataframe.
Let’s use the iloc method to specify the columns we want as well:
ufo.iloc[3:5, 1:3]
If we look at the columns of our dataframe for reference, we can see that we are slicing our columns from index 1, or the Colors Reported, to index 2, which is Shape Reported. We do not include the index of our stop, which is 3 with the value of State in this case.
Note: We could have used a callable function for either the loc or iloc methods that returns a valid output for indexing (any of the inputs we discussed above). However, we will save that for another tutorial.
All the code used in this tutorial can be seen here:
towardsdatascience.com
In this tutorial, we learned how to index a dataframe with both the loc and iloc methods. We learned how the loc method works primarily with labels of the rows and columns, and the iloc method works with integer locations. We also saw how we can use boolean arrays to index or specify our rows and columns. | [
{
"code": null,
"e": 551,
"s": 171,
"text": "Indexing a dataframe in pandas is an extremely important skill to have and master. Indexing just means selecting specific rows and/or columns in a dataframe or series. In this tutorial, we will cover the loc and iloc methods, which are two of the most common ways of indexing a dataframe in pandas. I will be working with the ufo sightings dataset found here in jupyter notebook."
},
{
"code": null,
"e": 664,
"s": 551,
"text": "Before we start, let’s read in our data into a dataframe and take a look at the top 5 rows of our ufo dataframe:"
},
{
"code": null,
"e": 733,
"s": 664,
"text": "And let’s take a look at some other information about our dataframe:"
},
{
"code": null,
"e": 880,
"s": 733,
"text": "We used the shape and columns attributes to get the shape of our dataframe (number of rows, number of columns) and the column names, respectively."
},
{
"code": null,
"e": 1468,
"s": 880,
"text": "Probably the most versatile method to index a dataframe is the loc method. loc is both a dataframe and series method, meaning you can call the loc method on either of those pandas objects. When using the loc method on a dataframe, we specify which rows and which columns we want using the following format: dataframe.loc[specified rows: specified columns]. There are different ways to specify which rows and columns we want to select. For example, we can pass in a single label, a list or array of labels, a slice object with labels, or a boolean array. Let’s go over each of these ways!"
},
{
"code": null,
"e": 1765,
"s": 1468,
"text": "One way we can specify which rows and/or columns we want is by using labels. For rows, the label is the index value of that row, and for columns, the column name is the label. For example, in our ufo dataframe, if we want the fifth row only along with all the columns, we would use the following:"
},
{
"code": null,
"e": 1779,
"s": 1765,
"text": "ufo.loc[4, :]"
},
{
"code": null,
"e": 1934,
"s": 1779,
"text": "So we specified which rows we want by using the label of that specific row, which is 4, and since we wanted all of the columns, we would just use a colon."
},
{
"code": null,
"e": 2120,
"s": 1934,
"text": "Note: We could have left out the colon and we would have gotten the same output, however, it is better for code readability to leave the colon in to explicitly show we want all columns."
},
{
"code": null,
"e": 2336,
"s": 2120,
"text": "Let’s say we want multiple rows and/or columns. How would we specify that? Well, with using labels, we can either enter a list of labels, or use something similar to the slice notation that you may be familiar with."
},
{
"code": null,
"e": 2373,
"s": 2336,
"text": "Let’s start with the list of labels:"
},
{
"code": null,
"e": 2451,
"s": 2373,
"text": "Note how we can just specify the row and column labels with a list of labels."
},
{
"code": null,
"e": 2473,
"s": 2451,
"text": "betterprogramming.pub"
},
{
"code": null,
"e": 2689,
"s": 2473,
"text": "We can also use slice notation with this format: start label: stop label. However, in contrast to using slice notation with lists or strings, both the start AND stop labels are included in our output as shown below:"
},
{
"code": null,
"e": 3146,
"s": 2689,
"text": "Note how row labels 3, 4, AND 5 were included in our output dataframe. Also note how the City, Colors Reported, and Shape Reported columns were included, even though we stopped at Shape Reported with our slice object. Remember, ufo.columns returned a list with the order of City, Colors Reported, Shape Reported, State, and Time. We are including everything from the City label to the Shape Reported label, which includes the Colors Reported label as well."
},
{
"code": null,
"e": 3169,
"s": 3146,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3753,
"s": 3169,
"text": "Lastly, we can use an array of boolean values. However, this array of boolean values must have the same length as the axis we are using it on. For example, our ufo dataframe has a shape of (18241, 5) according to the shape attribute we used above, meaning it has 18241 rows and 5 columns. So if we want to use a boolean array to specify our rows, then it would need to have a length of 18241 elements. If we want to use a boolean array to specify our columns, it would need to have a length of 5 elements. The most common way of creating this boolean array is by using a conditional."
},
{
"code": null,
"e": 3926,
"s": 3753,
"text": "For example, let’s say we wanted to select only the rows that included Abilene as the city in which the ufo sightings took place. We can start with the following condition:"
},
{
"code": null,
"e": 3948,
"s": 3926,
"text": "ufo.City == ‘Abilene’"
},
{
"code": null,
"e": 4672,
"s": 3948,
"text": "Note how this returns a pandas series (or array like object) that has a length of 18241 and is made up of boolean values (True or False). This is the exact number of values we need to be able to use this boolean array to specify our rows using the loc method. Imagine you are overlaying this series of True and False values over the index of our ufo dataframe. Wherever there is a True boolean value in this series, that specific row will be selected and will show up in our dataframe. Here we can see that the index or label of 3 is True (in the 4th row), which means that the first row we will see once we use this array of boolean values with our loc method is the row with the label 3 (or 4th row in our ufo dataframe)."
},
{
"code": null,
"e": 4706,
"s": 4672,
"text": "ufo.loc[ufo.City == ‘Abilene’, :]"
},
{
"code": null,
"e": 4876,
"s": 4706,
"text": "And that is exactly what we see! We have specified the rows we want using an array of boolean values with a length equal to the number of rows in our original dataframe."
},
{
"code": null,
"e": 5054,
"s": 4876,
"text": "Remember, we can combine these different ways of specifying rows and columns, meaning we can use one way of indexing on the rows and a different way on the columns. For example:"
},
{
"code": null,
"e": 5101,
"s": 5054,
"text": "ufo.loc[ufo.City == ‘Abilene’, ‘City’:’State’]"
},
{
"code": null,
"e": 5248,
"s": 5101,
"text": "Note how we used a condition that returns an array of boolean values to specify the rows and the slice object using labels to specify the columns."
},
{
"code": null,
"e": 5271,
"s": 5248,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5738,
"s": 5271,
"text": "The iloc method is also both a dataframe and series method that can be used to index a dataframe (or series). The i in iloc stands for integer, since instead of labels we are using integer-location based indexing based on the position of the rows and columns. Just like with the loc method, we can input an integer or list of integers, a slice object with integer locations, or a boolean array. Let’s just look at one key difference between the loc and iloc methods:"
},
{
"code": null,
"e": 5954,
"s": 5738,
"text": "In our ufo dataframe, we did not change the index, so the default index of our dataframe is just the integer location of our rows. However, let’s try using the slice object to specify our rows using the iloc method:"
},
{
"code": null,
"e": 5971,
"s": 5954,
"text": "ufo.iloc[3:5, :]"
},
{
"code": null,
"e": 6249,
"s": 5971,
"text": "Note how when using the slice object with the iloc method, the stop integer location is NOT included in our dataframe. So we are only seeing rows 3 and 4, but not row 5. This is in contrast with the loc method where both the start and stop labels are included in our dataframe."
},
{
"code": null,
"e": 6315,
"s": 6249,
"text": "Let’s use the iloc method to specify the columns we want as well:"
},
{
"code": null,
"e": 6334,
"s": 6315,
"text": "ufo.iloc[3:5, 1:3]"
},
{
"code": null,
"e": 6600,
"s": 6334,
"text": "If we look at the columns of our dataframe for reference, we can see that we are slicing our columns from index 1, or the Colors Reported, to index 2, which is Shape Reported. We do not include the index of our stop, which is 3 with the value of State in this case."
},
{
"code": null,
"e": 6810,
"s": 6600,
"text": "Note: We could have used a callable function for either the loc or iloc methods that returns a valid output for indexing (any of the inputs we discussed above). However, we will save that for another tutorial."
},
{
"code": null,
"e": 6863,
"s": 6810,
"text": "All the code used in this tutorial can be seen here:"
},
{
"code": null,
"e": 6886,
"s": 6863,
"text": "towardsdatascience.com"
}
]
|
Python dictionary get() Method | Python dictionary method get() returns a value for the given key. If key is not available then returns default value None.
Following is the syntax for get() method −
dict.get(key, default = None)
key − This is the Key to be searched in the dictionary.
key − This is the Key to be searched in the dictionary.
default − This is the Value to be returned in case key does not exist.
default − This is the Value to be returned in case key does not exist.
This method return a value for the given key. If key is not available, then returns default value None.
The following example shows the usage of get() method.
#!/usr/bin/python
dict = {'Name': 'Zabra', 'Age': 7}
print "Value : %s" % dict.get('Age')
print "Value : %s" % dict.get('Education', "Never")
When we run above program, it produces following result −
Value : 7
Value : Never
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2368,
"s": 2244,
"text": "Python dictionary method get() returns a value for the given key. If key is not available then returns default value None."
},
{
"code": null,
"e": 2411,
"s": 2368,
"text": "Following is the syntax for get() method −"
},
{
"code": null,
"e": 2442,
"s": 2411,
"text": "dict.get(key, default = None)\n"
},
{
"code": null,
"e": 2498,
"s": 2442,
"text": "key − This is the Key to be searched in the dictionary."
},
{
"code": null,
"e": 2554,
"s": 2498,
"text": "key − This is the Key to be searched in the dictionary."
},
{
"code": null,
"e": 2625,
"s": 2554,
"text": "default − This is the Value to be returned in case key does not exist."
},
{
"code": null,
"e": 2696,
"s": 2625,
"text": "default − This is the Value to be returned in case key does not exist."
},
{
"code": null,
"e": 2800,
"s": 2696,
"text": "This method return a value for the given key. If key is not available, then returns default value None."
},
{
"code": null,
"e": 2855,
"s": 2800,
"text": "The following example shows the usage of get() method."
},
{
"code": null,
"e": 3000,
"s": 2855,
"text": "#!/usr/bin/python\n\ndict = {'Name': 'Zabra', 'Age': 7}\nprint \"Value : %s\" % dict.get('Age')\nprint \"Value : %s\" % dict.get('Education', \"Never\")"
},
{
"code": null,
"e": 3058,
"s": 3000,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 3083,
"s": 3058,
"text": "Value : 7\nValue : Never\n"
},
{
"code": null,
"e": 3120,
"s": 3083,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3136,
"s": 3120,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3169,
"s": 3136,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3188,
"s": 3169,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3223,
"s": 3188,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3245,
"s": 3223,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3279,
"s": 3245,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3307,
"s": 3279,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3342,
"s": 3307,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3356,
"s": 3342,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3389,
"s": 3356,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3406,
"s": 3389,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3413,
"s": 3406,
"text": " Print"
},
{
"code": null,
"e": 3424,
"s": 3413,
"text": " Add Notes"
}
]
|
Introduction to Bayesian Linear Regression | by Will Koehrsen | Towards Data Science | The Bayesian vs Frequentist debate is one of those academic arguments that I find more interesting to watch than engage in. Rather than enthusiastically jump in on one side, I think it’s more productive to learn both methods of statistical inference and apply them where appropriate. In that line of thinking, recently, I have been working to learn and apply Bayesian inference methods to supplement the frequentist statistics covered in my grad classes.
One of my first areas of focus in applied Bayesian Inference was Bayesian Linear modeling. The most important part of the learning process might just be explaining an idea to others, and this post is my attempt to introduce the concept of Bayesian Linear Regression. We’ll do a brief review of the frequentist approach to linear regression, introduce the Bayesian interpretation, and look at some results applied to a simple dataset. I kept the code out of this article, but it can be found on GitHub in a Jupyter Notebook.
The frequentist view of linear regression is probably the one you are familiar with from school: the model assumes that the response variable (y) is a linear combination of weights multiplied by a set of predictor variables (x). The full formula also includes an error term to account for random sampling noise. For example, if we have two predictors, the equation is:
y is the response variable (also called the dependent variable), β’s are the weights (known as the model parameters), x’s are the values of the predictor variables, and ε is an error term representing random sampling noise or the effect of variables not included in the model.
Linear Regression is a simple model which makes it easily interpretable: β_0 is the intercept term and the other weights, β’s, show the effect on the response of increasing a predictor variable. For example, if β_1 is 1.2, then for every unit increase in x_1,the response will increase by 1.2.
We can generalize the linear model to any number of predictors using matrix equations. Adding a constant term of 1 to the predictor matrix to account for the intercept, we can write the matrix formula as:
The goal of learning a linear model from training data is to find the coefficients, β, that best explain the data. In frequentist linear regression, the best explanation is taken to mean the coefficients, β, that minimize the residual sum of squares (RSS). RSS is the total of the squared differences between the known values (y) and the predicted model outputs (ŷ, pronounced y-hat indicating an estimate). The residual sum of squares is a function of the model parameters:
The summation is taken over the N data points in the training set. We won’t go into the details here (check out this reference for the derivation), but this equation has a closed form solution for the model parameters, β, that minimize the error. This is known as the maximum likelihood estimate of β because it is the value that is the most probable given the inputs, X, and outputs, y. The closed form solution expressed in matrix form is:
(Again, we have to put the ‘hat’ on β because it represents an estimate for the model parameters.) Don’t let the matrix math scare you off! Thanks to libraries like Scikit-learn in Python, we generally don’t have to calculate this by hand (although it is good practice to code a linear regression). This method of fitting the model parameters by minimizing the RSS is called Ordinary Least Squares (OLS).
What we obtain from frequentist linear regression is a single estimate for the model parameters based only on the training data. Our model is completely informed by the data: in this view, everything that we need to know for our model is encoded in the training data we have available.
Once we have β-hat, we can estimate the output value of any new data point by applying our model equation:
As an example of OLS, we can perform a linear regression on real-world data which has duration and calories burned for 15000 exercise observations. Below is the data and OLS model obtained by solving the above matrix equation for the model parameters:
With OLS, we get a single estimate of the model parameters, in this case, the intercept and slope of the line.We can write the equation produced by OLS:
calories = -21.83 + 7.17 * duration
From the slope, we can say that every additional minute of exercise results in 7.17 additional calories burned. The intercept in this case is not as helpful, because it tells us that if we exercise for 0 minutes, we will burn -21.86 calories! This is just an artifact of the OLS fitting procedure, which finds the line that minimizes the error on the training data regardless of whether it physically makes sense.
If we have a new datapoint, say an exercise duration of 15.5 minutes, we can plug it into the equation to get a point estimate of calories burned:
calories = -21.83 + 7.17 * 15.5 = 89.2
Ordinary least squares gives us a single point estimate for the output, which we can interpret as the most likely estimate given the data. However, if we have a small dataset we might like to express our estimate as a distribution of possible values. This is where Bayesian Linear Regression comes in.
In the Bayesian viewpoint, we formulate linear regression using probability distributions rather than point estimates. The response, y, is not estimated as a single value, but is assumed to be drawn from a probability distribution. The model for Bayesian Linear Regression with the response sampled from a normal distribution is:
The output, y is generated from a normal (Gaussian) Distribution characterized by a mean and variance. The mean for linear regression is the transpose of the weight matrix multiplied by the predictor matrix. The variance is the square of the standard deviation σ (multiplied by the Identity matrix because this is a multi-dimensional formulation of the model).
The aim of Bayesian Linear Regression is not to find the single “best” value of the model parameters, but rather to determine the posterior distribution for the model parameters. Not only is the response generated from a probability distribution, but the model parameters are assumed to come from a distribution as well. The posterior probability of the model parameters is conditional upon the training inputs and outputs:
Here, P(β|y, X) is the posterior probability distribution of the model parameters given the inputs and outputs. This is equal to the likelihood of the data, P(y|β, X), multiplied by the prior probability of the parameters and divided by a normalization constant. This is a simple expression of Bayes Theorem, the fundamental underpinning of Bayesian Inference:
Let’s stop and think about what this means. In contrast to OLS, we have a posterior distribution for the model parameters that is proportional to the likelihood of the data multiplied by the prior probability of the parameters. Here we can observe the two primary benefits of Bayesian Linear Regression.
Priors: If we have domain knowledge, or a guess for what the model parameters should be, we can include them in our model, unlike in the frequentist approach which assumes everything there is to know about the parameters comes from the data. If we don’t have any estimates ahead of time, we can use non-informative priors for the parameters such as a normal distribution.Posterior: The result of performing Bayesian Linear Regression is a distribution of possible model parameters based on the data and the prior. This allows us to quantify our uncertainty about the model: if we have fewer data points, the posterior distribution will be more spread out.
Priors: If we have domain knowledge, or a guess for what the model parameters should be, we can include them in our model, unlike in the frequentist approach which assumes everything there is to know about the parameters comes from the data. If we don’t have any estimates ahead of time, we can use non-informative priors for the parameters such as a normal distribution.
Posterior: The result of performing Bayesian Linear Regression is a distribution of possible model parameters based on the data and the prior. This allows us to quantify our uncertainty about the model: if we have fewer data points, the posterior distribution will be more spread out.
As the amount of data points increases, the likelihood washes out the prior, and in the case of infinite data, the outputs for the parameters converge to the values obtained from OLS.
The formulation of model parameters as distributions encapsulates the Bayesian worldview: we start out with an initial estimate, our prior, and as we gather more evidence, our model becomes less wrong. Bayesian reasoning is a natural extension of our intuition. Often, we have an initial hypothesis, and as we collect data that either supports or disproves our ideas, we change our model of the world (ideally this is how we would reason)!
In practice, evaluating the posterior distribution for the model parameters is intractable for continuous variables, so we use sampling methods to draw samples from the posterior in order to approximate the posterior. The technique of drawing random samples from a distribution to approximate the distribution is one application of Monte Carlo methods. There are a number of algorithms for Monte Carlo sampling, with the most common being variants of Markov Chain Monte Carlo (see this post for an application in Python).
I’ll skip the code for this post (see the notebook for the implementation in PyMC3) but the basic procedure for implementing Bayesian Linear Regression is: specify priors for the model parameters (I used normal distributions in this example), creating a model mapping the training inputs to the training outputs, and then have a Markov Chain Monte Carlo (MCMC) algorithm draw samples from the posterior distribution for the model parameters. The end result will be posterior distributions for the parameters. We can inspect these distributions to get a sense of what is occurring.
The first plots show the approximations of the posterior distributions of model parameters. These are the result of 1000 steps of MCMC, meaning the algorithm drew 1000 steps from the posterior distribution.
If we compare the mean values for the slope and intercept to those obtained from OLS (the intercept from OLS was -21.83 and the slope was 7.17), we see that they are very similar. However, while we can use the mean as a single point estimate, we also have a range of possible values for the model parameters. As the number of data points increases, this range will shrink and converge one a single value representing greater confidence in the model parameters. (In Bayesian inference a range for a variable is called a credible interval and which has a slightly different interpretation from a confidence interval in frequentist inference).
When we want show the linear fit from a Bayesian model, instead of showing only estimate, we can draw a range of lines, with each one representing a different estimate of the model parameters. As the number of datapoints increases, the lines begin to overlap because there is less uncertainty in the model parameters.
In order to demonstrate the effect of the number of datapoints in the model, I used two models, the first, with the resulting fits shown on the left, used 500 datapoints and the one on the right used 15000 datapoints. Each graph shows 100 possible models drawn from the model parameter posteriors.
There is much more variation in the fits when using fewer data points, which represents a greater uncertainty in the model. With all of the data points, the OLS and Bayesian Fits are nearly identical because the priors are washed out by the likelihoods from the data.
When predicting the output for a single datapoint using our Bayesian Linear Model, we also do not get a single value but a distribution. Following is the probability density plot for the number of calories burned exercising for 15.5 minutes. The red vertical line indicates the point estimate from OLS.
We see that the probability of the number of calories burned peaks around 89.3, but the full estimate is a range of possible values.
Instead of taking sides in the Bayesian vs Frequentist debate (or any argument), it is more constructive to learn both approaches. That way, we can apply them in the right situation.
In problems where we have limited data or have some prior knowledge that we want to use in our model, the Bayesian Linear Regression approach can both incorporate prior information and show our uncertainty. Bayesian Linear Regression reflects the Bayesian framework: we form an initial estimate and improve our estimate as we gather more data. The Bayesian viewpoint is an intuitive way of looking at the world and Bayesian Inference can be a useful alternative to its frequentist counterpart. Data science is not about taking sides, but about figuring out the best tool for the job, and having more techniques in your repertoire only makes you more effective!
As always, I welcome feedback and constructive criticism. I can be reached on Twitter @koehrsen_will. | [
{
"code": null,
"e": 627,
"s": 172,
"text": "The Bayesian vs Frequentist debate is one of those academic arguments that I find more interesting to watch than engage in. Rather than enthusiastically jump in on one side, I think it’s more productive to learn both methods of statistical inference and apply them where appropriate. In that line of thinking, recently, I have been working to learn and apply Bayesian inference methods to supplement the frequentist statistics covered in my grad classes."
},
{
"code": null,
"e": 1151,
"s": 627,
"text": "One of my first areas of focus in applied Bayesian Inference was Bayesian Linear modeling. The most important part of the learning process might just be explaining an idea to others, and this post is my attempt to introduce the concept of Bayesian Linear Regression. We’ll do a brief review of the frequentist approach to linear regression, introduce the Bayesian interpretation, and look at some results applied to a simple dataset. I kept the code out of this article, but it can be found on GitHub in a Jupyter Notebook."
},
{
"code": null,
"e": 1520,
"s": 1151,
"text": "The frequentist view of linear regression is probably the one you are familiar with from school: the model assumes that the response variable (y) is a linear combination of weights multiplied by a set of predictor variables (x). The full formula also includes an error term to account for random sampling noise. For example, if we have two predictors, the equation is:"
},
{
"code": null,
"e": 1797,
"s": 1520,
"text": "y is the response variable (also called the dependent variable), β’s are the weights (known as the model parameters), x’s are the values of the predictor variables, and ε is an error term representing random sampling noise or the effect of variables not included in the model."
},
{
"code": null,
"e": 2091,
"s": 1797,
"text": "Linear Regression is a simple model which makes it easily interpretable: β_0 is the intercept term and the other weights, β’s, show the effect on the response of increasing a predictor variable. For example, if β_1 is 1.2, then for every unit increase in x_1,the response will increase by 1.2."
},
{
"code": null,
"e": 2296,
"s": 2091,
"text": "We can generalize the linear model to any number of predictors using matrix equations. Adding a constant term of 1 to the predictor matrix to account for the intercept, we can write the matrix formula as:"
},
{
"code": null,
"e": 2772,
"s": 2296,
"text": "The goal of learning a linear model from training data is to find the coefficients, β, that best explain the data. In frequentist linear regression, the best explanation is taken to mean the coefficients, β, that minimize the residual sum of squares (RSS). RSS is the total of the squared differences between the known values (y) and the predicted model outputs (ŷ, pronounced y-hat indicating an estimate). The residual sum of squares is a function of the model parameters:"
},
{
"code": null,
"e": 3214,
"s": 2772,
"text": "The summation is taken over the N data points in the training set. We won’t go into the details here (check out this reference for the derivation), but this equation has a closed form solution for the model parameters, β, that minimize the error. This is known as the maximum likelihood estimate of β because it is the value that is the most probable given the inputs, X, and outputs, y. The closed form solution expressed in matrix form is:"
},
{
"code": null,
"e": 3619,
"s": 3214,
"text": "(Again, we have to put the ‘hat’ on β because it represents an estimate for the model parameters.) Don’t let the matrix math scare you off! Thanks to libraries like Scikit-learn in Python, we generally don’t have to calculate this by hand (although it is good practice to code a linear regression). This method of fitting the model parameters by minimizing the RSS is called Ordinary Least Squares (OLS)."
},
{
"code": null,
"e": 3905,
"s": 3619,
"text": "What we obtain from frequentist linear regression is a single estimate for the model parameters based only on the training data. Our model is completely informed by the data: in this view, everything that we need to know for our model is encoded in the training data we have available."
},
{
"code": null,
"e": 4012,
"s": 3905,
"text": "Once we have β-hat, we can estimate the output value of any new data point by applying our model equation:"
},
{
"code": null,
"e": 4264,
"s": 4012,
"text": "As an example of OLS, we can perform a linear regression on real-world data which has duration and calories burned for 15000 exercise observations. Below is the data and OLS model obtained by solving the above matrix equation for the model parameters:"
},
{
"code": null,
"e": 4417,
"s": 4264,
"text": "With OLS, we get a single estimate of the model parameters, in this case, the intercept and slope of the line.We can write the equation produced by OLS:"
},
{
"code": null,
"e": 4453,
"s": 4417,
"text": "calories = -21.83 + 7.17 * duration"
},
{
"code": null,
"e": 4867,
"s": 4453,
"text": "From the slope, we can say that every additional minute of exercise results in 7.17 additional calories burned. The intercept in this case is not as helpful, because it tells us that if we exercise for 0 minutes, we will burn -21.86 calories! This is just an artifact of the OLS fitting procedure, which finds the line that minimizes the error on the training data regardless of whether it physically makes sense."
},
{
"code": null,
"e": 5014,
"s": 4867,
"text": "If we have a new datapoint, say an exercise duration of 15.5 minutes, we can plug it into the equation to get a point estimate of calories burned:"
},
{
"code": null,
"e": 5053,
"s": 5014,
"text": "calories = -21.83 + 7.17 * 15.5 = 89.2"
},
{
"code": null,
"e": 5355,
"s": 5053,
"text": "Ordinary least squares gives us a single point estimate for the output, which we can interpret as the most likely estimate given the data. However, if we have a small dataset we might like to express our estimate as a distribution of possible values. This is where Bayesian Linear Regression comes in."
},
{
"code": null,
"e": 5685,
"s": 5355,
"text": "In the Bayesian viewpoint, we formulate linear regression using probability distributions rather than point estimates. The response, y, is not estimated as a single value, but is assumed to be drawn from a probability distribution. The model for Bayesian Linear Regression with the response sampled from a normal distribution is:"
},
{
"code": null,
"e": 6046,
"s": 5685,
"text": "The output, y is generated from a normal (Gaussian) Distribution characterized by a mean and variance. The mean for linear regression is the transpose of the weight matrix multiplied by the predictor matrix. The variance is the square of the standard deviation σ (multiplied by the Identity matrix because this is a multi-dimensional formulation of the model)."
},
{
"code": null,
"e": 6470,
"s": 6046,
"text": "The aim of Bayesian Linear Regression is not to find the single “best” value of the model parameters, but rather to determine the posterior distribution for the model parameters. Not only is the response generated from a probability distribution, but the model parameters are assumed to come from a distribution as well. The posterior probability of the model parameters is conditional upon the training inputs and outputs:"
},
{
"code": null,
"e": 6831,
"s": 6470,
"text": "Here, P(β|y, X) is the posterior probability distribution of the model parameters given the inputs and outputs. This is equal to the likelihood of the data, P(y|β, X), multiplied by the prior probability of the parameters and divided by a normalization constant. This is a simple expression of Bayes Theorem, the fundamental underpinning of Bayesian Inference:"
},
{
"code": null,
"e": 7135,
"s": 6831,
"text": "Let’s stop and think about what this means. In contrast to OLS, we have a posterior distribution for the model parameters that is proportional to the likelihood of the data multiplied by the prior probability of the parameters. Here we can observe the two primary benefits of Bayesian Linear Regression."
},
{
"code": null,
"e": 7791,
"s": 7135,
"text": "Priors: If we have domain knowledge, or a guess for what the model parameters should be, we can include them in our model, unlike in the frequentist approach which assumes everything there is to know about the parameters comes from the data. If we don’t have any estimates ahead of time, we can use non-informative priors for the parameters such as a normal distribution.Posterior: The result of performing Bayesian Linear Regression is a distribution of possible model parameters based on the data and the prior. This allows us to quantify our uncertainty about the model: if we have fewer data points, the posterior distribution will be more spread out."
},
{
"code": null,
"e": 8163,
"s": 7791,
"text": "Priors: If we have domain knowledge, or a guess for what the model parameters should be, we can include them in our model, unlike in the frequentist approach which assumes everything there is to know about the parameters comes from the data. If we don’t have any estimates ahead of time, we can use non-informative priors for the parameters such as a normal distribution."
},
{
"code": null,
"e": 8448,
"s": 8163,
"text": "Posterior: The result of performing Bayesian Linear Regression is a distribution of possible model parameters based on the data and the prior. This allows us to quantify our uncertainty about the model: if we have fewer data points, the posterior distribution will be more spread out."
},
{
"code": null,
"e": 8632,
"s": 8448,
"text": "As the amount of data points increases, the likelihood washes out the prior, and in the case of infinite data, the outputs for the parameters converge to the values obtained from OLS."
},
{
"code": null,
"e": 9072,
"s": 8632,
"text": "The formulation of model parameters as distributions encapsulates the Bayesian worldview: we start out with an initial estimate, our prior, and as we gather more evidence, our model becomes less wrong. Bayesian reasoning is a natural extension of our intuition. Often, we have an initial hypothesis, and as we collect data that either supports or disproves our ideas, we change our model of the world (ideally this is how we would reason)!"
},
{
"code": null,
"e": 9594,
"s": 9072,
"text": "In practice, evaluating the posterior distribution for the model parameters is intractable for continuous variables, so we use sampling methods to draw samples from the posterior in order to approximate the posterior. The technique of drawing random samples from a distribution to approximate the distribution is one application of Monte Carlo methods. There are a number of algorithms for Monte Carlo sampling, with the most common being variants of Markov Chain Monte Carlo (see this post for an application in Python)."
},
{
"code": null,
"e": 10175,
"s": 9594,
"text": "I’ll skip the code for this post (see the notebook for the implementation in PyMC3) but the basic procedure for implementing Bayesian Linear Regression is: specify priors for the model parameters (I used normal distributions in this example), creating a model mapping the training inputs to the training outputs, and then have a Markov Chain Monte Carlo (MCMC) algorithm draw samples from the posterior distribution for the model parameters. The end result will be posterior distributions for the parameters. We can inspect these distributions to get a sense of what is occurring."
},
{
"code": null,
"e": 10382,
"s": 10175,
"text": "The first plots show the approximations of the posterior distributions of model parameters. These are the result of 1000 steps of MCMC, meaning the algorithm drew 1000 steps from the posterior distribution."
},
{
"code": null,
"e": 11023,
"s": 10382,
"text": "If we compare the mean values for the slope and intercept to those obtained from OLS (the intercept from OLS was -21.83 and the slope was 7.17), we see that they are very similar. However, while we can use the mean as a single point estimate, we also have a range of possible values for the model parameters. As the number of data points increases, this range will shrink and converge one a single value representing greater confidence in the model parameters. (In Bayesian inference a range for a variable is called a credible interval and which has a slightly different interpretation from a confidence interval in frequentist inference)."
},
{
"code": null,
"e": 11341,
"s": 11023,
"text": "When we want show the linear fit from a Bayesian model, instead of showing only estimate, we can draw a range of lines, with each one representing a different estimate of the model parameters. As the number of datapoints increases, the lines begin to overlap because there is less uncertainty in the model parameters."
},
{
"code": null,
"e": 11639,
"s": 11341,
"text": "In order to demonstrate the effect of the number of datapoints in the model, I used two models, the first, with the resulting fits shown on the left, used 500 datapoints and the one on the right used 15000 datapoints. Each graph shows 100 possible models drawn from the model parameter posteriors."
},
{
"code": null,
"e": 11907,
"s": 11639,
"text": "There is much more variation in the fits when using fewer data points, which represents a greater uncertainty in the model. With all of the data points, the OLS and Bayesian Fits are nearly identical because the priors are washed out by the likelihoods from the data."
},
{
"code": null,
"e": 12210,
"s": 11907,
"text": "When predicting the output for a single datapoint using our Bayesian Linear Model, we also do not get a single value but a distribution. Following is the probability density plot for the number of calories burned exercising for 15.5 minutes. The red vertical line indicates the point estimate from OLS."
},
{
"code": null,
"e": 12343,
"s": 12210,
"text": "We see that the probability of the number of calories burned peaks around 89.3, but the full estimate is a range of possible values."
},
{
"code": null,
"e": 12526,
"s": 12343,
"text": "Instead of taking sides in the Bayesian vs Frequentist debate (or any argument), it is more constructive to learn both approaches. That way, we can apply them in the right situation."
},
{
"code": null,
"e": 13187,
"s": 12526,
"text": "In problems where we have limited data or have some prior knowledge that we want to use in our model, the Bayesian Linear Regression approach can both incorporate prior information and show our uncertainty. Bayesian Linear Regression reflects the Bayesian framework: we form an initial estimate and improve our estimate as we gather more data. The Bayesian viewpoint is an intuitive way of looking at the world and Bayesian Inference can be a useful alternative to its frequentist counterpart. Data science is not about taking sides, but about figuring out the best tool for the job, and having more techniques in your repertoire only makes you more effective!"
}
]
|
How to create a table row using HTML5 ? - GeeksforGeeks | 02 Jun, 2020
In this article, we define a row in a table by using a <tr> tag in a document. This tag is used to define a row in an HTML table. The tr element contains multiple th or td elements.
Syntax:
<tr> ... </tr>
Example:
<!DOCTYPE html><html> <head> <title> How to define row of a table </title> <style> body { text-align: center; } h1 { color: green; } th { color: blue; } table, tbody, td { border: 1px solid black; border-collapse: collapse; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h2> HTML5: How to define a row in a table? </h2> <table> <thead> <!-- tr tag starts here --> <tr> <th>Name</th> <th>User Id</th> </tr> <!-- tr tag end here --> </thead> <tbody> <tr> <td>Shashank</td> <td>@shashankla</td> </tr> <tr> <td>GeeksforGeeks</td> <td>@geeks</td> </tr> </tbody> </table> </center></body> </html>
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Misc
HTML5
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Design a web page using HTML and CSS
How to position a div at the bottom of its container using CSS?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 24403,
"s": 24375,
"text": "\n02 Jun, 2020"
},
{
"code": null,
"e": 24585,
"s": 24403,
"text": "In this article, we define a row in a table by using a <tr> tag in a document. This tag is used to define a row in an HTML table. The tr element contains multiple th or td elements."
},
{
"code": null,
"e": 24593,
"s": 24585,
"text": "Syntax:"
},
{
"code": null,
"e": 24608,
"s": 24593,
"text": "<tr> ... </tr>"
},
{
"code": null,
"e": 24617,
"s": 24608,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to define row of a table </title> <style> body { text-align: center; } h1 { color: green; } th { color: blue; } table, tbody, td { border: 1px solid black; border-collapse: collapse; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h2> HTML5: How to define a row in a table? </h2> <table> <thead> <!-- tr tag starts here --> <tr> <th>Name</th> <th>User Id</th> </tr> <!-- tr tag end here --> </thead> <tbody> <tr> <td>Shashank</td> <td>@shashankla</td> </tr> <tr> <td>GeeksforGeeks</td> <td>@geeks</td> </tr> </tbody> </table> </center></body> </html>",
"e": 25718,
"s": 24617,
"text": null
},
{
"code": null,
"e": 25726,
"s": 25718,
"text": "Output:"
},
{
"code": null,
"e": 25746,
"s": 25726,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 25760,
"s": 25746,
"text": "Google Chrome"
},
{
"code": null,
"e": 25778,
"s": 25760,
"text": "Internet Explorer"
},
{
"code": null,
"e": 25786,
"s": 25778,
"text": "Firefox"
},
{
"code": null,
"e": 25792,
"s": 25786,
"text": "Opera"
},
{
"code": null,
"e": 25799,
"s": 25792,
"text": "Safari"
},
{
"code": null,
"e": 25936,
"s": 25799,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 25946,
"s": 25936,
"text": "HTML-Misc"
},
{
"code": null,
"e": 25952,
"s": 25946,
"text": "HTML5"
},
{
"code": null,
"e": 25957,
"s": 25952,
"text": "HTML"
},
{
"code": null,
"e": 25974,
"s": 25957,
"text": "Web Technologies"
},
{
"code": null,
"e": 26001,
"s": 25974,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 26006,
"s": 26001,
"text": "HTML"
},
{
"code": null,
"e": 26104,
"s": 26006,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26113,
"s": 26104,
"text": "Comments"
},
{
"code": null,
"e": 26126,
"s": 26113,
"text": "Old Comments"
},
{
"code": null,
"e": 26163,
"s": 26126,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 26213,
"s": 26163,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26237,
"s": 26213,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26274,
"s": 26237,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 26338,
"s": 26274,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 26394,
"s": 26338,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26427,
"s": 26394,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26470,
"s": 26427,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26531,
"s": 26470,
"text": "Difference between var, let and const keywords in JavaScript"
}
]
|
Program to find last two digits of 2^n in C++ | In this problem, we are given a number N. Our task is to create a Program to
find last two digits of 2^n in C++.
To find the last two digits. We will use only the
product of the last two digits. And leave other things to make the calculation
small.
Let’s take an example to understand the problem,
Input: N = 12
Output: 96
2^12 = 4096
To solve the problem, a direct approach could be finding the value of 2^N
and then finding the remainder when it is divided by 100.
Live Demo
#include <iostream>
using namespace std;
int findLastDigit(int N){
int powerVal = 1;
for(int i = 0; i < N; i++){
powerVal *= 2;
}
return powerVal%100;
}
int main() {
int N = 14;
cout<<"The last two digits of 2^"<<N<<" is "<<findLastDigit(N);
return 0;
}
The last two digits of 2^14 is 84
This approach is not effective, as for large values of N the program will
overflow.
A better approach is by only considering 2 digits from the values. And multiply it by two for every power.
For each in the case of 2^14, the last two digits are 84. We will multiply 84
by two instead of the whole number which will save calculations. So,
(84*2)%100 = 68.
Live Demo
#include <iostream>
using namespace std;
int findLastDigit(int N){
int powerVal = 1;
for(int i = 0; i < N; i++){
powerVal = (powerVal * 2)%100;
}
return powerVal;
}
int main() {
int N = 15;
cout<<"The last two digits of 2^"<<N<<" is "<<findLastDigit(N);
return 0;
}
The last two digits of 2^15 is 68 | [
{
"code": null,
"e": 1175,
"s": 1062,
"text": "In this problem, we are given a number N. Our task is to create a Program to\nfind last two digits of 2^n in C++."
},
{
"code": null,
"e": 1311,
"s": 1175,
"text": "To find the last two digits. We will use only the\nproduct of the last two digits. And leave other things to make the calculation\nsmall."
},
{
"code": null,
"e": 1360,
"s": 1311,
"text": "Let’s take an example to understand the problem,"
},
{
"code": null,
"e": 1375,
"s": 1360,
"text": "Input: N = 12 "
},
{
"code": null,
"e": 1386,
"s": 1375,
"text": "Output: 96"
},
{
"code": null,
"e": 1398,
"s": 1386,
"text": "2^12 = 4096"
},
{
"code": null,
"e": 1530,
"s": 1398,
"text": "To solve the problem, a direct approach could be finding the value of 2^N\nand then finding the remainder when it is divided by 100."
},
{
"code": null,
"e": 1541,
"s": 1530,
"text": " Live Demo"
},
{
"code": null,
"e": 1831,
"s": 1541,
"text": "#include <iostream>\nusing namespace std;\nint findLastDigit(int N){\n int powerVal = 1;\n for(int i = 0; i < N; i++){\n powerVal *= 2;\n }\n return powerVal%100;\n}\nint main() {\n int N = 14;\n cout<<\"The last two digits of 2^\"<<N<<\" is \"<<findLastDigit(N);\n return 0;\n}"
},
{
"code": null,
"e": 1865,
"s": 1831,
"text": "The last two digits of 2^14 is 84"
},
{
"code": null,
"e": 1949,
"s": 1865,
"text": "This approach is not effective, as for large values of N the program will\noverflow."
},
{
"code": null,
"e": 2056,
"s": 1949,
"text": "A better approach is by only considering 2 digits from the values. And multiply it by two for every power."
},
{
"code": null,
"e": 2220,
"s": 2056,
"text": "For each in the case of 2^14, the last two digits are 84. We will multiply 84\nby two instead of the whole number which will save calculations. So,\n(84*2)%100 = 68."
},
{
"code": null,
"e": 2231,
"s": 2220,
"text": " Live Demo"
},
{
"code": null,
"e": 2524,
"s": 2231,
"text": "#include <iostream>\nusing namespace std;\nint findLastDigit(int N){\n int powerVal = 1;\n for(int i = 0; i < N; i++){\n powerVal = (powerVal * 2)%100;\n }\n return powerVal;\n}\nint main() {\n int N = 15;\n cout<<\"The last two digits of 2^\"<<N<<\" is \"<<findLastDigit(N);\n return 0;\n}"
},
{
"code": null,
"e": 2558,
"s": 2524,
"text": "The last two digits of 2^15 is 68"
}
]
|
How to call OnDestroy Activity in Android app? | This example demonstrates about How do I call OnDestroy Activity in Android app.
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"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="16dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="32dp"
android:text="Destroy"
android:textColor="@color/colorPrimary"
android:textSize="32dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Step 3 − Add the following code to src/MainActivity.java
package com.sample.q2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
public static final String MY_TAG = "Destroy";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(MY_TAG, "onCreate");
}
protected void onDestroy() {
super.onDestroy();
Log.i(MY_TAG, "onDestroy");
}
}
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": 1143,
"s": 1062,
"text": "This example demonstrates about How do I call OnDestroy Activity in Android app."
},
{
"code": null,
"e": 1272,
"s": 1143,
"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": 1337,
"s": 1272,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2345,
"s": 1337,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<android.support.constraint.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginLeft=\"8dp\"\n android:layout_marginTop=\"16dp\"\n android:layout_marginRight=\"8dp\"\n android:layout_marginBottom=\"32dp\"\n android:text=\"Destroy\"\n android:textColor=\"@color/colorPrimary\"\n android:textSize=\"32dp\"\n android:textStyle=\"bold\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 2402,
"s": 2345,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2922,
"s": 2402,
"text": "package com.sample.q2;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.util.Log;\npublic class MainActivity extends AppCompatActivity {\n public static final String MY_TAG = \"Destroy\";\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Log.i(MY_TAG, \"onCreate\");\n }\n protected void onDestroy() {\n super.onDestroy();\n Log.i(MY_TAG, \"onDestroy\");\n }\n}"
},
{
"code": null,
"e": 2977,
"s": 2922,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3647,
"s": 2977,
"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": 3994,
"s": 3647,
"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": 4037,
"s": 3994,
"text": "Click here to download the project code."
}
]
|
Python Program to Find the Sum of all Nodes in a Tree | When it is required to get the sum of all the nodes in a Tree, a ‘Tree_structure’ class is created, methods to set a root value, and to add other values are defined. It also has a method to determine the sum of all elements of a Tree structure. Various options are given that the user can select. Based on the user’s choice, the operation is performed on the Tree elements.
Below is a demonstration of the same −
Live Demo
class Tree_structure:
def __init__(self, data=None):
self.key = data
self.children = []
def set_root(self, data):
self.key = data
def add_values(self, node):
self.children.append(node)
def search_val(self, key):
if self.key == key:
return self
for child in self.children:
temp = child.search(key)
if temp is not None:
return temp
return None
def summation_nodes(self):
sum_val = self.key
for child in self.children:
sum_val = sum_val + child.summation_nodes()
return sum_val
tree = None
print('Menu (no duplicate keys allowed)')
print('add <data> at root')
print('add <data> below <data>')
print('summation')
print('quit')
while True:
my_input = input('What would you like to do? ').split()
operation = my_input[0].strip().lower()
if operation == 'add':
data = int(my_input[1])
newNode = Tree_structure(data)
sub_op = my_input[2].strip().lower()
if sub_op == 'at':
tree = newNode
elif sub_op == 'below':
my_pos = my_input[3].strip().lower()
key = int(my_pos)
ref_node = None
if tree is not None:
ref_node = tree.search_val(key)
if ref_node is None:
print('No such key exists')
continue
ref_node.add_values(newNode)
elif operation == 'summation':
if tree is None:
print('The tree is empty')
else:
summation_val = tree.summation_nodes()
print('Sum of all the nodes is : {}'.format(summation_val))
elif operation == 'quit':
break
Menu (no duplicate keys allowed)
add <data> at root
add <data> below <data>
summation
quit
What would you like to do? add 56 at root
What would you like to do? add 45 below 56
What would you like to do? add 23 below 56
What would you like to do? summation
Sum of all the nodes is : 124
What would you like to do?
The ‘Tree_structure’ class is created.
The ‘Tree_structure’ class is created.
It sets the ‘key’ to True and sets an empty list to children of tree.
It sets the ‘key’ to True and sets an empty list to children of tree.
It has a ‘set_root’ function that helps set the root value for the Tree.
It has a ‘set_root’ function that helps set the root value for the Tree.
A method named ‘add_vals’ is defined, that helps add an element to the Tree.
A method named ‘add_vals’ is defined, that helps add an element to the Tree.
Another method named ‘search_val’ is defined, that helps search for an element in the Tree.
Another method named ‘search_val’ is defined, that helps search for an element in the Tree.
Another method named ‘summation_nodes’ is defined, that helps get the sum of all elements/nodes of the Tree.
Another method named ‘summation_nodes’ is defined, that helps get the sum of all elements/nodes of the Tree.
It is a recursive function.
It is a recursive function.
Four options are given, such as ‘add at root’, ‘add below’, ‘Summation’ and ‘quit’.
Four options are given, such as ‘add at root’, ‘add below’, ‘Summation’ and ‘quit’.
Depending on the option given by user, the respective operation is performed.
Depending on the option given by user, the respective operation is performed.
This output is displayed on the console.
This output is displayed on the console. | [
{
"code": null,
"e": 1436,
"s": 1062,
"text": "When it is required to get the sum of all the nodes in a Tree, a ‘Tree_structure’ class is created, methods to set a root value, and to add other values are defined. It also has a method to determine the sum of all elements of a Tree structure. Various options are given that the user can select. Based on the user’s choice, the operation is performed on the Tree elements."
},
{
"code": null,
"e": 1475,
"s": 1436,
"text": "Below is a demonstration of the same −"
},
{
"code": null,
"e": 1486,
"s": 1475,
"text": " Live Demo"
},
{
"code": null,
"e": 3135,
"s": 1486,
"text": "class Tree_structure:\n def __init__(self, data=None):\n self.key = data\n self.children = []\n\n def set_root(self, data):\n self.key = data\n\n def add_values(self, node):\n self.children.append(node)\n\n def search_val(self, key):\n if self.key == key:\n return self\n for child in self.children:\n temp = child.search(key)\n if temp is not None:\n return temp\n return None\n\n def summation_nodes(self):\n sum_val = self.key\n for child in self.children:\n sum_val = sum_val + child.summation_nodes()\n return sum_val\n\ntree = None\n\nprint('Menu (no duplicate keys allowed)')\nprint('add <data> at root')\nprint('add <data> below <data>')\nprint('summation')\nprint('quit')\n\nwhile True:\n my_input = input('What would you like to do? ').split()\n\n operation = my_input[0].strip().lower()\n if operation == 'add':\n data = int(my_input[1])\n newNode = Tree_structure(data)\n sub_op = my_input[2].strip().lower()\n if sub_op == 'at':\n tree = newNode\n elif sub_op == 'below':\n my_pos = my_input[3].strip().lower()\n key = int(my_pos)\n ref_node = None\n if tree is not None:\n ref_node = tree.search_val(key)\n if ref_node is None:\n print('No such key exists')\n continue\n ref_node.add_values(newNode)\n\n elif operation == 'summation':\n if tree is None:\n print('The tree is empty')\n else:\n summation_val = tree.summation_nodes()\n print('Sum of all the nodes is : {}'.format(summation_val))\n\n elif operation == 'quit':\n break"
},
{
"code": null,
"e": 3448,
"s": 3135,
"text": "Menu (no duplicate keys allowed)\nadd <data> at root\nadd <data> below <data>\nsummation\nquit\nWhat would you like to do? add 56 at root\nWhat would you like to do? add 45 below 56\nWhat would you like to do? add 23 below 56\nWhat would you like to do? summation\nSum of all the nodes is : 124\nWhat would you like to do?"
},
{
"code": null,
"e": 3487,
"s": 3448,
"text": "The ‘Tree_structure’ class is created."
},
{
"code": null,
"e": 3526,
"s": 3487,
"text": "The ‘Tree_structure’ class is created."
},
{
"code": null,
"e": 3596,
"s": 3526,
"text": "It sets the ‘key’ to True and sets an empty list to children of tree."
},
{
"code": null,
"e": 3666,
"s": 3596,
"text": "It sets the ‘key’ to True and sets an empty list to children of tree."
},
{
"code": null,
"e": 3739,
"s": 3666,
"text": "It has a ‘set_root’ function that helps set the root value for the Tree."
},
{
"code": null,
"e": 3812,
"s": 3739,
"text": "It has a ‘set_root’ function that helps set the root value for the Tree."
},
{
"code": null,
"e": 3889,
"s": 3812,
"text": "A method named ‘add_vals’ is defined, that helps add an element to the Tree."
},
{
"code": null,
"e": 3966,
"s": 3889,
"text": "A method named ‘add_vals’ is defined, that helps add an element to the Tree."
},
{
"code": null,
"e": 4058,
"s": 3966,
"text": "Another method named ‘search_val’ is defined, that helps search for an element in the Tree."
},
{
"code": null,
"e": 4150,
"s": 4058,
"text": "Another method named ‘search_val’ is defined, that helps search for an element in the Tree."
},
{
"code": null,
"e": 4259,
"s": 4150,
"text": "Another method named ‘summation_nodes’ is defined, that helps get the sum of all elements/nodes of the Tree."
},
{
"code": null,
"e": 4368,
"s": 4259,
"text": "Another method named ‘summation_nodes’ is defined, that helps get the sum of all elements/nodes of the Tree."
},
{
"code": null,
"e": 4396,
"s": 4368,
"text": "It is a recursive function."
},
{
"code": null,
"e": 4424,
"s": 4396,
"text": "It is a recursive function."
},
{
"code": null,
"e": 4508,
"s": 4424,
"text": "Four options are given, such as ‘add at root’, ‘add below’, ‘Summation’ and ‘quit’."
},
{
"code": null,
"e": 4592,
"s": 4508,
"text": "Four options are given, such as ‘add at root’, ‘add below’, ‘Summation’ and ‘quit’."
},
{
"code": null,
"e": 4670,
"s": 4592,
"text": "Depending on the option given by user, the respective operation is performed."
},
{
"code": null,
"e": 4748,
"s": 4670,
"text": "Depending on the option given by user, the respective operation is performed."
},
{
"code": null,
"e": 4789,
"s": 4748,
"text": "This output is displayed on the console."
},
{
"code": null,
"e": 4830,
"s": 4789,
"text": "This output is displayed on the console."
}
]
|
Java 8 - Base64 | With Java 8, Base64 has finally got its due. Java 8 now has inbuilt encoder and decoder for Base64 encoding. In Java 8, we can use three types of Base64 encoding.
Simple − Output is mapped to a set of characters lying in A-Za-z0-9+/. The encoder does not add any line feed in output, and the decoder rejects any character other than A-Za-z0-9+/.
Simple − Output is mapped to a set of characters lying in A-Za-z0-9+/. The encoder does not add any line feed in output, and the decoder rejects any character other than A-Za-z0-9+/.
URL − Output is mapped to set of characters lying in A-Za-z0-9+_. Output is URL and filename safe.
URL − Output is mapped to set of characters lying in A-Za-z0-9+_. Output is URL and filename safe.
MIME − Output is mapped to MIME friendly format. Output is represented in lines of no more than 76 characters each, and uses a carriage return '\r' followed by a linefeed '\n' as the line separator. No line separator is present to the end of the encoded output.
MIME − Output is mapped to MIME friendly format. Output is represented in lines of no more than 76 characters each, and uses a carriage return '\r' followed by a linefeed '\n' as the line separator. No line separator is present to the end of the encoded output.
static class Base64.Decoder
This class implements a decoder for decoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.
static class Base64.Encoder
This class implements an encoder for encoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.
static Base64.Decoder getDecoder()
Returns a Base64.Decoder that decodes using the Basic type base64 encoding scheme.
static Base64.Encoder getEncoder()
Returns a Base64.Encoder that encodes using the Basic type base64 encoding scheme.
static Base64.Decoder getMimeDecoder()
Returns a Base64.Decoder that decodes using the MIME type base64 decoding scheme.
static Base64.Encoder getMimeEncoder()
Returns a Base64.Encoder that encodes using the MIME type base64 encoding scheme.
static Base64.Encoder getMimeEncoder(int lineLength, byte[] lineSeparator)
Returns a Base64.Encoder that encodes using the MIME type base64 encoding scheme with specified line length and line separators.
static Base64.Decoder getUrlDecoder()
Returns a Base64.Decoder that decodes using the URL and Filename safe type base64 encoding scheme.
static Base64.Encoder getUrlEncoder()
Returns a Base64.Encoder that encodes using the URL and Filename safe type base64 encoding scheme.
This class inherits methods from the following class −
java.lang.Object
Create the following Java program using any editor of your choice in say C:/> JAVA.
import java.util.Base64;
import java.util.UUID;
import java.io.UnsupportedEncodingException;
public class HelloWorld {
public static void main(String args[]) {
try {
// Encode using basic encoder
String base64encodedString = Base64.getEncoder().encodeToString(
"TutorialsPoint?java8".getBytes("utf-8"));
System.out.println("Base64 Encoded String (Basic) :" + base64encodedString);
// Decode
byte[] base64decodedBytes = Base64.getDecoder().decode(base64encodedString);
System.out.println("Original String: " + new String(base64decodedBytes, "utf-8"));
base64encodedString = Base64.getUrlEncoder().encodeToString(
"TutorialsPoint?java8".getBytes("utf-8"));
System.out.println("Base64 Encoded String (URL) :" + base64encodedString);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 10; ++i) {
stringBuilder.append(UUID.randomUUID().toString());
}
byte[] mimeBytes = stringBuilder.toString().getBytes("utf-8");
String mimeEncodedString = Base64.getMimeEncoder().encodeToString(mimeBytes);
System.out.println("Base64 Encoded String (MIME) :" + mimeEncodedString);
} catch(UnsupportedEncodingException e) {
System.out.println("Error :" + e.getMessage());
}
}
}
Compile the class using javac compiler as follows −
C:\JAVA>javac Java8Tester.java
Now run the Java8Tester as follows −
C:\JAVA>java Java8Tester
It should produce the following output −
Base64 Encoded String (Basic) :VHV0b3JpYWxzUG9pbnQ/amF2YTg=
Original String: TutorialsPoint?java8
Base64 Encoded String (URL) :VHV0b3JpYWxzUG9pbnQ_amF2YTg=
Base64 Encoded String (MIME) :YmU3NWY2ODktNGM5YS00ODlmLWI2MTUtZTVkOTk2YzQ1Njk1Y2EwZTg2OTEtMmRiZC00YTQ1LWJl
NTctMTI1MWUwMTk0ZWQyNDE0NDAwYjgtYTYxOS00NDY5LTllYTctNjc1YzE3YWJhZTk1MTQ2MDQz
NDItOTAyOC00ZWI0LThlOTYtZWU5YzcwNWQyYzVhMTQxMWRjYTMtY2MwNi00MzU0LTg0MTgtNGQ1
MDkwYjdiMzg2ZTY0OWU5MmUtZmNkYS00YWEwLTg0MjQtYThiOTQxNDQ2YzhhNTVhYWExZjItNjU2
Mi00YmM4LTk2ZGYtMDE4YmY5ZDZhMjkwMzM3MWUzNDMtMmQ3MS00MDczLWI0Y2UtMTQxODE0MGU5
YjdmYTVlODUxYzItN2NmOS00N2UyLWIyODQtMThlMWVkYTY4M2Q1YjE3YTMyYmItZjllMS00MTFk
LWJiM2UtM2JhYzUxYzI5OWI4
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2037,
"s": 1874,
"text": "With Java 8, Base64 has finally got its due. Java 8 now has inbuilt encoder and decoder for Base64 encoding. In Java 8, we can use three types of Base64 encoding."
},
{
"code": null,
"e": 2220,
"s": 2037,
"text": "Simple − Output is mapped to a set of characters lying in A-Za-z0-9+/. The encoder does not add any line feed in output, and the decoder rejects any character other than A-Za-z0-9+/."
},
{
"code": null,
"e": 2403,
"s": 2220,
"text": "Simple − Output is mapped to a set of characters lying in A-Za-z0-9+/. The encoder does not add any line feed in output, and the decoder rejects any character other than A-Za-z0-9+/."
},
{
"code": null,
"e": 2502,
"s": 2403,
"text": "URL − Output is mapped to set of characters lying in A-Za-z0-9+_. Output is URL and filename safe."
},
{
"code": null,
"e": 2601,
"s": 2502,
"text": "URL − Output is mapped to set of characters lying in A-Za-z0-9+_. Output is URL and filename safe."
},
{
"code": null,
"e": 2863,
"s": 2601,
"text": "MIME − Output is mapped to MIME friendly format. Output is represented in lines of no more than 76 characters each, and uses a carriage return '\\r' followed by a linefeed '\\n' as the line separator. No line separator is present to the end of the encoded output."
},
{
"code": null,
"e": 3125,
"s": 2863,
"text": "MIME − Output is mapped to MIME friendly format. Output is represented in lines of no more than 76 characters each, and uses a carriage return '\\r' followed by a linefeed '\\n' as the line separator. No line separator is present to the end of the encoded output."
},
{
"code": null,
"e": 3153,
"s": 3125,
"text": "static class Base64.Decoder"
},
{
"code": null,
"e": 3280,
"s": 3153,
"text": "This class implements a decoder for decoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045."
},
{
"code": null,
"e": 3308,
"s": 3280,
"text": "static class Base64.Encoder"
},
{
"code": null,
"e": 3436,
"s": 3308,
"text": "This class implements an encoder for encoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045."
},
{
"code": null,
"e": 3471,
"s": 3436,
"text": "static Base64.Decoder getDecoder()"
},
{
"code": null,
"e": 3554,
"s": 3471,
"text": "Returns a Base64.Decoder that decodes using the Basic type base64 encoding scheme."
},
{
"code": null,
"e": 3589,
"s": 3554,
"text": "static Base64.Encoder getEncoder()"
},
{
"code": null,
"e": 3672,
"s": 3589,
"text": "Returns a Base64.Encoder that encodes using the Basic type base64 encoding scheme."
},
{
"code": null,
"e": 3711,
"s": 3672,
"text": "static Base64.Decoder getMimeDecoder()"
},
{
"code": null,
"e": 3793,
"s": 3711,
"text": "Returns a Base64.Decoder that decodes using the MIME type base64 decoding scheme."
},
{
"code": null,
"e": 3832,
"s": 3793,
"text": "static Base64.Encoder getMimeEncoder()"
},
{
"code": null,
"e": 3914,
"s": 3832,
"text": "Returns a Base64.Encoder that encodes using the MIME type base64 encoding scheme."
},
{
"code": null,
"e": 3989,
"s": 3914,
"text": "static Base64.Encoder getMimeEncoder(int lineLength, byte[] lineSeparator)"
},
{
"code": null,
"e": 4118,
"s": 3989,
"text": "Returns a Base64.Encoder that encodes using the MIME type base64 encoding scheme with specified line length and line separators."
},
{
"code": null,
"e": 4156,
"s": 4118,
"text": "static Base64.Decoder getUrlDecoder()"
},
{
"code": null,
"e": 4255,
"s": 4156,
"text": "Returns a Base64.Decoder that decodes using the URL and Filename safe type base64 encoding scheme."
},
{
"code": null,
"e": 4293,
"s": 4255,
"text": "static Base64.Encoder getUrlEncoder()"
},
{
"code": null,
"e": 4392,
"s": 4293,
"text": "Returns a Base64.Encoder that encodes using the URL and Filename safe type base64 encoding scheme."
},
{
"code": null,
"e": 4447,
"s": 4392,
"text": "This class inherits methods from the following class −"
},
{
"code": null,
"e": 4464,
"s": 4447,
"text": "java.lang.Object"
},
{
"code": null,
"e": 4548,
"s": 4464,
"text": "Create the following Java program using any editor of your choice in say C:/> JAVA."
},
{
"code": null,
"e": 5942,
"s": 4548,
"text": "import java.util.Base64;\nimport java.util.UUID;\nimport java.io.UnsupportedEncodingException;\n\npublic class HelloWorld {\n\n public static void main(String args[]) {\n\n try {\n\t\t\n // Encode using basic encoder\n String base64encodedString = Base64.getEncoder().encodeToString(\n \"TutorialsPoint?java8\".getBytes(\"utf-8\"));\n System.out.println(\"Base64 Encoded String (Basic) :\" + base64encodedString);\n\t\t\n // Decode\n byte[] base64decodedBytes = Base64.getDecoder().decode(base64encodedString);\n\t\t\n System.out.println(\"Original String: \" + new String(base64decodedBytes, \"utf-8\"));\n base64encodedString = Base64.getUrlEncoder().encodeToString(\n \"TutorialsPoint?java8\".getBytes(\"utf-8\"));\n System.out.println(\"Base64 Encoded String (URL) :\" + base64encodedString);\n\t\t\n StringBuilder stringBuilder = new StringBuilder();\n\t\t\n for (int i = 0; i < 10; ++i) {\n stringBuilder.append(UUID.randomUUID().toString());\n }\n\t\t\n byte[] mimeBytes = stringBuilder.toString().getBytes(\"utf-8\");\n String mimeEncodedString = Base64.getMimeEncoder().encodeToString(mimeBytes);\n System.out.println(\"Base64 Encoded String (MIME) :\" + mimeEncodedString);\n\n } catch(UnsupportedEncodingException e) {\n System.out.println(\"Error :\" + e.getMessage());\n }\n }\n}"
},
{
"code": null,
"e": 5994,
"s": 5942,
"text": "Compile the class using javac compiler as follows −"
},
{
"code": null,
"e": 6026,
"s": 5994,
"text": "C:\\JAVA>javac Java8Tester.java\n"
},
{
"code": null,
"e": 6063,
"s": 6026,
"text": "Now run the Java8Tester as follows −"
},
{
"code": null,
"e": 6089,
"s": 6063,
"text": "C:\\JAVA>java Java8Tester\n"
},
{
"code": null,
"e": 6130,
"s": 6089,
"text": "It should produce the following output −"
},
{
"code": null,
"e": 6804,
"s": 6130,
"text": "Base64 Encoded String (Basic) :VHV0b3JpYWxzUG9pbnQ/amF2YTg=\nOriginal String: TutorialsPoint?java8\nBase64 Encoded String (URL) :VHV0b3JpYWxzUG9pbnQ_amF2YTg=\nBase64 Encoded String (MIME) :YmU3NWY2ODktNGM5YS00ODlmLWI2MTUtZTVkOTk2YzQ1Njk1Y2EwZTg2OTEtMmRiZC00YTQ1LWJl\nNTctMTI1MWUwMTk0ZWQyNDE0NDAwYjgtYTYxOS00NDY5LTllYTctNjc1YzE3YWJhZTk1MTQ2MDQz\nNDItOTAyOC00ZWI0LThlOTYtZWU5YzcwNWQyYzVhMTQxMWRjYTMtY2MwNi00MzU0LTg0MTgtNGQ1\nMDkwYjdiMzg2ZTY0OWU5MmUtZmNkYS00YWEwLTg0MjQtYThiOTQxNDQ2YzhhNTVhYWExZjItNjU2\nMi00YmM4LTk2ZGYtMDE4YmY5ZDZhMjkwMzM3MWUzNDMtMmQ3MS00MDczLWI0Y2UtMTQxODE0MGU5\nYjdmYTVlODUxYzItN2NmOS00N2UyLWIyODQtMThlMWVkYTY4M2Q1YjE3YTMyYmItZjllMS00MTFk\nLWJiM2UtM2JhYzUxYzI5OWI4\n"
},
{
"code": null,
"e": 6837,
"s": 6804,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6853,
"s": 6837,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6886,
"s": 6853,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6902,
"s": 6886,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6937,
"s": 6902,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6951,
"s": 6937,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6985,
"s": 6951,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6999,
"s": 6985,
"text": " Tushar Kale"
},
{
"code": null,
"e": 7036,
"s": 6999,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 7051,
"s": 7036,
"text": " Monica Mittal"
},
{
"code": null,
"e": 7084,
"s": 7051,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 7103,
"s": 7084,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7110,
"s": 7103,
"text": " Print"
},
{
"code": null,
"e": 7121,
"s": 7110,
"text": " Add Notes"
}
]
|
MongoDB aggregate to get the count of field values of corresponding duplicate names? | Let us see an example and create a collection with documents −
> db.demo558.insertOne(
... {
... _id : 100,
... CountryCode:101,
... details: [
... {
... Name:"Chris",
... Subject:"MySQL"
... },
... {
... Name:"Chris",
... Subject:"MongoDB"
... },
... {
... Name:"Chris",
... Subject:"Java"
... },
... {
... Name:"Bob",
... Subject:"Python"
... },
... {
... Name:"Bob",
... Subject:"Java"
... }
... ]
... }
... )
{ "acknowledged" : true, "insertedId" : 100 }
Display all documents from a collection with the help of find() method −
> db.demo558.find();
This will produce the following output −
{ "_id" : 100, "CountryCode" : 101, "details" : [
{ "Name" : "Chris", "Subject" : "MySQL" },
{ "Name" : "Chris", "Subject" : "MongoDB" },
{ "Name" : "Chris", "Subject" : "Java" },
{ "Name" : "Bob", "Subject" : "Python" },
{ "Name" : "Bob", "Subject" : "Java" }
] }
Following is the query to get the count −
> db.demo558.aggregate([
... {$unwind: "$details" },
... {$group: { _id: "$details.Name", NameCount:{$sum : 1}, Subject : {$push: "$details.Subject"}}},
... {$project: { NameCount: 1, SubjectCount : {$size: "$Subject"}}}
... ]).pretty()
This will produce the following output −
{ "_id" : "Bob", "NameCount" : 2, "SubjectCount" : 2 }
{ "_id" : "Chris", "NameCount" : 3, "SubjectCount" : 3 } | [
{
"code": null,
"e": 1125,
"s": 1062,
"text": "Let us see an example and create a collection with documents −"
},
{
"code": null,
"e": 1683,
"s": 1125,
"text": "> db.demo558.insertOne(\n... {\n... _id : 100,\n... CountryCode:101,\n... details: [\n... {\n... Name:\"Chris\",\n... Subject:\"MySQL\"\n... },\n... {\n... Name:\"Chris\",\n... Subject:\"MongoDB\"\n... },\n... {\n... Name:\"Chris\",\n... Subject:\"Java\"\n... },\n... {\n... Name:\"Bob\",\n... Subject:\"Python\"\n... },\n... {\n... Name:\"Bob\",\n... Subject:\"Java\"\n... }\n... ]\n... }\n... )\n{ \"acknowledged\" : true, \"insertedId\" : 100 }"
},
{
"code": null,
"e": 1756,
"s": 1683,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1777,
"s": 1756,
"text": "> db.demo558.find();"
},
{
"code": null,
"e": 1818,
"s": 1777,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2098,
"s": 1818,
"text": "{ \"_id\" : 100, \"CountryCode\" : 101, \"details\" : [\n { \"Name\" : \"Chris\", \"Subject\" : \"MySQL\" },\n { \"Name\" : \"Chris\", \"Subject\" : \"MongoDB\" },\n { \"Name\" : \"Chris\", \"Subject\" : \"Java\" },\n { \"Name\" : \"Bob\", \"Subject\" : \"Python\" },\n { \"Name\" : \"Bob\", \"Subject\" : \"Java\" }\n] }"
},
{
"code": null,
"e": 2140,
"s": 2098,
"text": "Following is the query to get the count −"
},
{
"code": null,
"e": 2386,
"s": 2140,
"text": "> db.demo558.aggregate([\n... {$unwind: \"$details\" },\n... {$group: { _id: \"$details.Name\", NameCount:{$sum : 1}, Subject : {$push: \"$details.Subject\"}}},\n... {$project: { NameCount: 1, SubjectCount : {$size: \"$Subject\"}}}\n... ]).pretty()"
},
{
"code": null,
"e": 2427,
"s": 2386,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2539,
"s": 2427,
"text": "{ \"_id\" : \"Bob\", \"NameCount\" : 2, \"SubjectCount\" : 2 }\n{ \"_id\" : \"Chris\", \"NameCount\" : 3, \"SubjectCount\" : 3 }"
}
]
|
What is the implementation of a Lexical Analyzer? | Lexical Analysis is the first step of the compiler which reads the source code one character at a time and transforms it into an array of tokens. The token is a meaningful collection of characters in a program. These tokens can be keywords including do, if, while etc. and identifiers including x, num, count, etc. and operator symbols including >,>=, +, etc., and punctuation symbols including parenthesis or commas. The output of the lexical analyzer phase passes to the next phase called syntax analyzer or parser.
The syntax analyser or parser is also known as parsing phase. It takes tokens as input from lexical analyser phase. The syntax analyser groups tokens together into syntactic structures. The output of this phase is parse tree.
The main function of lexical analysis are as follows −
It can separate tokens from the program and return those tokens to the parser as requested by it.
It can separate tokens from the program and return those tokens to the parser as requested by it.
It can eliminate comments, whitespaces, newline characters, etc. from the string.
It can eliminate comments, whitespaces, newline characters, etc. from the string.
It can insert the token into the symbol table.
It can insert the token into the symbol table.
Lexical Analysis will return an integer number for each token to the parser.
Lexical Analysis will return an integer number for each token to the parser.
Stripping out the comments and whitespace (tab, newline, blank, and other characters that are used to separate tokens in the input).
Stripping out the comments and whitespace (tab, newline, blank, and other characters that are used to separate tokens in the input).
The correlating error messages that are produced by the compiler during lexical analyzer with the source program.
The correlating error messages that are produced by the compiler during lexical analyzer with the source program.
It can implement the expansion of macros, in the case of macro, pre-processors are used in the source code.
It can implement the expansion of macros, in the case of macro, pre-processors are used in the source code.
LEX generates Lexical Analyzer as its output by taking the LEX program as its input. LEX program is a collection of patterns (Regular Expression) and their corresponding Actions.
Patterns represent the tokens to be recognized by the lexical analyzer to be generated. For each pattern, a corresponding NFA will be designed.
There can be n number of NFAs for n number of patterns.
Example − If patterns are { }
P1 { }
P2 { }
Pn { }
Then NFA’s for corresponding patterns will be −
A start state is taken and using ε transition, and all these NFAs can be connected to make combined NFA −
The final state of each NFA shows that it has found its token Pi.
It converts the combined NFA to DFA as it is always easy to simulate the behavior of DFA with a program.
The final state shows which token we have found. If none of the states of DFA includes any final states of NFA then control returns to an error condition.
If the final state of DFA includes more than one final state of NFA, then the final state, for the pattern coming first in the Translation rules has priority. | [
{
"code": null,
"e": 1580,
"s": 1062,
"text": "Lexical Analysis is the first step of the compiler which reads the source code one character at a time and transforms it into an array of tokens. The token is a meaningful collection of characters in a program. These tokens can be keywords including do, if, while etc. and identifiers including x, num, count, etc. and operator symbols including >,>=, +, etc., and punctuation symbols including parenthesis or commas. The output of the lexical analyzer phase passes to the next phase called syntax analyzer or parser."
},
{
"code": null,
"e": 1806,
"s": 1580,
"text": "The syntax analyser or parser is also known as parsing phase. It takes tokens as input from lexical analyser phase. The syntax analyser groups tokens together into syntactic structures. The output of this phase is parse tree."
},
{
"code": null,
"e": 1861,
"s": 1806,
"text": "The main function of lexical analysis are as follows −"
},
{
"code": null,
"e": 1959,
"s": 1861,
"text": "It can separate tokens from the program and return those tokens to the parser as requested by it."
},
{
"code": null,
"e": 2057,
"s": 1959,
"text": "It can separate tokens from the program and return those tokens to the parser as requested by it."
},
{
"code": null,
"e": 2139,
"s": 2057,
"text": "It can eliminate comments, whitespaces, newline characters, etc. from the string."
},
{
"code": null,
"e": 2221,
"s": 2139,
"text": "It can eliminate comments, whitespaces, newline characters, etc. from the string."
},
{
"code": null,
"e": 2268,
"s": 2221,
"text": "It can insert the token into the symbol table."
},
{
"code": null,
"e": 2315,
"s": 2268,
"text": "It can insert the token into the symbol table."
},
{
"code": null,
"e": 2392,
"s": 2315,
"text": "Lexical Analysis will return an integer number for each token to the parser."
},
{
"code": null,
"e": 2469,
"s": 2392,
"text": "Lexical Analysis will return an integer number for each token to the parser."
},
{
"code": null,
"e": 2602,
"s": 2469,
"text": "Stripping out the comments and whitespace (tab, newline, blank, and other characters that are used to separate tokens in the input)."
},
{
"code": null,
"e": 2735,
"s": 2602,
"text": "Stripping out the comments and whitespace (tab, newline, blank, and other characters that are used to separate tokens in the input)."
},
{
"code": null,
"e": 2849,
"s": 2735,
"text": "The correlating error messages that are produced by the compiler during lexical analyzer with the source program."
},
{
"code": null,
"e": 2963,
"s": 2849,
"text": "The correlating error messages that are produced by the compiler during lexical analyzer with the source program."
},
{
"code": null,
"e": 3071,
"s": 2963,
"text": "It can implement the expansion of macros, in the case of macro, pre-processors are used in the source code."
},
{
"code": null,
"e": 3179,
"s": 3071,
"text": "It can implement the expansion of macros, in the case of macro, pre-processors are used in the source code."
},
{
"code": null,
"e": 3358,
"s": 3179,
"text": "LEX generates Lexical Analyzer as its output by taking the LEX program as its input. LEX program is a collection of patterns (Regular Expression) and their corresponding Actions."
},
{
"code": null,
"e": 3502,
"s": 3358,
"text": "Patterns represent the tokens to be recognized by the lexical analyzer to be generated. For each pattern, a corresponding NFA will be designed."
},
{
"code": null,
"e": 3558,
"s": 3502,
"text": "There can be n number of NFAs for n number of patterns."
},
{
"code": null,
"e": 3588,
"s": 3558,
"text": "Example − If patterns are { }"
},
{
"code": null,
"e": 3609,
"s": 3588,
"text": "P1 { }\nP2 { }\nPn { }"
},
{
"code": null,
"e": 3657,
"s": 3609,
"text": "Then NFA’s for corresponding patterns will be −"
},
{
"code": null,
"e": 3763,
"s": 3657,
"text": "A start state is taken and using ε transition, and all these NFAs can be connected to make combined NFA −"
},
{
"code": null,
"e": 3829,
"s": 3763,
"text": "The final state of each NFA shows that it has found its token Pi."
},
{
"code": null,
"e": 3934,
"s": 3829,
"text": "It converts the combined NFA to DFA as it is always easy to simulate the behavior of DFA with a program."
},
{
"code": null,
"e": 4089,
"s": 3934,
"text": "The final state shows which token we have found. If none of the states of DFA includes any final states of NFA then control returns to an error condition."
},
{
"code": null,
"e": 4248,
"s": 4089,
"text": "If the final state of DFA includes more than one final state of NFA, then the final state, for the pattern coming first in the Translation rules has priority."
}
]
|
Python while Loop Statements | A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true.
The syntax of a while loop in Python programming language is −
while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop.
In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements.
Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.
#!/usr/bin/python
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
When the above code is executed, it produces the following result −
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
The block here, consisting of the print and increment statements, is executed repeatedly until count is no longer less than 9. With each iteration, the current value of the index count is displayed and then increased by 1.
A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.
An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as and when required.
#!/usr/bin/python
var = 1
while var == 1 : # This constructs an infinite loop
num = raw_input("Enter a number :")
print "You entered: ", num
print "Good bye!"
When the above code is executed, it produces the following result −
Enter a number :20
You entered: 20
Enter a number :29
You entered: 29
Enter a number :3
You entered: 3
Enter a number between :Traceback (most recent call last):
File "test.py", line 5, in <module>
num = raw_input("Enter a number :")
KeyboardInterrupt
Above example goes in an infinite loop and you need to use CTRL+C to exit the program.
Python supports to have an else statement associated with a loop statement.
If the else statement is used with a while loop, the else statement is executed when the condition becomes false.
If the else statement is used with a while loop, the else statement is executed when the condition becomes false.
The following example illustrates the combination of an else statement with a while statement that prints a number as long as it is less than 5, otherwise else statement gets executed.
#!/usr/bin/python
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"
When the above code is executed, it produces the following result −
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
Similar to the if statement syntax, if your while clause consists only of a single statement, it may be placed on the same line as the while header.
Here is the syntax and example of a one-line while clause −
#!/usr/bin/python
flag = 1
while (flag): print 'Given flag is really true!'
print "Good bye!"
It is better not try above example because it goes into infinite loop and you need to press CTRL+C keys to exit.
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2375,
"s": 2244,
"text": "A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true."
},
{
"code": null,
"e": 2438,
"s": 2375,
"text": "The syntax of a while loop in Python programming language is −"
},
{
"code": null,
"e": 2473,
"s": 2438,
"text": "while expression:\n statement(s)\n"
},
{
"code": null,
"e": 2660,
"s": 2473,
"text": "Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true."
},
{
"code": null,
"e": 2761,
"s": 2660,
"text": "When the condition becomes false, program control passes to the line immediately following the loop."
},
{
"code": null,
"e": 2984,
"s": 2761,
"text": "In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements."
},
{
"code": null,
"e": 3202,
"s": 2984,
"text": "Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed."
},
{
"code": null,
"e": 3322,
"s": 3202,
"text": "#!/usr/bin/python\n\ncount = 0\nwhile (count < 9):\n print 'The count is:', count\n count = count + 1\n\nprint \"Good bye!\""
},
{
"code": null,
"e": 3390,
"s": 3322,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3545,
"s": 3390,
"text": "The count is: 0\nThe count is: 1\nThe count is: 2\nThe count is: 3\nThe count is: 4\nThe count is: 5\nThe count is: 6\nThe count is: 7\nThe count is: 8\nGood bye!\n"
},
{
"code": null,
"e": 3768,
"s": 3545,
"text": "The block here, consisting of the print and increment statements, is executed repeatedly until count is no longer less than 9. With each iteration, the current value of the index count is displayed and then increased by 1."
},
{
"code": null,
"e": 4037,
"s": 3768,
"text": "A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop."
},
{
"code": null,
"e": 4212,
"s": 4037,
"text": "An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as and when required."
},
{
"code": null,
"e": 4381,
"s": 4212,
"text": "#!/usr/bin/python\n\nvar = 1\nwhile var == 1 : # This constructs an infinite loop\n num = raw_input(\"Enter a number :\")\n print \"You entered: \", num\n\nprint \"Good bye!\""
},
{
"code": null,
"e": 4449,
"s": 4381,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 4717,
"s": 4449,
"text": "Enter a number :20\nYou entered: 20\nEnter a number :29\nYou entered: 29\nEnter a number :3\nYou entered: 3\nEnter a number between :Traceback (most recent call last):\n File \"test.py\", line 5, in <module>\n num = raw_input(\"Enter a number :\")\nKeyboardInterrupt\n"
},
{
"code": null,
"e": 4804,
"s": 4717,
"text": "Above example goes in an infinite loop and you need to use CTRL+C to exit the program."
},
{
"code": null,
"e": 4880,
"s": 4804,
"text": "Python supports to have an else statement associated with a loop statement."
},
{
"code": null,
"e": 4994,
"s": 4880,
"text": "If the else statement is used with a while loop, the else statement is executed when the condition becomes false."
},
{
"code": null,
"e": 5108,
"s": 4994,
"text": "If the else statement is used with a while loop, the else statement is executed when the condition becomes false."
},
{
"code": null,
"e": 5293,
"s": 5108,
"text": "The following example illustrates the combination of an else statement with a while statement that prints a number as long as it is less than 5, otherwise else statement gets executed."
},
{
"code": null,
"e": 5439,
"s": 5293,
"text": "#!/usr/bin/python\n\ncount = 0\nwhile count < 5:\n print count, \" is less than 5\"\n count = count + 1\nelse:\n print count, \" is not less than 5\""
},
{
"code": null,
"e": 5507,
"s": 5439,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 5614,
"s": 5507,
"text": "0 is less than 5\n1 is less than 5\n2 is less than 5\n3 is less than 5\n4 is less than 5\n5 is not less than 5\n"
},
{
"code": null,
"e": 5763,
"s": 5614,
"text": "Similar to the if statement syntax, if your while clause consists only of a single statement, it may be placed on the same line as the while header."
},
{
"code": null,
"e": 5823,
"s": 5763,
"text": "Here is the syntax and example of a one-line while clause −"
},
{
"code": null,
"e": 5918,
"s": 5823,
"text": "#!/usr/bin/python\n\nflag = 1\nwhile (flag): print 'Given flag is really true!'\nprint \"Good bye!\""
},
{
"code": null,
"e": 6031,
"s": 5918,
"text": "It is better not try above example because it goes into infinite loop and you need to press CTRL+C keys to exit."
},
{
"code": null,
"e": 6068,
"s": 6031,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6084,
"s": 6068,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6117,
"s": 6084,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6136,
"s": 6117,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6171,
"s": 6136,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 6193,
"s": 6171,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 6227,
"s": 6193,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6255,
"s": 6227,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 6290,
"s": 6255,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 6304,
"s": 6290,
"text": " Lets Kode It"
},
{
"code": null,
"e": 6337,
"s": 6304,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6354,
"s": 6337,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 6361,
"s": 6354,
"text": " Print"
},
{
"code": null,
"e": 6372,
"s": 6361,
"text": " Add Notes"
}
]
|
2 Keys Keyboard in C++ | Suppose we have only one character 'A' in a text editor. We can perform two operations on this letter for each step −
Copy All − We can copy all the characters present on the notepad
Paste − We can paste the characters which are copied last time.
Now suppose we have a number n. We have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. We have to find the result in the minimum number of steps to get n 'A'. So if the given n is 3, then answer will be 3, so initially there is only one “A”, Now copy this and paste this, so there will be “AA” now. Now we can paste again, so one ‘A’ will be placed. Thus we will get “AAA”.
To solve this, we will follow these steps −
ret := 0
for k in range 2 to nwhile n mod k is not 0ret := ret + k and n := n / k
while n mod k is not 0ret := ret + k and n := n / k
ret := ret + k and n := n / k
return ret
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int minSteps(int n) {
int ret = 0;
for(int k = 2; k <= n; k++){
for(; n % k == 0; ret += k, n /= k);
}
return ret;
}
};
main(){
Solution ob;
cout << (ob.minSteps(10));
}
10
7 | [
{
"code": null,
"e": 1180,
"s": 1062,
"text": "Suppose we have only one character 'A' in a text editor. We can perform two operations on this letter for each step −"
},
{
"code": null,
"e": 1245,
"s": 1180,
"text": "Copy All − We can copy all the characters present on the notepad"
},
{
"code": null,
"e": 1309,
"s": 1245,
"text": "Paste − We can paste the characters which are copied last time."
},
{
"code": null,
"e": 1725,
"s": 1309,
"text": "Now suppose we have a number n. We have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. We have to find the result in the minimum number of steps to get n 'A'. So if the given n is 3, then answer will be 3, so initially there is only one “A”, Now copy this and paste this, so there will be “AA” now. Now we can paste again, so one ‘A’ will be placed. Thus we will get “AAA”."
},
{
"code": null,
"e": 1769,
"s": 1725,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1778,
"s": 1769,
"text": "ret := 0"
},
{
"code": null,
"e": 1851,
"s": 1778,
"text": "for k in range 2 to nwhile n mod k is not 0ret := ret + k and n := n / k"
},
{
"code": null,
"e": 1903,
"s": 1851,
"text": "while n mod k is not 0ret := ret + k and n := n / k"
},
{
"code": null,
"e": 1933,
"s": 1903,
"text": "ret := ret + k and n := n / k"
},
{
"code": null,
"e": 1944,
"s": 1933,
"text": "return ret"
},
{
"code": null,
"e": 2014,
"s": 1944,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2025,
"s": 2014,
"text": " Live Demo"
},
{
"code": null,
"e": 2314,
"s": 2025,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int minSteps(int n) {\n int ret = 0;\n for(int k = 2; k <= n; k++){\n for(; n % k == 0; ret += k, n /= k);\n }\n return ret;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.minSteps(10));\n}"
},
{
"code": null,
"e": 2317,
"s": 2314,
"text": "10"
},
{
"code": null,
"e": 2319,
"s": 2317,
"text": "7"
}
]
|
Java Program for Cocktail Sort - GeeksforGeeks | 28 Jun, 2021
Cocktail Sort is a variation of Bubble sort. The Bubble sort algorithm always traverses elements from left and moves the largest element to its correct position in first iteration and second largest in second iteration and so on. Cocktail Sort traverses through a given array in both directions alternatively.
Algorithm:Each iteration of the algorithm is broken up into 2 stages:
The first stage loops through the array from left to right, just like the Bubble Sort. During the loop, adjacent items are compared and if value on the left is greater than the value on the right, then values are swapped. At the end of first iteration, largest number will reside at the end of the array.The second stage loops through the array in opposite direction- starting from the item just before the most recently sorted item, and moving back to the start of the array. Here also, adjacent items are compared and are swapped if required.
The first stage loops through the array from left to right, just like the Bubble Sort. During the loop, adjacent items are compared and if value on the left is greater than the value on the right, then values are swapped. At the end of first iteration, largest number will reside at the end of the array.
The second stage loops through the array in opposite direction- starting from the item just before the most recently sorted item, and moving back to the start of the array. Here also, adjacent items are compared and are swapped if required.
// Java program for implementation of Cocktail Sortpublic class CocktailSort { void cocktailSort(int a[]) { boolean swapped = true; int start = 0; int end = a.length; while (swapped == true) { // reset the swapped flag on entering the // loop, because it might be true from a // previous iteration. swapped = false; // loop from bottom to top same as // the bubble sort for (int i = start; i < end - 1; ++i) { if (a[i] > a[i + 1]) { int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; swapped = true; } } // if nothing moved, then array is sorted. if (swapped == false) break; // otherwise, reset the swapped flag so that it // can be used in the next stage swapped = false; // move the end point back by one, because // item at the end is in its rightful spot end = end - 1; // from top to bottom, doing the // same comparison as in the previous stage for (int i = end - 1; i >= start; i--) { if (a[i] > a[i + 1]) { int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; swapped = true; } } // increase the starting point, because // the last stage would have moved the next // smallest number to its rightful spot. start = start + 1; } } /* Prints the array */ void printArray(int a[]) { int n = a.length; for (int i = 0; i < n; i++) System.out.print(a[i] + " "); System.out.println(); } // Driver method public static void main(String[] args) { CocktailSort ob = new CocktailSort(); int a[] = { 5, 1, 4, 2, 8, 0, 2 }; ob.cocktailSort(a); System.out.println("Sorted array"); ob.printArray(a); }}
Sorted array
0 1 2 2 4 5 8
Please refer complete article on Cocktail Sort for more details!
Java Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Iterate HashMap in Java?
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
Modulo or Remainder Operator in Java | [
{
"code": null,
"e": 24591,
"s": 24563,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24901,
"s": 24591,
"text": "Cocktail Sort is a variation of Bubble sort. The Bubble sort algorithm always traverses elements from left and moves the largest element to its correct position in first iteration and second largest in second iteration and so on. Cocktail Sort traverses through a given array in both directions alternatively."
},
{
"code": null,
"e": 24971,
"s": 24901,
"text": "Algorithm:Each iteration of the algorithm is broken up into 2 stages:"
},
{
"code": null,
"e": 25516,
"s": 24971,
"text": "The first stage loops through the array from left to right, just like the Bubble Sort. During the loop, adjacent items are compared and if value on the left is greater than the value on the right, then values are swapped. At the end of first iteration, largest number will reside at the end of the array.The second stage loops through the array in opposite direction- starting from the item just before the most recently sorted item, and moving back to the start of the array. Here also, adjacent items are compared and are swapped if required."
},
{
"code": null,
"e": 25821,
"s": 25516,
"text": "The first stage loops through the array from left to right, just like the Bubble Sort. During the loop, adjacent items are compared and if value on the left is greater than the value on the right, then values are swapped. At the end of first iteration, largest number will reside at the end of the array."
},
{
"code": null,
"e": 26062,
"s": 25821,
"text": "The second stage loops through the array in opposite direction- starting from the item just before the most recently sorted item, and moving back to the start of the array. Here also, adjacent items are compared and are swapped if required."
},
{
"code": "// Java program for implementation of Cocktail Sortpublic class CocktailSort { void cocktailSort(int a[]) { boolean swapped = true; int start = 0; int end = a.length; while (swapped == true) { // reset the swapped flag on entering the // loop, because it might be true from a // previous iteration. swapped = false; // loop from bottom to top same as // the bubble sort for (int i = start; i < end - 1; ++i) { if (a[i] > a[i + 1]) { int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; swapped = true; } } // if nothing moved, then array is sorted. if (swapped == false) break; // otherwise, reset the swapped flag so that it // can be used in the next stage swapped = false; // move the end point back by one, because // item at the end is in its rightful spot end = end - 1; // from top to bottom, doing the // same comparison as in the previous stage for (int i = end - 1; i >= start; i--) { if (a[i] > a[i + 1]) { int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; swapped = true; } } // increase the starting point, because // the last stage would have moved the next // smallest number to its rightful spot. start = start + 1; } } /* Prints the array */ void printArray(int a[]) { int n = a.length; for (int i = 0; i < n; i++) System.out.print(a[i] + \" \"); System.out.println(); } // Driver method public static void main(String[] args) { CocktailSort ob = new CocktailSort(); int a[] = { 5, 1, 4, 2, 8, 0, 2 }; ob.cocktailSort(a); System.out.println(\"Sorted array\"); ob.printArray(a); }}",
"e": 28199,
"s": 26062,
"text": null
},
{
"code": null,
"e": 28227,
"s": 28199,
"text": "Sorted array\n0 1 2 2 4 5 8\n"
},
{
"code": null,
"e": 28292,
"s": 28227,
"text": "Please refer complete article on Cocktail Sort for more details!"
},
{
"code": null,
"e": 28306,
"s": 28292,
"text": "Java Programs"
},
{
"code": null,
"e": 28314,
"s": 28306,
"text": "Sorting"
},
{
"code": null,
"e": 28322,
"s": 28314,
"text": "Sorting"
},
{
"code": null,
"e": 28420,
"s": 28322,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28429,
"s": 28420,
"text": "Comments"
},
{
"code": null,
"e": 28442,
"s": 28429,
"text": "Old Comments"
},
{
"code": null,
"e": 28474,
"s": 28442,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 28522,
"s": 28474,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 28573,
"s": 28522,
"text": "How to Get Elements By Index from HashSet in Java?"
},
{
"code": null,
"e": 28607,
"s": 28573,
"text": "Java Program to Write into a File"
}
]
|
Hypergeometric Distribution in R Programming - GeeksforGeeks | 10 Jul, 2020
Hypergeometric Distribution in R Language is defined as a method that is used to calculate probabilities when sampling without replacement is to be done in order to get the density value.
In R, there are 4 built-in functions to generate Hypergeometric Distribution:
dhyper()dhyper(x, m, n, k)
dhyper(x, m, n, k)
phyper()phyper(x, m, n, k)
phyper(x, m, n, k)
qhyper()qhyper(x, m, n, k)
qhyper(x, m, n, k)
rhyper()rhyper(N, m, n, k)
rhyper(N, m, n, k)
where,
x: represents the data set of valuesm: size of the populationn: number of samples drawnk: number of items in the populationN: hypergeometrically distributed values
It is defined as Hypergeometric Density Distribution used in order to get the density value.
Syntax:
dhyper(x_dhyper, m, n, k)
Example 1:
# Specify x-values for dhyper functionx_dhyper <- seq(0, 22, by = 1.2) # Apply dhyper functiony_dhyper <- dhyper(x_dhyper, m = 45, n = 30, k = 20) # Plot dhyper valuesplot(y_dhyper)
Output:
Hypergeometric Cumulative Distribution Function used estimating the number of faults initially resident in a program at the beginning of the test or debugging process based on the hypergeometric distribution and calculate each value in x using the corresponding values.
Syntax:
phyper(x, m, n, k)
Example 1:
# Specify x-values for phyper functionx_phyper <- seq(0, 22, by = 1) # Apply phyper functiony_phyper <- phyper(x_phyper, m = 40, n = 20, k = 31) # Plot phyper valuesplot(y_phyper)
Output:
It is basically Hypergeometric Quantile Function used to specify a sequence of probabilities between 0 and 1.
Syntax:
qhyper(x, m, n, k)
Example 1:
# Specify x-values for qhyper functionx_qhyper <- seq(0, 1, by = 0.02) # Apply qhyper functiony_qhyper <- qhyper(x_qhyper, m = 49, n = 18, k = 30) # Plot qhyper valuesplot(y_qhyper)
Output:
It generally refers to generating random numbers function by specifying a seed and sample size.
Syntax:
rhyper(x, m, n, k)
Example 1:
# Set seed for reproducibility# Specify sample sizeset.seed(400) N <- 10000 # Draw N hypergeometrically distributed valuesy_rhyper <- rhyper(N, m = 50, n = 20, k = 30) y_rhyper # Plot of randomly drawn hyper densityhist(y_rhyper, breaks = 50, main = "")
Output :
R Statistics-Function
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?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R | [
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 25039,
"s": 24851,
"text": "Hypergeometric Distribution in R Language is defined as a method that is used to calculate probabilities when sampling without replacement is to be done in order to get the density value."
},
{
"code": null,
"e": 25117,
"s": 25039,
"text": "In R, there are 4 built-in functions to generate Hypergeometric Distribution:"
},
{
"code": null,
"e": 25144,
"s": 25117,
"text": "dhyper()dhyper(x, m, n, k)"
},
{
"code": null,
"e": 25163,
"s": 25144,
"text": "dhyper(x, m, n, k)"
},
{
"code": null,
"e": 25190,
"s": 25163,
"text": "phyper()phyper(x, m, n, k)"
},
{
"code": null,
"e": 25209,
"s": 25190,
"text": "phyper(x, m, n, k)"
},
{
"code": null,
"e": 25236,
"s": 25209,
"text": "qhyper()qhyper(x, m, n, k)"
},
{
"code": null,
"e": 25255,
"s": 25236,
"text": "qhyper(x, m, n, k)"
},
{
"code": null,
"e": 25282,
"s": 25255,
"text": "rhyper()rhyper(N, m, n, k)"
},
{
"code": null,
"e": 25301,
"s": 25282,
"text": "rhyper(N, m, n, k)"
},
{
"code": null,
"e": 25308,
"s": 25301,
"text": "where,"
},
{
"code": null,
"e": 25472,
"s": 25308,
"text": "x: represents the data set of valuesm: size of the populationn: number of samples drawnk: number of items in the populationN: hypergeometrically distributed values"
},
{
"code": null,
"e": 25565,
"s": 25472,
"text": "It is defined as Hypergeometric Density Distribution used in order to get the density value."
},
{
"code": null,
"e": 25573,
"s": 25565,
"text": "Syntax:"
},
{
"code": null,
"e": 25600,
"s": 25573,
"text": "dhyper(x_dhyper, m, n, k)\n"
},
{
"code": null,
"e": 25611,
"s": 25600,
"text": "Example 1:"
},
{
"code": " # Specify x-values for dhyper functionx_dhyper <- seq(0, 22, by = 1.2) # Apply dhyper functiony_dhyper <- dhyper(x_dhyper, m = 45, n = 30, k = 20) # Plot dhyper valuesplot(y_dhyper) ",
"e": 25803,
"s": 25611,
"text": null
},
{
"code": null,
"e": 25811,
"s": 25803,
"text": "Output:"
},
{
"code": null,
"e": 26081,
"s": 25811,
"text": "Hypergeometric Cumulative Distribution Function used estimating the number of faults initially resident in a program at the beginning of the test or debugging process based on the hypergeometric distribution and calculate each value in x using the corresponding values."
},
{
"code": null,
"e": 26089,
"s": 26081,
"text": "Syntax:"
},
{
"code": null,
"e": 26108,
"s": 26089,
"text": "phyper(x, m, n, k)"
},
{
"code": null,
"e": 26119,
"s": 26108,
"text": "Example 1:"
},
{
"code": "# Specify x-values for phyper functionx_phyper <- seq(0, 22, by = 1) # Apply phyper functiony_phyper <- phyper(x_phyper, m = 40, n = 20, k = 31) # Plot phyper valuesplot(y_phyper) ",
"e": 26311,
"s": 26119,
"text": null
},
{
"code": null,
"e": 26319,
"s": 26311,
"text": "Output:"
},
{
"code": null,
"e": 26429,
"s": 26319,
"text": "It is basically Hypergeometric Quantile Function used to specify a sequence of probabilities between 0 and 1."
},
{
"code": null,
"e": 26437,
"s": 26429,
"text": "Syntax:"
},
{
"code": null,
"e": 26456,
"s": 26437,
"text": "qhyper(x, m, n, k)"
},
{
"code": null,
"e": 26467,
"s": 26456,
"text": "Example 1:"
},
{
"code": "# Specify x-values for qhyper functionx_qhyper <- seq(0, 1, by = 0.02) # Apply qhyper functiony_qhyper <- qhyper(x_qhyper, m = 49, n = 18, k = 30) # Plot qhyper valuesplot(y_qhyper)",
"e": 26663,
"s": 26467,
"text": null
},
{
"code": null,
"e": 26671,
"s": 26663,
"text": "Output:"
},
{
"code": null,
"e": 26767,
"s": 26671,
"text": "It generally refers to generating random numbers function by specifying a seed and sample size."
},
{
"code": null,
"e": 26775,
"s": 26767,
"text": "Syntax:"
},
{
"code": null,
"e": 26794,
"s": 26775,
"text": "rhyper(x, m, n, k)"
},
{
"code": null,
"e": 26805,
"s": 26794,
"text": "Example 1:"
},
{
"code": "# Set seed for reproducibility# Specify sample sizeset.seed(400) N <- 10000 # Draw N hypergeometrically distributed valuesy_rhyper <- rhyper(N, m = 50, n = 20, k = 30) y_rhyper # Plot of randomly drawn hyper densityhist(y_rhyper, breaks = 50, main = \"\")",
"e": 27190,
"s": 26805,
"text": null
},
{
"code": null,
"e": 27199,
"s": 27190,
"text": "Output :"
},
{
"code": null,
"e": 27221,
"s": 27199,
"text": "R Statistics-Function"
},
{
"code": null,
"e": 27232,
"s": 27221,
"text": "R Language"
},
{
"code": null,
"e": 27330,
"s": 27232,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27339,
"s": 27330,
"text": "Comments"
},
{
"code": null,
"e": 27352,
"s": 27339,
"text": "Old Comments"
},
{
"code": null,
"e": 27404,
"s": 27352,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27442,
"s": 27404,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27477,
"s": 27442,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27535,
"s": 27477,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27578,
"s": 27535,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 27627,
"s": 27578,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 27677,
"s": 27627,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 27694,
"s": 27677,
"text": "R - if statement"
},
{
"code": null,
"e": 27731,
"s": 27694,
"text": "How to import an Excel File into R ?"
}
]
|
C# | Sealed Class - GeeksforGeeks | 01 Oct, 2021
Sealed classes are used to restrict the users from inheriting the class. A class can be sealed by using the sealed keyword. The keyword tells the compiler that the class is sealed, and therefore, cannot be extended. No class can be derived from a sealed class.
The following is the syntax of a sealed class :
sealed class class_name
{
// data members
// methods
.
.
.
}
A method can also be sealed, and in that case, the method cannot be overridden. However, a method can be sealed in the classes in which they have been inherited. If you want to declare a method as sealed, then it has to be declared as virtual in its base class.
The following class definition defines a sealed class in C#:
In the following code, create a sealed class SealedClass and use it from Program. If you run this code then it will work fine.
C#
// C# code to define// a Sealed Classusing System; // Sealed classsealed class SealedClass { // Calling Function public int Add(int a, int b) { return a + b; }} class Program { // Main Method static void Main(string[] args) { // Creating an object of Sealed Class SealedClass slc = new SealedClass(); // Performing Addition operation int total = slc.Add(6, 4); Console.WriteLine("Total = " + total.ToString()); }}
Output :
Total = 10
Now, if it is tried to inherit a class from a sealed class then an error will be produced stating that ” It cannot be derived from a Sealed class.
C#
// C# code to show restrictions// of a Sealed Classusing System; class Bird { } // Creating a sealed classsealed class Test : Bird {} // Inheriting the Sealed Classclass Example : Test {} // Driver Classclass Program { // Main Method static void Main() { }}
Error:
Error CS0509 ‘Example’ : cannot derive from sealed type ‘Test’
Consider the following example of a sealed method in a derived class :
C#
// C# program to// define Sealed Classusing System; class Printer { // Display Function for // Dimension printing public virtual void show() { Console.WriteLine("display dimension : 6*6"); } // Display Function public virtual void print() { Console.WriteLine("printer printing....\n"); }} // inheriting classclass LaserJet : Printer { // Sealed Display Function // for Dimension printing sealed override public void show() { Console.WriteLine("display dimension : 12*12"); } // Function to override // Print() function override public void print() { Console.WriteLine("Laserjet printer printing....\n"); }} // Officejet class cannot override show// function as it is sealed in LaserJet class.class Officejet : LaserJet { // can not override show function or else // compiler error : 'Officejet.show()' : // cannot override inherited member // 'LaserJet.show()' because it is sealed. override public void print() { Console.WriteLine("Officejet printer printing...."); }} // Driver Classclass Program { // Driver Code static void Main(string[] args) { Printer p = new Printer(); p.show(); p.print(); Printer ls = new LaserJet(); ls.show(); ls.print(); Printer of = new Officejet(); of.show(); of.print(); }}
Output :
display dimension : 6*6
Printer printing....
display dimension : 12*12
LaserJet printer printing....
display dimension : 12*12
Officejet printer printing....
Explanation: In above C# code, Printer class has display unit with the dimension of 6*6 and LaserJet class have implemented the show method by overriding it to have the dimension of 12*12. If any class will inherit LaserJet class then it will have the same dimension of 12*12 and can’t implement its own i.e. it cannot have 15*15, 16*16 or any other dimensions. So, LaserJet call will seal the show method to prevent further overriding of it.
Why Sealed Classes?
Sealed class is used to stop a class to be inherited. You cannot derive or extend any class from it.
Sealed method is implemented so that no other class can overthrow it and implement its own method.
The main purpose of the sealed class is to withdraw the inheritance attribute from the user so that they can’t attain a class from a sealed class. Sealed classes are used best when you have a class with static members. e.g the “Pens” and “Brushes” classes of the System.Drawing namespace. The Pens class represents the pens for standard colors. This class has only static members. For example, “Pens.Red” represents a pen with red color. Similarly, the “Brushes” class represents standard brushes. “Brushes.Red” represents a brush with red color.
gabaa406
CSharp-OOP
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Dictionary with examples
C# | Delegates
Top 50 C# Interview Questions & Answers
Extension Method in C#
Introduction to .NET Framework
C# | String.IndexOf( ) Method | Set - 1
Different ways to sort an array in descending order in C#
Common Language Runtime (CLR) in C#
HashSet in C# with Examples
C# | Replace() Method | [
{
"code": null,
"e": 23795,
"s": 23767,
"text": "\n01 Oct, 2021"
},
{
"code": null,
"e": 24056,
"s": 23795,
"text": "Sealed classes are used to restrict the users from inheriting the class. A class can be sealed by using the sealed keyword. The keyword tells the compiler that the class is sealed, and therefore, cannot be extended. No class can be derived from a sealed class."
},
{
"code": null,
"e": 24105,
"s": 24056,
"text": "The following is the syntax of a sealed class : "
},
{
"code": null,
"e": 24187,
"s": 24105,
"text": "sealed class class_name\n{\n // data members\n // methods\n .\n .\n .\n\n}"
},
{
"code": null,
"e": 24449,
"s": 24187,
"text": "A method can also be sealed, and in that case, the method cannot be overridden. However, a method can be sealed in the classes in which they have been inherited. If you want to declare a method as sealed, then it has to be declared as virtual in its base class."
},
{
"code": null,
"e": 24510,
"s": 24449,
"text": "The following class definition defines a sealed class in C#:"
},
{
"code": null,
"e": 24639,
"s": 24510,
"text": "In the following code, create a sealed class SealedClass and use it from Program. If you run this code then it will work fine. "
},
{
"code": null,
"e": 24642,
"s": 24639,
"text": "C#"
},
{
"code": "// C# code to define// a Sealed Classusing System; // Sealed classsealed class SealedClass { // Calling Function public int Add(int a, int b) { return a + b; }} class Program { // Main Method static void Main(string[] args) { // Creating an object of Sealed Class SealedClass slc = new SealedClass(); // Performing Addition operation int total = slc.Add(6, 4); Console.WriteLine(\"Total = \" + total.ToString()); }}",
"e": 25126,
"s": 24642,
"text": null
},
{
"code": null,
"e": 25136,
"s": 25126,
"text": "Output : "
},
{
"code": null,
"e": 25147,
"s": 25136,
"text": "Total = 10"
},
{
"code": null,
"e": 25294,
"s": 25147,
"text": "Now, if it is tried to inherit a class from a sealed class then an error will be produced stating that ” It cannot be derived from a Sealed class."
},
{
"code": null,
"e": 25297,
"s": 25294,
"text": "C#"
},
{
"code": "// C# code to show restrictions// of a Sealed Classusing System; class Bird { } // Creating a sealed classsealed class Test : Bird {} // Inheriting the Sealed Classclass Example : Test {} // Driver Classclass Program { // Main Method static void Main() { }}",
"e": 25568,
"s": 25297,
"text": null
},
{
"code": null,
"e": 25575,
"s": 25568,
"text": "Error:"
},
{
"code": null,
"e": 25638,
"s": 25575,
"text": "Error CS0509 ‘Example’ : cannot derive from sealed type ‘Test’"
},
{
"code": null,
"e": 25710,
"s": 25638,
"text": "Consider the following example of a sealed method in a derived class : "
},
{
"code": null,
"e": 25713,
"s": 25710,
"text": "C#"
},
{
"code": "// C# program to// define Sealed Classusing System; class Printer { // Display Function for // Dimension printing public virtual void show() { Console.WriteLine(\"display dimension : 6*6\"); } // Display Function public virtual void print() { Console.WriteLine(\"printer printing....\\n\"); }} // inheriting classclass LaserJet : Printer { // Sealed Display Function // for Dimension printing sealed override public void show() { Console.WriteLine(\"display dimension : 12*12\"); } // Function to override // Print() function override public void print() { Console.WriteLine(\"Laserjet printer printing....\\n\"); }} // Officejet class cannot override show// function as it is sealed in LaserJet class.class Officejet : LaserJet { // can not override show function or else // compiler error : 'Officejet.show()' : // cannot override inherited member // 'LaserJet.show()' because it is sealed. override public void print() { Console.WriteLine(\"Officejet printer printing....\"); }} // Driver Classclass Program { // Driver Code static void Main(string[] args) { Printer p = new Printer(); p.show(); p.print(); Printer ls = new LaserJet(); ls.show(); ls.print(); Printer of = new Officejet(); of.show(); of.print(); }}",
"e": 27115,
"s": 25713,
"text": null
},
{
"code": null,
"e": 27125,
"s": 27115,
"text": "Output : "
},
{
"code": null,
"e": 27285,
"s": 27125,
"text": "display dimension : 6*6\nPrinter printing....\n\ndisplay dimension : 12*12\nLaserJet printer printing....\n\ndisplay dimension : 12*12\nOfficejet printer printing...."
},
{
"code": null,
"e": 27728,
"s": 27285,
"text": "Explanation: In above C# code, Printer class has display unit with the dimension of 6*6 and LaserJet class have implemented the show method by overriding it to have the dimension of 12*12. If any class will inherit LaserJet class then it will have the same dimension of 12*12 and can’t implement its own i.e. it cannot have 15*15, 16*16 or any other dimensions. So, LaserJet call will seal the show method to prevent further overriding of it."
},
{
"code": null,
"e": 27749,
"s": 27728,
"text": "Why Sealed Classes? "
},
{
"code": null,
"e": 27850,
"s": 27749,
"text": "Sealed class is used to stop a class to be inherited. You cannot derive or extend any class from it."
},
{
"code": null,
"e": 27949,
"s": 27850,
"text": "Sealed method is implemented so that no other class can overthrow it and implement its own method."
},
{
"code": null,
"e": 28496,
"s": 27949,
"text": "The main purpose of the sealed class is to withdraw the inheritance attribute from the user so that they can’t attain a class from a sealed class. Sealed classes are used best when you have a class with static members. e.g the “Pens” and “Brushes” classes of the System.Drawing namespace. The Pens class represents the pens for standard colors. This class has only static members. For example, “Pens.Red” represents a pen with red color. Similarly, the “Brushes” class represents standard brushes. “Brushes.Red” represents a brush with red color."
},
{
"code": null,
"e": 28507,
"s": 28498,
"text": "gabaa406"
},
{
"code": null,
"e": 28518,
"s": 28507,
"text": "CSharp-OOP"
},
{
"code": null,
"e": 28521,
"s": 28518,
"text": "C#"
},
{
"code": null,
"e": 28619,
"s": 28521,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28628,
"s": 28619,
"text": "Comments"
},
{
"code": null,
"e": 28641,
"s": 28628,
"text": "Old Comments"
},
{
"code": null,
"e": 28669,
"s": 28641,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 28684,
"s": 28669,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28724,
"s": 28684,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28747,
"s": 28724,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28778,
"s": 28747,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 28818,
"s": 28778,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 28876,
"s": 28818,
"text": "Different ways to sort an array in descending order in C#"
},
{
"code": null,
"e": 28912,
"s": 28876,
"text": "Common Language Runtime (CLR) in C#"
},
{
"code": null,
"e": 28940,
"s": 28912,
"text": "HashSet in C# with Examples"
}
]
|
MySQL Exercises With Solutions | Theory of Computation
+------------------------+------------------------------+----------+----------+
| first_name | last_name | age | dept |
+------------------------+------------------------------+----------+----------+
| Mesa | Loop | 30 | Acct |
| Smith | Oak | 27 | Devl |
| John | Jorz | 37 | QA |
| Hary | Gaga | 32 | QA |
+------------------------+------------------------------+----------+----------+
+----+--------------+------------+-----+
| id | name | department | age |
+----+--------------+------------+-----+
| 1 | Maria Gloria | CS | 22 |
| 2 | John Smith | IT | 23 |
| 3 | Gal Rao | CS | 22 |
| 4 | Jakey Smith | EC | 24 |
| 5 | Rama Saho | IT | 22 |
| 6 | Maria Gaga | EC | 23 |
+----+--------------+------------+-----+
+----+--------------+------------+-----+
| id | name | department | age |
+----+--------------+------------+-----+
| 1 | Maria Gloria | CS | 22 |
| 2 | John Smith | IT | 23 |
| 3 | Gal Rao | CS | 22 |
| 4 | Jakey Smith | EC | 24 |
| 5 | Rama Saho | IT | 22 |
| 6 | Maria Gaga | EC | 23 |
+----+--------------+------------+-----+
+----+--------------+------------+------------+
| id | name | department | birth |
+----+--------------+------------+------------+
| 1 | Maria Gloria | CS | 1994-03-12 |
| 2 | John Smith | IT | 1993-02-07 |
| 3 | Gal Rao | CS | 1992-09-11 |
| 4 | Jakey Smith | EC | 1990-08-31 |
| 5 | Rama Saho | IT | 1994-12-09 |
| 6 | Maria Gaga | EC | 1993-10-09 |
+----+--------------+------------+------------+
+----+--------------+------------+------------+
| id | name | department | birth |
+----+--------------+------------+------------+
| 1 | Maria Gloria | CS | 1994-03-12 |
| 2 | John Smith | IT | 1993-02-07 |
| 3 | Gal Rao | CS | 1992-09-11 |
| 4 | Jakey Smith | EC | 1990-08-31 |
| 5 | Rama Saho | IT | 1994-12-09 |
| 6 | Maria Gaga | EC | 1993-10-09 |
+----+--------------+------------+------------+
+----+--------------+------------+------------+
| id | name | dept_id | birth |
+----+--------------+------------+------------+
| 1 | Maria Gloria | 2 | 1994-03-12 |
| 2 | John Smith | 1 | 1993-02-07 |
| 3 | Gal Rao | 4 | 1992-09-11 |
| 4 | Jakey Smith | 2 | 1990-08-31 |
| 5 | Rama Saho | 1 | 1994-12-09 |
| 6 | Maria Gaga | 4 | 1993-10-09 |
+----+--------------+------------+------------+
+---------+--------------------------+------------+
| dept_id | dept_name | dept_block |
+---------+--------------------------+------------+
| 1 | Computer Science | B-Block |
| 2 | Information Technology | C-Block |
| 3 | Mechanical | A-Block |
| 4 | Electronic Communication | D-Block |
+---------+--------------------------+------------+
+----+-------+---------+------------+
| id | name | dept_id | birth |
+----+-------+---------+------------+
| 1 | Maria | 2 | 1994-03-12 |
| 2 | John | 1 | 1993-02-07 |
| 3 | Gal | 4 | 1992-09-11 |
| 4 | Jakey | 2 | 1990-08-31 |
| 5 | Rama | 1 | 1994-12-09 |
| 6 | Maria | 4 | 1993-10-09 | | [
{
"code": null,
"e": 112,
"s": 90,
"text": "Theory of Computation"
},
{
"code": null,
"e": 758,
"s": 112,
"text": " \n+------------------------+------------------------------+----------+----------+\n| first_name | last_name | age | dept |\n+------------------------+------------------------------+----------+----------+\n| Mesa | Loop | 30 | Acct |\n| Smith | Oak | 27 | Devl | \n| John | Jorz | 37 | QA | \n| Hary | Gaga | 32 | QA | \n+------------------------+------------------------------+----------+----------+\n"
},
{
"code": null,
"e": 1171,
"s": 758,
"text": " \n+----+--------------+------------+-----+\n| id | name | department | age |\n+----+--------------+------------+-----+\n| 1 | Maria Gloria | CS | 22 |\n| 2 | John Smith | IT | 23 |\n| 3 | Gal Rao | CS | 22 |\n| 4 | Jakey Smith | EC | 24 |\n| 5 | Rama Saho | IT | 22 |\n| 6 | Maria Gaga | EC | 23 |\n+----+--------------+------------+-----+\n"
},
{
"code": null,
"e": 1584,
"s": 1171,
"text": " \n+----+--------------+------------+-----+\n| id | name | department | age |\n+----+--------------+------------+-----+\n| 1 | Maria Gloria | CS | 22 |\n| 2 | John Smith | IT | 23 |\n| 3 | Gal Rao | CS | 22 |\n| 4 | Jakey Smith | EC | 24 |\n| 5 | Rama Saho | IT | 22 |\n| 6 | Maria Gaga | EC | 23 |\n+----+--------------+------------+-----+\n"
},
{
"code": null,
"e": 2067,
"s": 1584,
"text": " \n+----+--------------+------------+------------+\n| id | name | department | birth |\n+----+--------------+------------+------------+\n| 1 | Maria Gloria | CS | 1994-03-12 |\n| 2 | John Smith | IT | 1993-02-07 |\n| 3 | Gal Rao | CS | 1992-09-11 |\n| 4 | Jakey Smith | EC | 1990-08-31 |\n| 5 | Rama Saho | IT | 1994-12-09 |\n| 6 | Maria Gaga | EC | 1993-10-09 |\n+----+--------------+------------+------------+\n"
},
{
"code": null,
"e": 2550,
"s": 2067,
"text": " \n+----+--------------+------------+------------+\n| id | name | department | birth |\n+----+--------------+------------+------------+\n| 1 | Maria Gloria | CS | 1994-03-12 |\n| 2 | John Smith | IT | 1993-02-07 |\n| 3 | Gal Rao | CS | 1992-09-11 |\n| 4 | Jakey Smith | EC | 1990-08-31 |\n| 5 | Rama Saho | IT | 1994-12-09 |\n| 6 | Maria Gaga | EC | 1993-10-09 |\n+----+--------------+------------+------------+\n"
},
{
"code": null,
"e": 3453,
"s": 2550,
"text": " \n+----+--------------+------------+------------+ \n| id | name | dept_id | birth |\n+----+--------------+------------+------------+\n| 1 | Maria Gloria | 2 | 1994-03-12 |\n| 2 | John Smith | 1 | 1993-02-07 |\n| 3 | Gal Rao | 4 | 1992-09-11 |\n| 4 | Jakey Smith | 2 | 1990-08-31 |\n| 5 | Rama Saho | 1 | 1994-12-09 |\n| 6 | Maria Gaga | 4 | 1993-10-09 |\n+----+--------------+------------+------------+\n\n+---------+--------------------------+------------+\n| dept_id | dept_name | dept_block |\n+---------+--------------------------+------------+\n| 1 | Computer Science | B-Block |\n| 2 | Information Technology | C-Block |\n| 3 | Mechanical | A-Block |\n| 4 | Electronic Communication | D-Block |\n+---------+--------------------------+------------+\n"
}
]
|
Applied Deep Learning - Part 1: Artificial Neural Networks | by Arden Dertat | Towards Data Science | Welcome to the Applied Deep Learning tutorial series. We will do a detailed analysis of several deep learning techniques starting with Artificial Neural Networks (ANN), in particular Feedforward Neural Networks. What separates this tutorial from the rest you can find online is that we’ll take a hands-on approach with plenty of code examples and visualization. I won’t go into too much math and theory behind these models to keep the focus on application.
We will use the Keras deep learning framework, which is a high level API on top of Tensorflow. Keras is becoming super popular recently because of its simplicity. It’s very easy to build complex models and iterate rapidly. I also used barebone Tensorflow, and actually struggled quite a bit. After trying out Keras I’m not going back.
Here’s the table of contents. First an overview of ANN and the intuition behind these deep models. Then we will start simple with Logistic Regression, mainly to get familiar with Keras. Then we will train deep neural nets and demonstrate how they outperform linear models. We will compare the models on both binary and multiclass classification datasets.
ANN Overview1.1) Introduction1.2) Intuition1.3) ReasoningLogistic Regression2.1) Linearly Separable Data2.2) Complex Data - Moons2.3) Complex Data - CirclesArtificial Neural Networks (ANN)3.1) Complex Data - Moons3.2) Complex Data - Circles3.3) Complex Data - Sine WaveMulticlass Classification4.1) Softmax Regression4.2) Deep ANNConclusion
ANN Overview1.1) Introduction1.2) Intuition1.3) Reasoning
Logistic Regression2.1) Linearly Separable Data2.2) Complex Data - Moons2.3) Complex Data - Circles
Artificial Neural Networks (ANN)3.1) Complex Data - Moons3.2) Complex Data - Circles3.3) Complex Data - Sine Wave
Multiclass Classification4.1) Softmax Regression4.2) Deep ANN
Conclusion
The code for this article is available here as a Jupyter notebook, feel free to download and try it out yourself.
I think you’ll learn a lot from this article. You don’t need to have prior knowledge of deep learning, only some basic familiarity with general machine learning. So let’s begin...
Artificial Neural Networks (ANN) are multi-layer fully-connected neural nets that look like the figure below. They consist of an input layer, multiple hidden layers, and an output layer. Every node in one layer is connected to every other node in the next layer. We make the network deeper by increasing the number of hidden layers.
If we zoom in to one of the hidden or output nodes, what we will encounter is the figure below.
A given node takes the weighted sum of its inputs, and passes it through a non-linear activation function. This is the output of the node, which then becomes the input of another node in the next layer. The signal flows from left to right, and the final output is calculated by performing this procedure for all the nodes. Training this deep neural network means learning the weights associated with all the edges.
The equation for a given node looks as follows. The weighted sum of its inputs passed through a non-linear activation function. It can be represented as a vector dot product, where n is the number of inputs for the node.
I omitted the bias term for simplicity. Bias is an input to all the nodes and always has the value 1. It allows to shift the result of the activation function to the left or right. It also helps the model to train when all the input features are 0. If this sounds complicated right now you can safely ignore the bias terms. For completeness, the above equation looks as follows with the bias included.
So far we have described the forward pass, meaning given an input and weights how the output is computed. After the training is complete, we only run the forward pass to make the predictions. But we first need to train our model to actually learn the weights, and the training procedure works as follows:
Randomly initialize the weights for all the nodes. There are smart initialization methods which we will explore in another article.
For every training example, perform a forward pass using the current weights, and calculate the output of each node going from left to right. The final output is the value of the last node.
Compare the final output with the actual target in the training data, and measure the error using a loss function.
Perform a backwards pass from right to left and propagate the error to every individual node using backpropagation. Calculate each weight’s contribution to the error, and adjust the weights accordingly using gradient descent. Propagate the error gradients back starting from the last layer.
Backpropagation with gradient descent is literally the “magic” behind the deep learning models. It’s a rather long topic and involves some calculus, so we won’t go into the specifics in this applied deep learning series. For a detailed explanation of gradient descent refer here. A basic overview of backpropagation is available here. For a detailed mathematical treatment refer here and here. And for more advanced optimization algorithms refer here.
In the standard ML world this feed forward architecture is known as the multilayer perceptron. The difference between the ANN and perceptron is that ANN uses a non-linear activation function such as sigmoid but the perceptron uses the step function. And that non-linearity gives the ANN its great power.
There’s a lot going on already, even with the basic forward pass. Now let’s simplify this, and understand the intuition behind it.
Essentially what each layer of the ANN does is a non-linear transformation of the input from one vector space to another.
Let’s use the ANN in Figure 1 above as an example. We have a 3-dimensional input corresponding to a vector in 3D space. We then pass it through two hidden layers with 4 nodes each. And the final output is a 1D vector or a scalar.
So if we visualize this as a sequence of vector transformations, we first map the 3D input to a 4D vector space, then we perform another transformation to a new 4D space, and the final transformation reduces it to 1D. This is just a chain of matrix multiplications. The forward pass performs these matrix dot products and applies the activation function element-wise to the result. The figure below only shows the weight matrices being used (not the activations).
The input vector x has 1 row and 3 columns. To transform it into a 4D space, we need to multiply it with a 3x4 matrix. Then to another 4D space, we multiply with a 4x4 matrix. And finally to reduce it to a 1D space, we use a 4x1 matrix.
Notice how the dimensions of the matrices represent the input and output dimensions of a layer. The connection between a layer with 3 nodes and 4 nodes is a matrix multiplication using a 3x4 matrix.
These matrices represent the weights that define the ANN. To make a prediction using the ANN on a given input, we only need to know these weights and the activation function (and the biases), nothing more. We train the ANN via backpropagation to “learn” these weights.
If we put everything together it looks like the figure below.
A fully connected layer between 3 nodes and 4 nodes is just a matrix multiplication of the 1x3 input vector (yellow nodes) with the 3x4 weight matrix W1. The result of this dot product is a 1x4 vector represented as the blue nodes. We then multiply this 1x4 vector with a 4x4 matrix W2, resulting in a 1x4 vector, the green nodes. And finally a using a 4x1 matrix W3 we get the output.
We have omitted the activation function in the above figures for simplicity. In reality after every matrix multiplication, we apply the activation function to each element of the resulting matrix. More formally
The output of the matrix multiplications go through the activation function f. In case of the sigmoid function, this means taking the sigmoid of each element in the matrix. We can see the chain of matrix multiplications more clearly in the equations.
So far we talked about what deep models are and how they work, but why do we need to go deep in the first place?
We saw that a layer of ANN just performs a non-linear transformation of its inputs from one vector space to another. If we take a classification problem as an example, we want to separate out the classes by drawing a decision boundary. The input data in its given form is not separable. By performing non-linear transformations at each layer, we are able to project the input to a new vector space, and draw a complex decision boundary to separate the classes.
Let’s visualize what we just described with a concrete example. Given the following data we can see that it isn’t linearly separable.
So we project it to a higher dimensional space by performing a non-linear transformation, and then it becomes linearly separable. The green hyperplane is the decision boundary.
This is equivalent to drawing a complex decision boundary in the original input space.
So the main benefit of having a deeper model is being able to do more non-linear transformations of the input and drawing a more complex decision boundary.
As a summary, ANNs are very flexible yet powerful deep learning models. They are universal function approximators, meaning they can model any complex function. There has been an incredible surge on their popularity recently due to a couple of reasons: clever tricks which made training these models possible, huge increase in computational power especially GPUs and distributed training, and vast amount of training data. All these combined enabled deep learning to gain significant traction.
This was a brief introduction, there are tons of great tutorials online which cover deep neural nets. For reference, I highly recommend this paper. It’s a fantastic overview of deep learning and Section 4 covers ANN. Another great reference is this book which is available online.
Despite its name, logistic regression (LR) is a binary classification algorithm. It’s the most popular technique for 0/1 classification. On a 2 dimensional (2D) data LR will try to draw a straight line to separate the classes, that’s where the term linear model comes from. LR works with any number of dimensions though, not just two. For 3D data it’ll try to draw a 2D plane to separate the classes. This generalizes to N dimensional data and N-1 dimensional hyperplane separator. If you have a supervised binary classification problem, given an input data with multiple columns and a binary 0/1 outcome, LR is the first method to try. In this section we will focus on 2D data since it’s easier to visualize, and in another tutorial we will focus on multidimensional input.
First let’s start with an easy example. 2D linearly separable data. We are using the scikit-learn make_classification method to generate our data and using a helper function to visualize it.
There is a LogisticRegression classifier available in scikit-learn, I won’t go into too much detail here since our goal is to learn building models with Keras. But here’s how to train an LR model, using the fit function just like any other model in scikit-learn. We see the linear decision boundary as the green line.
As we can see the data is linearly separable. We will now train the same logistic regression model with Keras to predict the class membership of every input point. To keep things simple for now, we won’t perform the standard practices of separating out the data to training and test sets, or performing k-fold cross-validation.
Keras has great documentation, check it out for a more detailed description of its API. Here’s the code for training the model, let’s go over it step by step below.
We will use the Sequential model API available here. The Sequential model allows us to build deep neural networks by stacking layers one on top of another. Since we’re now building a simple logistic regression model, we will have the input nodes directly connected to output node, without any hidden layers. Note that the LR model has the form y=f(xW) where f is the sigmoid function. Having a single output layer being directly connected to the input reflects this function.
Quick clarification to disambiguate the terms being used. In neural networks literature, it’s common to talk about input nodes and output nodes. This may sound strange at first glance, what’s an input “node” per se? When we say input nodes, we’re talking about the features of a given training example. In our case we have 2 features, the x and y coordinates of the points we plotted above, so we have 2 input nodes. You can simply think of it as a vector of 2 numbers. What about the output node then? The output of the logistic regression model is a single number, the probability of an input data point belonging to class 1. In other words P(class=1). The probability of an input point belonging to class 0 is then P(class=0)=1−P(class=1). So you can simply think of the output node as a vector with a single number (or simply a scalar) between 0 and 1.
In Keras we don’t add layers corresponding to input nodes, we only do for hidden and output nodes. In our current model, we don’t have any hidden layers, the input nodes are directly connected to the output node. This means our neural network definition in Keras will just have one layer with one node, corresponding to the output node.
model = Sequential()model.add(Dense(units=1, input_shape=(2,), activation='sigmoid'))
The Dense function in Keras constructs a fully connected neural network layer, automatically initializing the weights as biases. It’s a super useful function that you will see being used everywhere. The function arguments are defined as follows:
units: The first argument, representing number of nodes in this layer. Since we’re constructing the output layer, and we said it has only one node, this value is 1.
input_shape: The first layer in Keras models need to specify the input dimensions. The subsequent layers (which we don’t have here but we will in later sections) don’t need to specify this argument because Keras can infer the dimensions automatically. In this case our input dimensionality is 2, the x and y coordinates. The input_shape parameter expects a vector, so in our case it’s a tuple with one number.
activation: The activation function of a logistic regression model is the logistic function, or alternatively called the sigmoid. We will explore different activation functions, where to use them and why in another tutorial.
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
We then compile the model with the compile function. This creates the neural network model by specifying the details of the learning process. The model hasn’t been trained yet. Right now we’re just declaring the optimizer to use and the loss function to minimize. The arguments for the compile function are defined as follows:
optimizer: Which optimizer to use in order to minimize the loss function. There are a lot of different optimizers, most of them based on gradient descent. We will explore different optimizers in another tutorial. For now we will use the adam optimizer, which is the one people prefer to use by default.
loss: The loss function to minimize. Since we’re building a binary 0/1 classifier, the loss function to minimize is binary_crossentropy. We will see other examples of loss functions in later sections.
metrics: Which metric to report statistics on, for classification problems we set this as accuracy.
history = model.fit(x=X, y=y, verbose=0, epochs=50)
Now comes the fun part of actually training the model using the fit function. The arguments are as follows:
x: The input data, we defined it as X above. It contains the x and y coordinates of the input points
y: Not to be confused with the y coordinate of the input points. In all ML tutorials y refers to the labels, in our case the class we’re trying to predict: 0 or 1.
verbose: Prints out the loss and accuracy, set it to 1 to see the output.
epochs: Number of times to go over the entire training data. When training models we pass through the training data not just once but multiple times.
plot_loss_accuracy(history)
The output of the fit method is the loss and accuracy at every epoch. We then plot it using our custom function, and see that the loss goes down to almost 0 over time, and the accuracy goes up to almost 1. Great! We have successfully trained our first neural network model with Keras. I know this was a long explanation, but I wanted to explain what we’re doing in detail the first time. Once you understand what’s going on and practice a couple of times, all this becomes second nature.
Below is a plot of the decision boundary. The various shades of blue and red represent the probability of a hypothetical point in that area belonging to class 1 or 0. The top left area is classified as class 1, with the color blue. The bottom right area is classified as class 0, colored as red. And there is a transition around the decision boundary. This is a cool way to visualize the decision boundary the model is learning.
The classification report shows the precision and recall of our model. We get close to 100% accuracy. The value shown in the report should be 0.997 but it got rounded up to 1.0.
The confusion matrix shows us how many classes were correctly classified vs misclassified. The numbers on the diagonal axis represent the number of correctly classified points, the rest are the misclassified ones. This particular matrix is not very interesting because the model only misclassifies 3 points. We can see one of the misclassified points at the top right part of the confusion matrix, the true value is class 0 but the predicted value is class 1.
The previous dataset was linearly separable, so it was trivial for our logistic regression model to separate the classes. Here is a more complex dataset which isn’t linearly separable. The simple logistic regression model won’t be able to clearly distinguish between the classes. We’re using the make_moons method of scikit-learn to generate the data.
Let’s build another logistic regression model with the same parameters as we did before. On this dataset we get 86% accuracy.
The current decision boundary doesn’t look as clean as the one before. The model tried to separate out the classes from the middle, but there are a lot of misclassified points. We need a more complex classifier with a non-linear decision boundary, and we will see an example of that soon.
Precision of the model is 86%. It looks good on paper but we should easily be able to get 100% with a more complex model. You can imagine a curved decision boundary that will separate out the classes, and a complex model should be able to approximate that.
The classification report and the confusion matrix looks as follows.
Let’s look at one final example where the liner model will fail. This time using the make_circles function in scikit-learn.
Building the model with same parameters.
The decision boundary again passes from the middle of the data, but now we have much more misclassified points.
The accuracy is around 50%, shown below. No matter where the model draws the line, it will misclassify half of the points, due to the nature of the dataset.
The confusion matrix we see here is an example one belonging to a poor classifier. Ideally we prefer confusion matrices to look like the ones we saw above. High numbers along the diagonals meaning that the classifier was right, and low numbers everywhere else where the classifier was wrong. In our visualization, the color blue represents large numbers and yellow represents the smaller ones. So we would prefer to see blue on the diagonals and yellow everywhere else. Blue color everywhere is a bad sign meaning that our classifier is confused.
The most naive method which always predicts 1 no matter what the input is would get a 50% accuracy. Our model also got 50% accuracy, so it’s not useful at all.
Now we will train a deep Artificial Neural Networks (ANN) to better classify the datasets which the logistic regression model struggled, Moons and Circles. We will also classify an even harder dataset of Sine Wave to demonstrate that ANN can form really complex decision boundaries.
While building Keras models for logistic regression above, we performed the following steps:
Step 1: Define a Sequential model.
Step 2: Add a Dense layer with sigmoid activation function. This was the only layer we needed.
Step 3: Compile the model with an optimizer and loss function.
Step 4: Fit the model to the dataset.
Step 5: Analyze the results: plotting loss/accuracy curves, plotting the decision boundary, looking at the classification report, and understanding the confusion matrix.
While building a deep neural network, we only need to change step 2 such that, we will add several Dense layers one after another. The output of one layer becomes the input of the next. Keras again does most of the heavy lifting by initializing the weights and biases, and connecting the output of one layer to the input of the next. We only need to specify how many nodes we want in a given layer, and the activation function. It’s as simple as that.
We first add a layer with 4 nodes and tanh activation function. Tanh is a commonly used activation function, and we’ll learn more about it in another tutorial. We then add another layer with 2 nodes again using tanh activation. We finally add the last layer with 1 node and sigmoid activation. This is the final layer that we also used in the logistic regression model.
This is not a very deep ANN, it only has 3 layers: 2 hidden layers, and the output layer. But notice a couple of patterns:
Output layer still uses the sigmoid activation function since we’re working on a binary classification problem.
Hidden layers use the tanh activation function. If we added more hidden layers, they would also use tanh activation. We have a couple of options for activation functions: sigmoid, tanh, relu, and variants of relu. In another article we’ll explore the pros and cons of each one. We will also demonstrate why using sigmoid activation in hidden layers is a bad idea. For now it’s safe to use tanh.
We have fewer number of nodes in each subsequent layer. It’s common to have less nodes as we stack layers on top of one another, sort of a triangular shape.
We didn’t build a very deep ANN here because it wasn’t necessary. We already achieve 100% accuracy with this configuration.
The ANN is able to come up with a perfect separator to distinguish the classes.
100% precision, nothing misclassified.
Now let’s look at the Circles dataset, where the LR model achieved only 50% accuracy. The model is the same as above, we only change the input to the fit function using the current dataset. And we again achieve 100% accuracy.
Similarly the decision boundary looks just like the one we would draw by hand ourselves. The ANN was able to figure out an optimal separator.
Just like above we get 100% accuracy.
Let’s try to classify one final toy dataset. In the previous sections, the classes were separable by one continuous decision boundary. The boundary had a complex shape, it wasn’t linear, but still one continuous decision boundary was enough. ANN can draw arbitrary number of complex decision boundaries, and we will demonstrate that.
Let’s create a sinusoidal dataset looking like the sine function, every up and down belonging to an alternating class. As we can see in the figure, a single decision boundary won’t be able to separate out the classes. We will need a series of non-linear separators.
Now we need a more complex model for accurate classification. So we have 3 hidden layers, and an output layer. The number of nodes per layer has also increased to improve the learning capacity of the model. Choosing the right number of hidden layers and nodes per layer is more of an art than science, usually decided by trial and error.
The ANN was able to model a pretty complex set of decision boundaries.
Precision is 99%, we only have 14 misclassified points out of 2400. Pretty good.
In the previous sections we worked on binary classification. Now we will take a look at a multi-class classification problem, where the number of classes is more than 2. We will pick 3 classes for demonstration, but our approach generalizes to any number of classes.
Here’s how our dataset looks like, spiral data with 3 classes, using the make_multiclass method in scikit-learn.
As we saw above, Logistic Regression (LR) is a classification method for 2 classes. It works with binary labels 0/1. Softmax Regression (SR) is a generalization of LR where we can have more than 2 classes. In our current dataset we have 3 classes, represented as 0/1/2.
Building the model for SR is very similar to LR, for reference here’s how we built our Logistic Regression model.
And here’s how how we will build the Softmax Regression model.
There are a couple of differences, let’s go over them one by one:
Number of nodes in the dense layer: LR uses 1 node, where SR has 3 nodes. Since we have 3 classes it makes sense for SR to be using 3 nodes. Then the question is, why does LR uses only 1 node, it has 2 classes so it appears like we should have used 2 nodes instead. The answer is, because we can achieve the same result with using only 1 node. As we saw above, LR models the probability of an example belonging to class one: P(class=1). And we can calculate class 0 probability by: 1−P(class=1). But when we have more than 2 classes, we need individual nodes for each class. Because knowing the probability of one class doesn’t let us infer the probability of the other classes.
Activation function: LR used sigmoid activation function, SR uses softmax. Softmax scales the values of the output nodes such that they represent probabilities and sum up to 1. So in our case P(class=0)+P(class=1)+P(class=2)=1. It doesn’t do it in a naive way by dividing individual probabilities by the sum though, it uses the exponential function. So higher values get emphasized more and lower values get squashed more. We will talk in detail what softmax does in another tutorial. For now you can simply think of it as a normalization function which lets us interpret the output values as probabilities.
Loss function: In a binary classification problem like LR, the loss function is binary_crossentropy. In the multiclass case, the loss function is categorical_crossentropy. Categorical crossentropy is the generalization of binary crossentropy to more than 2 classes. Going into the theory behind loss functions is beyond the scope of this tutorial. But for now only knowing this property is enough.
Fit function: LR used the vector y directly in the fit function, which has just one column with 0/1 values. When we’re doing SR the labels need to be in one-hot representation. In our case y_cat is a matrix with 3 columns, where all the values are 0 except for the one that represents our class, and that is 1.
It took some time to talk about all the differences between LR and SR, and it looks like there’s a lot to digest. But again after some practice this will become a habit, and you won’t even need to think about any of this.
After all this theory let’s take a step back and remember that LR is a linear classifier. SR is also a linear classifier, but for multiple classes. So the “power” of the model hasn’t changed, it’s still a linear model. We just generalized LR to apply it to a multiclass problem.
Training the model gives us an accuracy of around 50%. The most naive method which always predicts class 1 no matter what the input is would have an accuracy of 33%. The SR model is not much of an improvement over it. Which is expected because the dataset is not linearly separable.
Looking at the decision boundary confirms that we still have a linear classifier. The lines look jagged due to floating point rounding but in reality they’re straight.
Here’s the precision and recall corresponding to the 3 classes. And the confusion matrix is all over the place. Clearly this is not an optimal classifier.
Now let’s build a deep ANN for multiclass classification. Remember that the changes going from LR to ANN was minimal. We only needed to add more Dense layers. We will do the same again. Adding a couple of Dense layers with tanh activation function.
Note that the output layer still has 3 nodes, and uses the softmax activation. The loss function also didn’t change, still categorical_crossentropy. These won’t change going from a linear model to a deep ANN, since the problem definition hasn’t changed. We’re still working on multiclass classification. But now using a more powerful model, and that power comes from adding more layers to our neural net.
We achieve 99% accuracy in just a couple of epochs.
The decision boundary is non-linear.
We got almost 100% accuracy. We totally misclassified 5 points out of 1500.
Thanks for spending time reading this article, I know this was a rather lengthy tutorial on Artificial Neural Networks and Keras. I wanted to be as detailed as possible, while still keeping the article length manageable. I hope you enjoyed it.
There was a common theme in this article such that we first introduced the task, we then approached it using a simple method and observed the limitations. Afterwards we used a more complex deep model to improve on it and got much better results. I think the ordering is important. No complex method becomes successful unless it has evolved from a simpler model.
The entire code for this article is available here if you want to hack on it yourself. If you have any feedback feel free to reach out to me on twitter. | [
{
"code": null,
"e": 628,
"s": 171,
"text": "Welcome to the Applied Deep Learning tutorial series. We will do a detailed analysis of several deep learning techniques starting with Artificial Neural Networks (ANN), in particular Feedforward Neural Networks. What separates this tutorial from the rest you can find online is that we’ll take a hands-on approach with plenty of code examples and visualization. I won’t go into too much math and theory behind these models to keep the focus on application."
},
{
"code": null,
"e": 963,
"s": 628,
"text": "We will use the Keras deep learning framework, which is a high level API on top of Tensorflow. Keras is becoming super popular recently because of its simplicity. It’s very easy to build complex models and iterate rapidly. I also used barebone Tensorflow, and actually struggled quite a bit. After trying out Keras I’m not going back."
},
{
"code": null,
"e": 1318,
"s": 963,
"text": "Here’s the table of contents. First an overview of ANN and the intuition behind these deep models. Then we will start simple with Logistic Regression, mainly to get familiar with Keras. Then we will train deep neural nets and demonstrate how they outperform linear models. We will compare the models on both binary and multiclass classification datasets."
},
{
"code": null,
"e": 1659,
"s": 1318,
"text": "ANN Overview1.1) Introduction1.2) Intuition1.3) ReasoningLogistic Regression2.1) Linearly Separable Data2.2) Complex Data - Moons2.3) Complex Data - CirclesArtificial Neural Networks (ANN)3.1) Complex Data - Moons3.2) Complex Data - Circles3.3) Complex Data - Sine WaveMulticlass Classification4.1) Softmax Regression4.2) Deep ANNConclusion"
},
{
"code": null,
"e": 1717,
"s": 1659,
"text": "ANN Overview1.1) Introduction1.2) Intuition1.3) Reasoning"
},
{
"code": null,
"e": 1817,
"s": 1717,
"text": "Logistic Regression2.1) Linearly Separable Data2.2) Complex Data - Moons2.3) Complex Data - Circles"
},
{
"code": null,
"e": 1931,
"s": 1817,
"text": "Artificial Neural Networks (ANN)3.1) Complex Data - Moons3.2) Complex Data - Circles3.3) Complex Data - Sine Wave"
},
{
"code": null,
"e": 1993,
"s": 1931,
"text": "Multiclass Classification4.1) Softmax Regression4.2) Deep ANN"
},
{
"code": null,
"e": 2004,
"s": 1993,
"text": "Conclusion"
},
{
"code": null,
"e": 2118,
"s": 2004,
"text": "The code for this article is available here as a Jupyter notebook, feel free to download and try it out yourself."
},
{
"code": null,
"e": 2298,
"s": 2118,
"text": "I think you’ll learn a lot from this article. You don’t need to have prior knowledge of deep learning, only some basic familiarity with general machine learning. So let’s begin..."
},
{
"code": null,
"e": 2631,
"s": 2298,
"text": "Artificial Neural Networks (ANN) are multi-layer fully-connected neural nets that look like the figure below. They consist of an input layer, multiple hidden layers, and an output layer. Every node in one layer is connected to every other node in the next layer. We make the network deeper by increasing the number of hidden layers."
},
{
"code": null,
"e": 2727,
"s": 2631,
"text": "If we zoom in to one of the hidden or output nodes, what we will encounter is the figure below."
},
{
"code": null,
"e": 3142,
"s": 2727,
"text": "A given node takes the weighted sum of its inputs, and passes it through a non-linear activation function. This is the output of the node, which then becomes the input of another node in the next layer. The signal flows from left to right, and the final output is calculated by performing this procedure for all the nodes. Training this deep neural network means learning the weights associated with all the edges."
},
{
"code": null,
"e": 3363,
"s": 3142,
"text": "The equation for a given node looks as follows. The weighted sum of its inputs passed through a non-linear activation function. It can be represented as a vector dot product, where n is the number of inputs for the node."
},
{
"code": null,
"e": 3765,
"s": 3363,
"text": "I omitted the bias term for simplicity. Bias is an input to all the nodes and always has the value 1. It allows to shift the result of the activation function to the left or right. It also helps the model to train when all the input features are 0. If this sounds complicated right now you can safely ignore the bias terms. For completeness, the above equation looks as follows with the bias included."
},
{
"code": null,
"e": 4070,
"s": 3765,
"text": "So far we have described the forward pass, meaning given an input and weights how the output is computed. After the training is complete, we only run the forward pass to make the predictions. But we first need to train our model to actually learn the weights, and the training procedure works as follows:"
},
{
"code": null,
"e": 4202,
"s": 4070,
"text": "Randomly initialize the weights for all the nodes. There are smart initialization methods which we will explore in another article."
},
{
"code": null,
"e": 4392,
"s": 4202,
"text": "For every training example, perform a forward pass using the current weights, and calculate the output of each node going from left to right. The final output is the value of the last node."
},
{
"code": null,
"e": 4507,
"s": 4392,
"text": "Compare the final output with the actual target in the training data, and measure the error using a loss function."
},
{
"code": null,
"e": 4798,
"s": 4507,
"text": "Perform a backwards pass from right to left and propagate the error to every individual node using backpropagation. Calculate each weight’s contribution to the error, and adjust the weights accordingly using gradient descent. Propagate the error gradients back starting from the last layer."
},
{
"code": null,
"e": 5250,
"s": 4798,
"text": "Backpropagation with gradient descent is literally the “magic” behind the deep learning models. It’s a rather long topic and involves some calculus, so we won’t go into the specifics in this applied deep learning series. For a detailed explanation of gradient descent refer here. A basic overview of backpropagation is available here. For a detailed mathematical treatment refer here and here. And for more advanced optimization algorithms refer here."
},
{
"code": null,
"e": 5554,
"s": 5250,
"text": "In the standard ML world this feed forward architecture is known as the multilayer perceptron. The difference between the ANN and perceptron is that ANN uses a non-linear activation function such as sigmoid but the perceptron uses the step function. And that non-linearity gives the ANN its great power."
},
{
"code": null,
"e": 5685,
"s": 5554,
"text": "There’s a lot going on already, even with the basic forward pass. Now let’s simplify this, and understand the intuition behind it."
},
{
"code": null,
"e": 5807,
"s": 5685,
"text": "Essentially what each layer of the ANN does is a non-linear transformation of the input from one vector space to another."
},
{
"code": null,
"e": 6037,
"s": 5807,
"text": "Let’s use the ANN in Figure 1 above as an example. We have a 3-dimensional input corresponding to a vector in 3D space. We then pass it through two hidden layers with 4 nodes each. And the final output is a 1D vector or a scalar."
},
{
"code": null,
"e": 6501,
"s": 6037,
"text": "So if we visualize this as a sequence of vector transformations, we first map the 3D input to a 4D vector space, then we perform another transformation to a new 4D space, and the final transformation reduces it to 1D. This is just a chain of matrix multiplications. The forward pass performs these matrix dot products and applies the activation function element-wise to the result. The figure below only shows the weight matrices being used (not the activations)."
},
{
"code": null,
"e": 6738,
"s": 6501,
"text": "The input vector x has 1 row and 3 columns. To transform it into a 4D space, we need to multiply it with a 3x4 matrix. Then to another 4D space, we multiply with a 4x4 matrix. And finally to reduce it to a 1D space, we use a 4x1 matrix."
},
{
"code": null,
"e": 6937,
"s": 6738,
"text": "Notice how the dimensions of the matrices represent the input and output dimensions of a layer. The connection between a layer with 3 nodes and 4 nodes is a matrix multiplication using a 3x4 matrix."
},
{
"code": null,
"e": 7206,
"s": 6937,
"text": "These matrices represent the weights that define the ANN. To make a prediction using the ANN on a given input, we only need to know these weights and the activation function (and the biases), nothing more. We train the ANN via backpropagation to “learn” these weights."
},
{
"code": null,
"e": 7268,
"s": 7206,
"text": "If we put everything together it looks like the figure below."
},
{
"code": null,
"e": 7654,
"s": 7268,
"text": "A fully connected layer between 3 nodes and 4 nodes is just a matrix multiplication of the 1x3 input vector (yellow nodes) with the 3x4 weight matrix W1. The result of this dot product is a 1x4 vector represented as the blue nodes. We then multiply this 1x4 vector with a 4x4 matrix W2, resulting in a 1x4 vector, the green nodes. And finally a using a 4x1 matrix W3 we get the output."
},
{
"code": null,
"e": 7865,
"s": 7654,
"text": "We have omitted the activation function in the above figures for simplicity. In reality after every matrix multiplication, we apply the activation function to each element of the resulting matrix. More formally"
},
{
"code": null,
"e": 8116,
"s": 7865,
"text": "The output of the matrix multiplications go through the activation function f. In case of the sigmoid function, this means taking the sigmoid of each element in the matrix. We can see the chain of matrix multiplications more clearly in the equations."
},
{
"code": null,
"e": 8229,
"s": 8116,
"text": "So far we talked about what deep models are and how they work, but why do we need to go deep in the first place?"
},
{
"code": null,
"e": 8690,
"s": 8229,
"text": "We saw that a layer of ANN just performs a non-linear transformation of its inputs from one vector space to another. If we take a classification problem as an example, we want to separate out the classes by drawing a decision boundary. The input data in its given form is not separable. By performing non-linear transformations at each layer, we are able to project the input to a new vector space, and draw a complex decision boundary to separate the classes."
},
{
"code": null,
"e": 8824,
"s": 8690,
"text": "Let’s visualize what we just described with a concrete example. Given the following data we can see that it isn’t linearly separable."
},
{
"code": null,
"e": 9001,
"s": 8824,
"text": "So we project it to a higher dimensional space by performing a non-linear transformation, and then it becomes linearly separable. The green hyperplane is the decision boundary."
},
{
"code": null,
"e": 9088,
"s": 9001,
"text": "This is equivalent to drawing a complex decision boundary in the original input space."
},
{
"code": null,
"e": 9244,
"s": 9088,
"text": "So the main benefit of having a deeper model is being able to do more non-linear transformations of the input and drawing a more complex decision boundary."
},
{
"code": null,
"e": 9737,
"s": 9244,
"text": "As a summary, ANNs are very flexible yet powerful deep learning models. They are universal function approximators, meaning they can model any complex function. There has been an incredible surge on their popularity recently due to a couple of reasons: clever tricks which made training these models possible, huge increase in computational power especially GPUs and distributed training, and vast amount of training data. All these combined enabled deep learning to gain significant traction."
},
{
"code": null,
"e": 10018,
"s": 9737,
"text": "This was a brief introduction, there are tons of great tutorials online which cover deep neural nets. For reference, I highly recommend this paper. It’s a fantastic overview of deep learning and Section 4 covers ANN. Another great reference is this book which is available online."
},
{
"code": null,
"e": 10793,
"s": 10018,
"text": "Despite its name, logistic regression (LR) is a binary classification algorithm. It’s the most popular technique for 0/1 classification. On a 2 dimensional (2D) data LR will try to draw a straight line to separate the classes, that’s where the term linear model comes from. LR works with any number of dimensions though, not just two. For 3D data it’ll try to draw a 2D plane to separate the classes. This generalizes to N dimensional data and N-1 dimensional hyperplane separator. If you have a supervised binary classification problem, given an input data with multiple columns and a binary 0/1 outcome, LR is the first method to try. In this section we will focus on 2D data since it’s easier to visualize, and in another tutorial we will focus on multidimensional input."
},
{
"code": null,
"e": 10984,
"s": 10793,
"text": "First let’s start with an easy example. 2D linearly separable data. We are using the scikit-learn make_classification method to generate our data and using a helper function to visualize it."
},
{
"code": null,
"e": 11302,
"s": 10984,
"text": "There is a LogisticRegression classifier available in scikit-learn, I won’t go into too much detail here since our goal is to learn building models with Keras. But here’s how to train an LR model, using the fit function just like any other model in scikit-learn. We see the linear decision boundary as the green line."
},
{
"code": null,
"e": 11630,
"s": 11302,
"text": "As we can see the data is linearly separable. We will now train the same logistic regression model with Keras to predict the class membership of every input point. To keep things simple for now, we won’t perform the standard practices of separating out the data to training and test sets, or performing k-fold cross-validation."
},
{
"code": null,
"e": 11795,
"s": 11630,
"text": "Keras has great documentation, check it out for a more detailed description of its API. Here’s the code for training the model, let’s go over it step by step below."
},
{
"code": null,
"e": 12271,
"s": 11795,
"text": "We will use the Sequential model API available here. The Sequential model allows us to build deep neural networks by stacking layers one on top of another. Since we’re now building a simple logistic regression model, we will have the input nodes directly connected to output node, without any hidden layers. Note that the LR model has the form y=f(xW) where f is the sigmoid function. Having a single output layer being directly connected to the input reflects this function."
},
{
"code": null,
"e": 13128,
"s": 12271,
"text": "Quick clarification to disambiguate the terms being used. In neural networks literature, it’s common to talk about input nodes and output nodes. This may sound strange at first glance, what’s an input “node” per se? When we say input nodes, we’re talking about the features of a given training example. In our case we have 2 features, the x and y coordinates of the points we plotted above, so we have 2 input nodes. You can simply think of it as a vector of 2 numbers. What about the output node then? The output of the logistic regression model is a single number, the probability of an input data point belonging to class 1. In other words P(class=1). The probability of an input point belonging to class 0 is then P(class=0)=1−P(class=1). So you can simply think of the output node as a vector with a single number (or simply a scalar) between 0 and 1."
},
{
"code": null,
"e": 13465,
"s": 13128,
"text": "In Keras we don’t add layers corresponding to input nodes, we only do for hidden and output nodes. In our current model, we don’t have any hidden layers, the input nodes are directly connected to the output node. This means our neural network definition in Keras will just have one layer with one node, corresponding to the output node."
},
{
"code": null,
"e": 13551,
"s": 13465,
"text": "model = Sequential()model.add(Dense(units=1, input_shape=(2,), activation='sigmoid'))"
},
{
"code": null,
"e": 13797,
"s": 13551,
"text": "The Dense function in Keras constructs a fully connected neural network layer, automatically initializing the weights as biases. It’s a super useful function that you will see being used everywhere. The function arguments are defined as follows:"
},
{
"code": null,
"e": 13962,
"s": 13797,
"text": "units: The first argument, representing number of nodes in this layer. Since we’re constructing the output layer, and we said it has only one node, this value is 1."
},
{
"code": null,
"e": 14372,
"s": 13962,
"text": "input_shape: The first layer in Keras models need to specify the input dimensions. The subsequent layers (which we don’t have here but we will in later sections) don’t need to specify this argument because Keras can infer the dimensions automatically. In this case our input dimensionality is 2, the x and y coordinates. The input_shape parameter expects a vector, so in our case it’s a tuple with one number."
},
{
"code": null,
"e": 14597,
"s": 14372,
"text": "activation: The activation function of a logistic regression model is the logistic function, or alternatively called the sigmoid. We will explore different activation functions, where to use them and why in another tutorial."
},
{
"code": null,
"e": 14679,
"s": 14597,
"text": "model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])"
},
{
"code": null,
"e": 15006,
"s": 14679,
"text": "We then compile the model with the compile function. This creates the neural network model by specifying the details of the learning process. The model hasn’t been trained yet. Right now we’re just declaring the optimizer to use and the loss function to minimize. The arguments for the compile function are defined as follows:"
},
{
"code": null,
"e": 15309,
"s": 15006,
"text": "optimizer: Which optimizer to use in order to minimize the loss function. There are a lot of different optimizers, most of them based on gradient descent. We will explore different optimizers in another tutorial. For now we will use the adam optimizer, which is the one people prefer to use by default."
},
{
"code": null,
"e": 15510,
"s": 15309,
"text": "loss: The loss function to minimize. Since we’re building a binary 0/1 classifier, the loss function to minimize is binary_crossentropy. We will see other examples of loss functions in later sections."
},
{
"code": null,
"e": 15610,
"s": 15510,
"text": "metrics: Which metric to report statistics on, for classification problems we set this as accuracy."
},
{
"code": null,
"e": 15662,
"s": 15610,
"text": "history = model.fit(x=X, y=y, verbose=0, epochs=50)"
},
{
"code": null,
"e": 15770,
"s": 15662,
"text": "Now comes the fun part of actually training the model using the fit function. The arguments are as follows:"
},
{
"code": null,
"e": 15871,
"s": 15770,
"text": "x: The input data, we defined it as X above. It contains the x and y coordinates of the input points"
},
{
"code": null,
"e": 16035,
"s": 15871,
"text": "y: Not to be confused with the y coordinate of the input points. In all ML tutorials y refers to the labels, in our case the class we’re trying to predict: 0 or 1."
},
{
"code": null,
"e": 16109,
"s": 16035,
"text": "verbose: Prints out the loss and accuracy, set it to 1 to see the output."
},
{
"code": null,
"e": 16259,
"s": 16109,
"text": "epochs: Number of times to go over the entire training data. When training models we pass through the training data not just once but multiple times."
},
{
"code": null,
"e": 16287,
"s": 16259,
"text": "plot_loss_accuracy(history)"
},
{
"code": null,
"e": 16775,
"s": 16287,
"text": "The output of the fit method is the loss and accuracy at every epoch. We then plot it using our custom function, and see that the loss goes down to almost 0 over time, and the accuracy goes up to almost 1. Great! We have successfully trained our first neural network model with Keras. I know this was a long explanation, but I wanted to explain what we’re doing in detail the first time. Once you understand what’s going on and practice a couple of times, all this becomes second nature."
},
{
"code": null,
"e": 17204,
"s": 16775,
"text": "Below is a plot of the decision boundary. The various shades of blue and red represent the probability of a hypothetical point in that area belonging to class 1 or 0. The top left area is classified as class 1, with the color blue. The bottom right area is classified as class 0, colored as red. And there is a transition around the decision boundary. This is a cool way to visualize the decision boundary the model is learning."
},
{
"code": null,
"e": 17382,
"s": 17204,
"text": "The classification report shows the precision and recall of our model. We get close to 100% accuracy. The value shown in the report should be 0.997 but it got rounded up to 1.0."
},
{
"code": null,
"e": 17842,
"s": 17382,
"text": "The confusion matrix shows us how many classes were correctly classified vs misclassified. The numbers on the diagonal axis represent the number of correctly classified points, the rest are the misclassified ones. This particular matrix is not very interesting because the model only misclassifies 3 points. We can see one of the misclassified points at the top right part of the confusion matrix, the true value is class 0 but the predicted value is class 1."
},
{
"code": null,
"e": 18194,
"s": 17842,
"text": "The previous dataset was linearly separable, so it was trivial for our logistic regression model to separate the classes. Here is a more complex dataset which isn’t linearly separable. The simple logistic regression model won’t be able to clearly distinguish between the classes. We’re using the make_moons method of scikit-learn to generate the data."
},
{
"code": null,
"e": 18320,
"s": 18194,
"text": "Let’s build another logistic regression model with the same parameters as we did before. On this dataset we get 86% accuracy."
},
{
"code": null,
"e": 18609,
"s": 18320,
"text": "The current decision boundary doesn’t look as clean as the one before. The model tried to separate out the classes from the middle, but there are a lot of misclassified points. We need a more complex classifier with a non-linear decision boundary, and we will see an example of that soon."
},
{
"code": null,
"e": 18866,
"s": 18609,
"text": "Precision of the model is 86%. It looks good on paper but we should easily be able to get 100% with a more complex model. You can imagine a curved decision boundary that will separate out the classes, and a complex model should be able to approximate that."
},
{
"code": null,
"e": 18935,
"s": 18866,
"text": "The classification report and the confusion matrix looks as follows."
},
{
"code": null,
"e": 19059,
"s": 18935,
"text": "Let’s look at one final example where the liner model will fail. This time using the make_circles function in scikit-learn."
},
{
"code": null,
"e": 19100,
"s": 19059,
"text": "Building the model with same parameters."
},
{
"code": null,
"e": 19212,
"s": 19100,
"text": "The decision boundary again passes from the middle of the data, but now we have much more misclassified points."
},
{
"code": null,
"e": 19369,
"s": 19212,
"text": "The accuracy is around 50%, shown below. No matter where the model draws the line, it will misclassify half of the points, due to the nature of the dataset."
},
{
"code": null,
"e": 19916,
"s": 19369,
"text": "The confusion matrix we see here is an example one belonging to a poor classifier. Ideally we prefer confusion matrices to look like the ones we saw above. High numbers along the diagonals meaning that the classifier was right, and low numbers everywhere else where the classifier was wrong. In our visualization, the color blue represents large numbers and yellow represents the smaller ones. So we would prefer to see blue on the diagonals and yellow everywhere else. Blue color everywhere is a bad sign meaning that our classifier is confused."
},
{
"code": null,
"e": 20076,
"s": 19916,
"text": "The most naive method which always predicts 1 no matter what the input is would get a 50% accuracy. Our model also got 50% accuracy, so it’s not useful at all."
},
{
"code": null,
"e": 20359,
"s": 20076,
"text": "Now we will train a deep Artificial Neural Networks (ANN) to better classify the datasets which the logistic regression model struggled, Moons and Circles. We will also classify an even harder dataset of Sine Wave to demonstrate that ANN can form really complex decision boundaries."
},
{
"code": null,
"e": 20452,
"s": 20359,
"text": "While building Keras models for logistic regression above, we performed the following steps:"
},
{
"code": null,
"e": 20487,
"s": 20452,
"text": "Step 1: Define a Sequential model."
},
{
"code": null,
"e": 20582,
"s": 20487,
"text": "Step 2: Add a Dense layer with sigmoid activation function. This was the only layer we needed."
},
{
"code": null,
"e": 20645,
"s": 20582,
"text": "Step 3: Compile the model with an optimizer and loss function."
},
{
"code": null,
"e": 20683,
"s": 20645,
"text": "Step 4: Fit the model to the dataset."
},
{
"code": null,
"e": 20853,
"s": 20683,
"text": "Step 5: Analyze the results: plotting loss/accuracy curves, plotting the decision boundary, looking at the classification report, and understanding the confusion matrix."
},
{
"code": null,
"e": 21305,
"s": 20853,
"text": "While building a deep neural network, we only need to change step 2 such that, we will add several Dense layers one after another. The output of one layer becomes the input of the next. Keras again does most of the heavy lifting by initializing the weights and biases, and connecting the output of one layer to the input of the next. We only need to specify how many nodes we want in a given layer, and the activation function. It’s as simple as that."
},
{
"code": null,
"e": 21675,
"s": 21305,
"text": "We first add a layer with 4 nodes and tanh activation function. Tanh is a commonly used activation function, and we’ll learn more about it in another tutorial. We then add another layer with 2 nodes again using tanh activation. We finally add the last layer with 1 node and sigmoid activation. This is the final layer that we also used in the logistic regression model."
},
{
"code": null,
"e": 21798,
"s": 21675,
"text": "This is not a very deep ANN, it only has 3 layers: 2 hidden layers, and the output layer. But notice a couple of patterns:"
},
{
"code": null,
"e": 21910,
"s": 21798,
"text": "Output layer still uses the sigmoid activation function since we’re working on a binary classification problem."
},
{
"code": null,
"e": 22305,
"s": 21910,
"text": "Hidden layers use the tanh activation function. If we added more hidden layers, they would also use tanh activation. We have a couple of options for activation functions: sigmoid, tanh, relu, and variants of relu. In another article we’ll explore the pros and cons of each one. We will also demonstrate why using sigmoid activation in hidden layers is a bad idea. For now it’s safe to use tanh."
},
{
"code": null,
"e": 22462,
"s": 22305,
"text": "We have fewer number of nodes in each subsequent layer. It’s common to have less nodes as we stack layers on top of one another, sort of a triangular shape."
},
{
"code": null,
"e": 22586,
"s": 22462,
"text": "We didn’t build a very deep ANN here because it wasn’t necessary. We already achieve 100% accuracy with this configuration."
},
{
"code": null,
"e": 22666,
"s": 22586,
"text": "The ANN is able to come up with a perfect separator to distinguish the classes."
},
{
"code": null,
"e": 22705,
"s": 22666,
"text": "100% precision, nothing misclassified."
},
{
"code": null,
"e": 22931,
"s": 22705,
"text": "Now let’s look at the Circles dataset, where the LR model achieved only 50% accuracy. The model is the same as above, we only change the input to the fit function using the current dataset. And we again achieve 100% accuracy."
},
{
"code": null,
"e": 23073,
"s": 22931,
"text": "Similarly the decision boundary looks just like the one we would draw by hand ourselves. The ANN was able to figure out an optimal separator."
},
{
"code": null,
"e": 23111,
"s": 23073,
"text": "Just like above we get 100% accuracy."
},
{
"code": null,
"e": 23445,
"s": 23111,
"text": "Let’s try to classify one final toy dataset. In the previous sections, the classes were separable by one continuous decision boundary. The boundary had a complex shape, it wasn’t linear, but still one continuous decision boundary was enough. ANN can draw arbitrary number of complex decision boundaries, and we will demonstrate that."
},
{
"code": null,
"e": 23711,
"s": 23445,
"text": "Let’s create a sinusoidal dataset looking like the sine function, every up and down belonging to an alternating class. As we can see in the figure, a single decision boundary won’t be able to separate out the classes. We will need a series of non-linear separators."
},
{
"code": null,
"e": 24049,
"s": 23711,
"text": "Now we need a more complex model for accurate classification. So we have 3 hidden layers, and an output layer. The number of nodes per layer has also increased to improve the learning capacity of the model. Choosing the right number of hidden layers and nodes per layer is more of an art than science, usually decided by trial and error."
},
{
"code": null,
"e": 24120,
"s": 24049,
"text": "The ANN was able to model a pretty complex set of decision boundaries."
},
{
"code": null,
"e": 24201,
"s": 24120,
"text": "Precision is 99%, we only have 14 misclassified points out of 2400. Pretty good."
},
{
"code": null,
"e": 24468,
"s": 24201,
"text": "In the previous sections we worked on binary classification. Now we will take a look at a multi-class classification problem, where the number of classes is more than 2. We will pick 3 classes for demonstration, but our approach generalizes to any number of classes."
},
{
"code": null,
"e": 24581,
"s": 24468,
"text": "Here’s how our dataset looks like, spiral data with 3 classes, using the make_multiclass method in scikit-learn."
},
{
"code": null,
"e": 24851,
"s": 24581,
"text": "As we saw above, Logistic Regression (LR) is a classification method for 2 classes. It works with binary labels 0/1. Softmax Regression (SR) is a generalization of LR where we can have more than 2 classes. In our current dataset we have 3 classes, represented as 0/1/2."
},
{
"code": null,
"e": 24965,
"s": 24851,
"text": "Building the model for SR is very similar to LR, for reference here’s how we built our Logistic Regression model."
},
{
"code": null,
"e": 25028,
"s": 24965,
"text": "And here’s how how we will build the Softmax Regression model."
},
{
"code": null,
"e": 25094,
"s": 25028,
"text": "There are a couple of differences, let’s go over them one by one:"
},
{
"code": null,
"e": 25773,
"s": 25094,
"text": "Number of nodes in the dense layer: LR uses 1 node, where SR has 3 nodes. Since we have 3 classes it makes sense for SR to be using 3 nodes. Then the question is, why does LR uses only 1 node, it has 2 classes so it appears like we should have used 2 nodes instead. The answer is, because we can achieve the same result with using only 1 node. As we saw above, LR models the probability of an example belonging to class one: P(class=1). And we can calculate class 0 probability by: 1−P(class=1). But when we have more than 2 classes, we need individual nodes for each class. Because knowing the probability of one class doesn’t let us infer the probability of the other classes."
},
{
"code": null,
"e": 26381,
"s": 25773,
"text": "Activation function: LR used sigmoid activation function, SR uses softmax. Softmax scales the values of the output nodes such that they represent probabilities and sum up to 1. So in our case P(class=0)+P(class=1)+P(class=2)=1. It doesn’t do it in a naive way by dividing individual probabilities by the sum though, it uses the exponential function. So higher values get emphasized more and lower values get squashed more. We will talk in detail what softmax does in another tutorial. For now you can simply think of it as a normalization function which lets us interpret the output values as probabilities."
},
{
"code": null,
"e": 26779,
"s": 26381,
"text": "Loss function: In a binary classification problem like LR, the loss function is binary_crossentropy. In the multiclass case, the loss function is categorical_crossentropy. Categorical crossentropy is the generalization of binary crossentropy to more than 2 classes. Going into the theory behind loss functions is beyond the scope of this tutorial. But for now only knowing this property is enough."
},
{
"code": null,
"e": 27090,
"s": 26779,
"text": "Fit function: LR used the vector y directly in the fit function, which has just one column with 0/1 values. When we’re doing SR the labels need to be in one-hot representation. In our case y_cat is a matrix with 3 columns, where all the values are 0 except for the one that represents our class, and that is 1."
},
{
"code": null,
"e": 27312,
"s": 27090,
"text": "It took some time to talk about all the differences between LR and SR, and it looks like there’s a lot to digest. But again after some practice this will become a habit, and you won’t even need to think about any of this."
},
{
"code": null,
"e": 27591,
"s": 27312,
"text": "After all this theory let’s take a step back and remember that LR is a linear classifier. SR is also a linear classifier, but for multiple classes. So the “power” of the model hasn’t changed, it’s still a linear model. We just generalized LR to apply it to a multiclass problem."
},
{
"code": null,
"e": 27874,
"s": 27591,
"text": "Training the model gives us an accuracy of around 50%. The most naive method which always predicts class 1 no matter what the input is would have an accuracy of 33%. The SR model is not much of an improvement over it. Which is expected because the dataset is not linearly separable."
},
{
"code": null,
"e": 28042,
"s": 27874,
"text": "Looking at the decision boundary confirms that we still have a linear classifier. The lines look jagged due to floating point rounding but in reality they’re straight."
},
{
"code": null,
"e": 28197,
"s": 28042,
"text": "Here’s the precision and recall corresponding to the 3 classes. And the confusion matrix is all over the place. Clearly this is not an optimal classifier."
},
{
"code": null,
"e": 28446,
"s": 28197,
"text": "Now let’s build a deep ANN for multiclass classification. Remember that the changes going from LR to ANN was minimal. We only needed to add more Dense layers. We will do the same again. Adding a couple of Dense layers with tanh activation function."
},
{
"code": null,
"e": 28851,
"s": 28446,
"text": "Note that the output layer still has 3 nodes, and uses the softmax activation. The loss function also didn’t change, still categorical_crossentropy. These won’t change going from a linear model to a deep ANN, since the problem definition hasn’t changed. We’re still working on multiclass classification. But now using a more powerful model, and that power comes from adding more layers to our neural net."
},
{
"code": null,
"e": 28903,
"s": 28851,
"text": "We achieve 99% accuracy in just a couple of epochs."
},
{
"code": null,
"e": 28940,
"s": 28903,
"text": "The decision boundary is non-linear."
},
{
"code": null,
"e": 29016,
"s": 28940,
"text": "We got almost 100% accuracy. We totally misclassified 5 points out of 1500."
},
{
"code": null,
"e": 29260,
"s": 29016,
"text": "Thanks for spending time reading this article, I know this was a rather lengthy tutorial on Artificial Neural Networks and Keras. I wanted to be as detailed as possible, while still keeping the article length manageable. I hope you enjoyed it."
},
{
"code": null,
"e": 29622,
"s": 29260,
"text": "There was a common theme in this article such that we first introduced the task, we then approached it using a simple method and observed the limitations. Afterwards we used a more complex deep model to improve on it and got much better results. I think the ordering is important. No complex method becomes successful unless it has evolved from a simpler model."
}
]
|
MATLAB - Appending Vectors | MATLAB allows you to append vectors together to create new vectors.
If you have two row vectors r1 and r2 with n and m number of elements, to create a row vector r of n plus m elements, by appending these vectors, you write −
r = [r1,r2]
You can also create a matrix r by appending these two vectors, the vector r2, will be the second row of the matrix −
r = [r1;r2]
However, to do this, both the vectors should have same number of elements.
Similarly, you can append two column vectors c1 and c2 with n and m number of elements. To create a column vector c of n plus m elements, by appending these vectors, you write −
c = [c1; c2]
You can also create a matrix c by appending these two vectors; the vector c2 will be the second column of the matrix −
c = [c1, c2]
However, to do this, both the vectors should have same number of elements.
Create a script file with the following code −
r1 = [ 1 2 3 4 ];
r2 = [5 6 7 8 ];
r = [r1,r2]
rMat = [r1;r2]
c1 = [ 1; 2; 3; 4 ];
c2 = [5; 6; 7; 8 ];
c = [c1; c2]
cMat = [c1,c2]
When you run the file, it displays the following result −
r =
Columns 1 through 7:
1 2 3 4 5 6 7
Column 8:
8
rMat =
1 2 3 4
5 6 7 8
c =
1
2
3
4
5
6
7
8
cMat =
1 5
2 6
3 7
4 8
30 Lectures
4 hours
Nouman Azam
127 Lectures
12 hours
Nouman Azam
17 Lectures
3 hours
Sanjeev
37 Lectures
5 hours
TELCOMA Global
22 Lectures
4 hours
TELCOMA Global
18 Lectures
3 hours
Phinite Academy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2209,
"s": 2141,
"text": "MATLAB allows you to append vectors together to create new vectors."
},
{
"code": null,
"e": 2367,
"s": 2209,
"text": "If you have two row vectors r1 and r2 with n and m number of elements, to create a row vector r of n plus m elements, by appending these vectors, you write −"
},
{
"code": null,
"e": 2380,
"s": 2367,
"text": "r = [r1,r2]\n"
},
{
"code": null,
"e": 2497,
"s": 2380,
"text": "You can also create a matrix r by appending these two vectors, the vector r2, will be the second row of the matrix −"
},
{
"code": null,
"e": 2510,
"s": 2497,
"text": "r = [r1;r2]\n"
},
{
"code": null,
"e": 2585,
"s": 2510,
"text": "However, to do this, both the vectors should have same number of elements."
},
{
"code": null,
"e": 2763,
"s": 2585,
"text": "Similarly, you can append two column vectors c1 and c2 with n and m number of elements. To create a column vector c of n plus m elements, by appending these vectors, you write −"
},
{
"code": null,
"e": 2777,
"s": 2763,
"text": "c = [c1; c2]\n"
},
{
"code": null,
"e": 2896,
"s": 2777,
"text": "You can also create a matrix c by appending these two vectors; the vector c2 will be the second column of the matrix −"
},
{
"code": null,
"e": 2910,
"s": 2896,
"text": "c = [c1, c2]\n"
},
{
"code": null,
"e": 2985,
"s": 2910,
"text": "However, to do this, both the vectors should have same number of elements."
},
{
"code": null,
"e": 3032,
"s": 2985,
"text": "Create a script file with the following code −"
},
{
"code": null,
"e": 3165,
"s": 3032,
"text": "r1 = [ 1 2 3 4 ];\nr2 = [5 6 7 8 ];\nr = [r1,r2]\nrMat = [r1;r2]\n \nc1 = [ 1; 2; 3; 4 ];\nc2 = [5; 6; 7; 8 ];\nc = [c1; c2]\ncMat = [c1,c2]"
},
{
"code": null,
"e": 3223,
"s": 3165,
"text": "When you run the file, it displays the following result −"
},
{
"code": null,
"e": 3640,
"s": 3223,
"text": "r =\n\nColumns 1 through 7:\n\n 1 2 3 4 5 6 7\n\nColumn 8:\n\n 8\n\nrMat =\n\n 1 2 3 4\n 5 6 7 8\n\nc =\n\n 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n\ncMat =\n\n 1 5\n 2 6\n 3 7\n 4 8\n\n"
},
{
"code": null,
"e": 3673,
"s": 3640,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3686,
"s": 3673,
"text": " Nouman Azam"
},
{
"code": null,
"e": 3721,
"s": 3686,
"text": "\n 127 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 3734,
"s": 3721,
"text": " Nouman Azam"
},
{
"code": null,
"e": 3767,
"s": 3734,
"text": "\n 17 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3776,
"s": 3767,
"text": " Sanjeev"
},
{
"code": null,
"e": 3809,
"s": 3776,
"text": "\n 37 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3825,
"s": 3809,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3858,
"s": 3825,
"text": "\n 22 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3874,
"s": 3858,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3907,
"s": 3874,
"text": "\n 18 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3924,
"s": 3907,
"text": " Phinite Academy"
},
{
"code": null,
"e": 3931,
"s": 3924,
"text": " Print"
},
{
"code": null,
"e": 3942,
"s": 3931,
"text": " Add Notes"
}
]
|
Generics in Java | 09 Feb, 2022
Generics means parameterized types. The idea is to allow type (Integer, String, ... etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types. An entity such as class, interface, or method that operates on a parameterized type is a generic entity.
The Object is the superclass of all other classes, and Object reference can refer to any object. These features lack type safety. Generics add that type of safety feature. We will discuss that type of safety feature in later examples.
Generics in Java are similar to templates in C++. For example, classes like HashSet, ArrayList, HashMap, etc., use generics very well. There are some fundamental differences between the two approaches to generic types.
Generic Method: Generic Java method takes a parameter and returns some value after performing a task. It is exactly like a normal function, however, a generic method has type parameters that are cited by actual type. This allows the generic method to be used in a more general way. The compiler takes care of the type of safety which enables programmers to code easily since they do not have to perform long, individual type castings.
Generic Classes: A generic class is implemented exactly like a non-generic class. The only difference is that it contains a type parameter section. There can be more than one type of parameter, separated by a comma. The classes, which accept one or more parameters, are known as parameterized classes or parameterized types.
Like C++, we use <> to specify parameter types in generic class creation. To create objects of a generic class, we use the following syntax.
// To create an instance of generic class
BaseType <Type> obj = new BaseType <Type>()
Note: In Parameter type we can not use primitives like ‘int’,’char’ or ‘double’.
Java
// Java program to show working of user defined// Generic classes // We use < > to specify Parameter typeclass Test<T> { // An object of type T is declared T obj; Test(T obj) { this.obj = obj; } // constructor public T getObject() { return this.obj; }} // Driver class to test aboveclass Main { public static void main(String[] args) { // instance of Integer type Test<Integer> iObj = new Test<Integer>(15); System.out.println(iObj.getObject()); // instance of String type Test<String> sObj = new Test<String>("GeeksForGeeks"); System.out.println(sObj.getObject()); }}
15
GeeksForGeeks
We can also pass multiple Type parameters in Generic classes.
Java
// Java program to show multiple// type parameters in Java Generics // We use < > to specify Parameter typeclass Test<T, U>{ T obj1; // An object of type T U obj2; // An object of type U // constructor Test(T obj1, U obj2) { this.obj1 = obj1; this.obj2 = obj2; } // To print objects of T and U public void print() { System.out.println(obj1); System.out.println(obj2); }} // Driver class to test aboveclass Main{ public static void main (String[] args) { Test <String, Integer> obj = new Test<String, Integer>("GfG", 15); obj.print(); }}
GfG
15
We can also write generic functions that can be called with different types of arguments based on the type of arguments passed to the generic method. The compiler handles each method.
Java
// Java program to show working of user defined// Generic functions class Test { // A Generic method example static <T> void genericDisplay(T element) { System.out.println(element.getClass().getName() + " = " + element); } // Driver method public static void main(String[] args) { // Calling generic method with Integer argument genericDisplay(11); // Calling generic method with String argument genericDisplay("GeeksForGeeks"); // Calling generic method with double argument genericDisplay(1.0); }}
java.lang.Integer = 11
java.lang.String = GeeksForGeeks
java.lang.Double = 1.0
When we declare an instance of a generic type, the type argument passed to the type parameter must be a reference type. We cannot use primitive data types like int, char.
Test<int> obj = new Test<int>(20);
The above line results in a compile-time error that can be resolved using type wrappers to encapsulate a primitive type.
But primitive type arrays can be passed to the type parameter because arrays are reference types.
ArrayList<int[]> a = new ArrayList<>();
Consider the following Java code.
Java
// Java program to show working// of user-defined Generic classes // We use < > to specify Parameter typeclass Test<T> { // An object of type T is declared T obj; Test(T obj) { this.obj = obj; } // constructor public T getObject() { return this.obj; }} // Driver class to test aboveclass Main { public static void main(String[] args) { // instance of Integer type Test<Integer> iObj = new Test<Integer>(15); System.out.println(iObj.getObject()); // instance of String type Test<String> sObj = new Test<String>("GeeksForGeeks"); System.out.println(sObj.getObject()); iObj = sObj; // This results an error }}
Output:
error:
incompatible types:
Test cannot be converted to Test
Even though iObj and sObj are of type Test, they are the references to different types because their type parameters differ. Generics add type safety through this and prevent errors.
The type parameters naming conventions are important to learn generics thoroughly. The common type parameters are as follows:
T – Type
E – Element
K – Key
N – Number
V – Value
Programs that use Generics has got many benefits over non-generic code.
1. Code Reuse: We can write a method/class/interface once and use it for any type we want.
2. Type Safety: Generics make errors to appear compile time than at run time (It’s always better to know problems in your code at compile time rather than making your code fail at run time). Suppose you want to create an ArrayList that store name of students, and if by mistake the programmer adds an integer object instead of a string, the compiler allows it. But, when we retrieve this data from ArrayList, it causes problems at runtime.
Java
// Java program to demonstrate that NOT using// generics can cause run time exceptions import java.util.*; class Test{ public static void main(String[] args) { // Creatinga an ArrayList without any type specified ArrayList al = new ArrayList(); al.add("Sachin"); al.add("Rahul"); al.add(10); // Compiler allows this String s1 = (String)al.get(0); String s2 = (String)al.get(1); // Causes Runtime Exception String s3 = (String)al.get(2); }}
Output :
Exception in thread "main" java.lang.ClassCastException:
java.lang.Integer cannot be cast to java.lang.String
at Test.main(Test.java:19)
When defining ArrayList, we can specify that this list can take only String objects.
Java
// Using Java Generics converts run time exceptions into // compile time exception.import java.util.*; class Test{ public static void main(String[] args) { // Creating a an ArrayList with String specified ArrayList <String> al = new ArrayList<String> (); al.add("Sachin"); al.add("Rahul"); // Now Compiler doesn't allow this al.add(10); String s1 = (String)al.get(0); String s2 = (String)al.get(1); String s3 = (String)al.get(2); }}
Output:
15: error: no suitable method found for add(int)
al.add(10);
^
3. Individual Type Casting is not needed: If we do not use generics, then, in the above example, every time we retrieve data from ArrayList, we have to typecast it. Typecasting at every retrieval operation is a big headache. If we already know that our list only holds string data, we need not typecast it every time.
Java
// We don't need to typecast individual members of ArrayList import java.util.*; class Test { public static void main(String[] args) { // Creating a an ArrayList with String specified ArrayList<String> al = new ArrayList<String>(); al.add("Sachin"); al.add("Rahul"); // Typecasting is not needed String s1 = al.get(0); String s2 = al.get(1); }}
4. Generics Promotes Code Reusability: With the help of generics in Java, we can write code that will work with different types of data. For example,
public <T> void genericsMethod (T data) {...}
Here, we have created a generics method. This same method can be used to perform operations on integer data, string data, and so on.
5. Implementing Generic Algorithms: By using generics, we can implement algorithms that work on different types of objects, and at the same, they are type-safe too.
This article is contributed by Dharmesh Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
avsadityavardhan
bestswaraj
nishkarshgandhi
Java-Generics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Feb, 2022"
},
{
"code": null,
"e": 412,
"s": 52,
"text": "Generics means parameterized types. The idea is to allow type (Integer, String, ... etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types. An entity such as class, interface, or method that operates on a parameterized type is a generic entity."
},
{
"code": null,
"e": 647,
"s": 412,
"text": "The Object is the superclass of all other classes, and Object reference can refer to any object. These features lack type safety. Generics add that type of safety feature. We will discuss that type of safety feature in later examples."
},
{
"code": null,
"e": 867,
"s": 647,
"text": "Generics in Java are similar to templates in C++. For example, classes like HashSet, ArrayList, HashMap, etc., use generics very well. There are some fundamental differences between the two approaches to generic types. "
},
{
"code": null,
"e": 1302,
"s": 867,
"text": "Generic Method: Generic Java method takes a parameter and returns some value after performing a task. It is exactly like a normal function, however, a generic method has type parameters that are cited by actual type. This allows the generic method to be used in a more general way. The compiler takes care of the type of safety which enables programmers to code easily since they do not have to perform long, individual type castings."
},
{
"code": null,
"e": 1628,
"s": 1302,
"text": "Generic Classes: A generic class is implemented exactly like a non-generic class. The only difference is that it contains a type parameter section. There can be more than one type of parameter, separated by a comma. The classes, which accept one or more parameters, are known as parameterized classes or parameterized types."
},
{
"code": null,
"e": 1770,
"s": 1628,
"text": "Like C++, we use <> to specify parameter types in generic class creation. To create objects of a generic class, we use the following syntax. "
},
{
"code": null,
"e": 1857,
"s": 1770,
"text": "// To create an instance of generic class \nBaseType <Type> obj = new BaseType <Type>()"
},
{
"code": null,
"e": 1938,
"s": 1857,
"text": "Note: In Parameter type we can not use primitives like ‘int’,’char’ or ‘double’."
},
{
"code": null,
"e": 1943,
"s": 1938,
"text": "Java"
},
{
"code": "// Java program to show working of user defined// Generic classes // We use < > to specify Parameter typeclass Test<T> { // An object of type T is declared T obj; Test(T obj) { this.obj = obj; } // constructor public T getObject() { return this.obj; }} // Driver class to test aboveclass Main { public static void main(String[] args) { // instance of Integer type Test<Integer> iObj = new Test<Integer>(15); System.out.println(iObj.getObject()); // instance of String type Test<String> sObj = new Test<String>(\"GeeksForGeeks\"); System.out.println(sObj.getObject()); }}",
"e": 2590,
"s": 1943,
"text": null
},
{
"code": null,
"e": 2607,
"s": 2590,
"text": "15\nGeeksForGeeks"
},
{
"code": null,
"e": 2670,
"s": 2607,
"text": "We can also pass multiple Type parameters in Generic classes. "
},
{
"code": null,
"e": 2675,
"s": 2670,
"text": "Java"
},
{
"code": "// Java program to show multiple// type parameters in Java Generics // We use < > to specify Parameter typeclass Test<T, U>{ T obj1; // An object of type T U obj2; // An object of type U // constructor Test(T obj1, U obj2) { this.obj1 = obj1; this.obj2 = obj2; } // To print objects of T and U public void print() { System.out.println(obj1); System.out.println(obj2); }} // Driver class to test aboveclass Main{ public static void main (String[] args) { Test <String, Integer> obj = new Test<String, Integer>(\"GfG\", 15); obj.print(); }}",
"e": 3314,
"s": 2675,
"text": null
},
{
"code": null,
"e": 3321,
"s": 3314,
"text": "GfG\n15"
},
{
"code": null,
"e": 3505,
"s": 3321,
"text": "We can also write generic functions that can be called with different types of arguments based on the type of arguments passed to the generic method. The compiler handles each method."
},
{
"code": null,
"e": 3510,
"s": 3505,
"text": "Java"
},
{
"code": "// Java program to show working of user defined// Generic functions class Test { // A Generic method example static <T> void genericDisplay(T element) { System.out.println(element.getClass().getName() + \" = \" + element); } // Driver method public static void main(String[] args) { // Calling generic method with Integer argument genericDisplay(11); // Calling generic method with String argument genericDisplay(\"GeeksForGeeks\"); // Calling generic method with double argument genericDisplay(1.0); }}",
"e": 4116,
"s": 3510,
"text": null
},
{
"code": null,
"e": 4195,
"s": 4116,
"text": "java.lang.Integer = 11\njava.lang.String = GeeksForGeeks\njava.lang.Double = 1.0"
},
{
"code": null,
"e": 4366,
"s": 4195,
"text": "When we declare an instance of a generic type, the type argument passed to the type parameter must be a reference type. We cannot use primitive data types like int, char."
},
{
"code": null,
"e": 4402,
"s": 4366,
"text": "Test<int> obj = new Test<int>(20); "
},
{
"code": null,
"e": 4524,
"s": 4402,
"text": "The above line results in a compile-time error that can be resolved using type wrappers to encapsulate a primitive type. "
},
{
"code": null,
"e": 4622,
"s": 4524,
"text": "But primitive type arrays can be passed to the type parameter because arrays are reference types."
},
{
"code": null,
"e": 4662,
"s": 4622,
"text": "ArrayList<int[]> a = new ArrayList<>();"
},
{
"code": null,
"e": 4696,
"s": 4662,
"text": "Consider the following Java code."
},
{
"code": null,
"e": 4701,
"s": 4696,
"text": "Java"
},
{
"code": "// Java program to show working// of user-defined Generic classes // We use < > to specify Parameter typeclass Test<T> { // An object of type T is declared T obj; Test(T obj) { this.obj = obj; } // constructor public T getObject() { return this.obj; }} // Driver class to test aboveclass Main { public static void main(String[] args) { // instance of Integer type Test<Integer> iObj = new Test<Integer>(15); System.out.println(iObj.getObject()); // instance of String type Test<String> sObj = new Test<String>(\"GeeksForGeeks\"); System.out.println(sObj.getObject()); iObj = sObj; // This results an error }}",
"e": 5393,
"s": 4701,
"text": null
},
{
"code": null,
"e": 5402,
"s": 5393,
"text": "Output: "
},
{
"code": null,
"e": 5465,
"s": 5402,
"text": "error:\n incompatible types:\n Test cannot be converted to Test "
},
{
"code": null,
"e": 5648,
"s": 5465,
"text": "Even though iObj and sObj are of type Test, they are the references to different types because their type parameters differ. Generics add type safety through this and prevent errors."
},
{
"code": null,
"e": 5774,
"s": 5648,
"text": "The type parameters naming conventions are important to learn generics thoroughly. The common type parameters are as follows:"
},
{
"code": null,
"e": 5783,
"s": 5774,
"text": "T – Type"
},
{
"code": null,
"e": 5795,
"s": 5783,
"text": "E – Element"
},
{
"code": null,
"e": 5803,
"s": 5795,
"text": "K – Key"
},
{
"code": null,
"e": 5814,
"s": 5803,
"text": "N – Number"
},
{
"code": null,
"e": 5824,
"s": 5814,
"text": "V – Value"
},
{
"code": null,
"e": 5897,
"s": 5824,
"text": "Programs that use Generics has got many benefits over non-generic code. "
},
{
"code": null,
"e": 5988,
"s": 5897,
"text": "1. Code Reuse: We can write a method/class/interface once and use it for any type we want."
},
{
"code": null,
"e": 6428,
"s": 5988,
"text": "2. Type Safety: Generics make errors to appear compile time than at run time (It’s always better to know problems in your code at compile time rather than making your code fail at run time). Suppose you want to create an ArrayList that store name of students, and if by mistake the programmer adds an integer object instead of a string, the compiler allows it. But, when we retrieve this data from ArrayList, it causes problems at runtime."
},
{
"code": null,
"e": 6433,
"s": 6428,
"text": "Java"
},
{
"code": "// Java program to demonstrate that NOT using// generics can cause run time exceptions import java.util.*; class Test{ public static void main(String[] args) { // Creatinga an ArrayList without any type specified ArrayList al = new ArrayList(); al.add(\"Sachin\"); al.add(\"Rahul\"); al.add(10); // Compiler allows this String s1 = (String)al.get(0); String s2 = (String)al.get(1); // Causes Runtime Exception String s3 = (String)al.get(2); }}",
"e": 6953,
"s": 6433,
"text": null
},
{
"code": null,
"e": 6962,
"s": 6953,
"text": "Output :"
},
{
"code": null,
"e": 7107,
"s": 6962,
"text": "Exception in thread \"main\" java.lang.ClassCastException: \n java.lang.Integer cannot be cast to java.lang.String\n at Test.main(Test.java:19)"
},
{
"code": null,
"e": 7192,
"s": 7107,
"text": "When defining ArrayList, we can specify that this list can take only String objects."
},
{
"code": null,
"e": 7197,
"s": 7192,
"text": "Java"
},
{
"code": "// Using Java Generics converts run time exceptions into // compile time exception.import java.util.*; class Test{ public static void main(String[] args) { // Creating a an ArrayList with String specified ArrayList <String> al = new ArrayList<String> (); al.add(\"Sachin\"); al.add(\"Rahul\"); // Now Compiler doesn't allow this al.add(10); String s1 = (String)al.get(0); String s2 = (String)al.get(1); String s3 = (String)al.get(2); }}",
"e": 7710,
"s": 7197,
"text": null
},
{
"code": null,
"e": 7719,
"s": 7710,
"text": "Output: "
},
{
"code": null,
"e": 7801,
"s": 7719,
"text": "15: error: no suitable method found for add(int)\n al.add(10); \n ^"
},
{
"code": null,
"e": 8119,
"s": 7801,
"text": "3. Individual Type Casting is not needed: If we do not use generics, then, in the above example, every time we retrieve data from ArrayList, we have to typecast it. Typecasting at every retrieval operation is a big headache. If we already know that our list only holds string data, we need not typecast it every time."
},
{
"code": null,
"e": 8124,
"s": 8119,
"text": "Java"
},
{
"code": "// We don't need to typecast individual members of ArrayList import java.util.*; class Test { public static void main(String[] args) { // Creating a an ArrayList with String specified ArrayList<String> al = new ArrayList<String>(); al.add(\"Sachin\"); al.add(\"Rahul\"); // Typecasting is not needed String s1 = al.get(0); String s2 = al.get(1); }}",
"e": 8533,
"s": 8124,
"text": null
},
{
"code": null,
"e": 8683,
"s": 8533,
"text": "4. Generics Promotes Code Reusability: With the help of generics in Java, we can write code that will work with different types of data. For example,"
},
{
"code": null,
"e": 8729,
"s": 8683,
"text": "public <T> void genericsMethod (T data) {...}"
},
{
"code": null,
"e": 8862,
"s": 8729,
"text": "Here, we have created a generics method. This same method can be used to perform operations on integer data, string data, and so on."
},
{
"code": null,
"e": 9027,
"s": 8862,
"text": "5. Implementing Generic Algorithms: By using generics, we can implement algorithms that work on different types of objects, and at the same, they are type-safe too."
},
{
"code": null,
"e": 9421,
"s": 9027,
"text": "This article is contributed by Dharmesh Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 9438,
"s": 9421,
"text": "avsadityavardhan"
},
{
"code": null,
"e": 9449,
"s": 9438,
"text": "bestswaraj"
},
{
"code": null,
"e": 9465,
"s": 9449,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 9479,
"s": 9465,
"text": "Java-Generics"
},
{
"code": null,
"e": 9484,
"s": 9479,
"text": "Java"
},
{
"code": null,
"e": 9489,
"s": 9484,
"text": "Java"
}
]
|
How to disable scrolling temporarily using JavaScript? | 26 Jul, 2021
Scrolling can be disabled using JavaScript using 2 methods:
Method 1: Overriding the window.onscroll function
The window.onscroll event fires when the window has been scrolled. Overriding this function and setting it to a fixed position every time the scroll happens will effectively disable the scroll effect.
The current scroll position from the top is found by using the window.pageYOffset and the document.documentElement.scrollTop values. These 2 properties returns the current y scroll position. They are used together using the OR operator as one of them may return 0 on certain browsers.
Similarly, the current scroll position from the left is found by using the window.pageXOffset and the document.documentElement.scrollLeft values. These 2 properties returns the current x scroll position.
The window.scrollTo() method is then used with these 2 values to set the scroll position of the current page to that value.
To enable the scrolling back, window.onscroll is overridden with a blank function. This will enable the scrolling of the page again.
Syntax:
function disableScroll() { // Get the current page scroll position scrollTop = window.pageYOffset || document.documentElement.scrollTop; scrollLeft = window.pageXOffset || document.documentElement.scrollLeft, // if any scroll is attempted, set this to the previous value window.onscroll = function() { window.scrollTo(scrollLeft, scrollTop); };} function enableScroll() { window.onscroll = function() {};}
Example: Overriding the window.onscroll function
<!DOCTYPE html><html> <head> <title>How to disable scrolling temporarily using JavaScript?</title> <style> .scrollable-place { height: 1000px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>How to disable scrolling temporarily using JavaScript?</b> <p>Click on the buttons below to enable or disable scrolling.</p> <p class="scrollable-place"> <button onclick="disableScroll()">Disable Scrolling</button> <button onclick="enableScroll()">Enable Scrolling</button> </p> <script> function disableScroll() { // Get the current page scroll position scrollTop = window.pageYOffset || document.documentElement.scrollTop; scrollLeft = window.pageXOffset || document.documentElement.scrollLeft, // if any scroll is attempted, // set this to the previous value window.onscroll = function() { window.scrollTo(scrollLeft, scrollTop); }; } function enableScroll() { window.onscroll = function() {}; } </script></body> </html>
Output:
Method 2: Setting the height of the body to 100% and overflow to hidden
In this method, a new CSS class is created where the height is set to 100% and the scroll bar is disabled by setting the overflow property to hidden.
.stop-scrolling { height: 100%; overflow: hidden;}
Whenever scrolling has to be disabled, this class is added to the body using the document.body.classList.add(“classname”) method. This method adds the specified class name to the body element’s class list.
To enable the scrolling back, this class is removed from the body using the document.body.classList.remove(“classname”) method. This method removes the specified class name to the body element’s class list. This will enable the scrolling of the page again.
Syntax:
function disableScroll() { document.body.classList.add("stop-scrolling");} function enableScroll() { document.body.classList.remove("stop-scrolling");}
Example: Setting the height of the body to 100% and overflow to hidden
<!DOCTYPE html><html> <head> <title>How to disable scrolling temporarily using JavaScript?</title> <style> .scrollable-place { height: 1000px; } .stop-scrolling { height: 100%; overflow: hidden; } </style></head> <body> <h1 style="color: green">GeeksforGeeks</h1> <b>How to disable scrolling temporarily using JavaScript?</b> <p>Click on the buttons below to enable or disable scrolling.</p> <p class="scrollable-place"> <button onclick="disableScroll()">Disable Scrolling</button> <button onclick="enableScroll()">Enable Scrolling</button> </p> <script> function disableScroll() { document.body.classList.add("stop-scrolling"); } function enableScroll() { document.body.classList.remove("stop-scrolling"); } </script></body> </html>
Output:
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
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
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
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": "\n26 Jul, 2021"
},
{
"code": null,
"e": 88,
"s": 28,
"text": "Scrolling can be disabled using JavaScript using 2 methods:"
},
{
"code": null,
"e": 138,
"s": 88,
"text": "Method 1: Overriding the window.onscroll function"
},
{
"code": null,
"e": 339,
"s": 138,
"text": "The window.onscroll event fires when the window has been scrolled. Overriding this function and setting it to a fixed position every time the scroll happens will effectively disable the scroll effect."
},
{
"code": null,
"e": 624,
"s": 339,
"text": "The current scroll position from the top is found by using the window.pageYOffset and the document.documentElement.scrollTop values. These 2 properties returns the current y scroll position. They are used together using the OR operator as one of them may return 0 on certain browsers."
},
{
"code": null,
"e": 828,
"s": 624,
"text": "Similarly, the current scroll position from the left is found by using the window.pageXOffset and the document.documentElement.scrollLeft values. These 2 properties returns the current x scroll position."
},
{
"code": null,
"e": 952,
"s": 828,
"text": "The window.scrollTo() method is then used with these 2 values to set the scroll position of the current page to that value."
},
{
"code": null,
"e": 1085,
"s": 952,
"text": "To enable the scrolling back, window.onscroll is overridden with a blank function. This will enable the scrolling of the page again."
},
{
"code": null,
"e": 1093,
"s": 1085,
"text": "Syntax:"
},
{
"code": "function disableScroll() { // Get the current page scroll position scrollTop = window.pageYOffset || document.documentElement.scrollTop; scrollLeft = window.pageXOffset || document.documentElement.scrollLeft, // if any scroll is attempted, set this to the previous value window.onscroll = function() { window.scrollTo(scrollLeft, scrollTop); };} function enableScroll() { window.onscroll = function() {};}",
"e": 1546,
"s": 1093,
"text": null
},
{
"code": null,
"e": 1595,
"s": 1546,
"text": "Example: Overriding the window.onscroll function"
},
{
"code": "<!DOCTYPE html><html> <head> <title>How to disable scrolling temporarily using JavaScript?</title> <style> .scrollable-place { height: 1000px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>How to disable scrolling temporarily using JavaScript?</b> <p>Click on the buttons below to enable or disable scrolling.</p> <p class=\"scrollable-place\"> <button onclick=\"disableScroll()\">Disable Scrolling</button> <button onclick=\"enableScroll()\">Enable Scrolling</button> </p> <script> function disableScroll() { // Get the current page scroll position scrollTop = window.pageYOffset || document.documentElement.scrollTop; scrollLeft = window.pageXOffset || document.documentElement.scrollLeft, // if any scroll is attempted, // set this to the previous value window.onscroll = function() { window.scrollTo(scrollLeft, scrollTop); }; } function enableScroll() { window.onscroll = function() {}; } </script></body> </html>",
"e": 2814,
"s": 1595,
"text": null
},
{
"code": null,
"e": 2822,
"s": 2814,
"text": "Output:"
},
{
"code": null,
"e": 2894,
"s": 2822,
"text": "Method 2: Setting the height of the body to 100% and overflow to hidden"
},
{
"code": null,
"e": 3044,
"s": 2894,
"text": "In this method, a new CSS class is created where the height is set to 100% and the scroll bar is disabled by setting the overflow property to hidden."
},
{
"code": ".stop-scrolling { height: 100%; overflow: hidden;}",
"e": 3101,
"s": 3044,
"text": null
},
{
"code": null,
"e": 3307,
"s": 3101,
"text": "Whenever scrolling has to be disabled, this class is added to the body using the document.body.classList.add(“classname”) method. This method adds the specified class name to the body element’s class list."
},
{
"code": null,
"e": 3564,
"s": 3307,
"text": "To enable the scrolling back, this class is removed from the body using the document.body.classList.remove(“classname”) method. This method removes the specified class name to the body element’s class list. This will enable the scrolling of the page again."
},
{
"code": null,
"e": 3572,
"s": 3564,
"text": "Syntax:"
},
{
"code": "function disableScroll() { document.body.classList.add(\"stop-scrolling\");} function enableScroll() { document.body.classList.remove(\"stop-scrolling\");}",
"e": 3731,
"s": 3572,
"text": null
},
{
"code": null,
"e": 3802,
"s": 3731,
"text": "Example: Setting the height of the body to 100% and overflow to hidden"
},
{
"code": "<!DOCTYPE html><html> <head> <title>How to disable scrolling temporarily using JavaScript?</title> <style> .scrollable-place { height: 1000px; } .stop-scrolling { height: 100%; overflow: hidden; } </style></head> <body> <h1 style=\"color: green\">GeeksforGeeks</h1> <b>How to disable scrolling temporarily using JavaScript?</b> <p>Click on the buttons below to enable or disable scrolling.</p> <p class=\"scrollable-place\"> <button onclick=\"disableScroll()\">Disable Scrolling</button> <button onclick=\"enableScroll()\">Enable Scrolling</button> </p> <script> function disableScroll() { document.body.classList.add(\"stop-scrolling\"); } function enableScroll() { document.body.classList.remove(\"stop-scrolling\"); } </script></body> </html>",
"e": 4721,
"s": 3802,
"text": null
},
{
"code": null,
"e": 4729,
"s": 4721,
"text": "Output:"
},
{
"code": null,
"e": 4948,
"s": 4729,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 4964,
"s": 4948,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 4971,
"s": 4964,
"text": "Picked"
},
{
"code": null,
"e": 4982,
"s": 4971,
"text": "JavaScript"
},
{
"code": null,
"e": 4999,
"s": 4982,
"text": "Web Technologies"
},
{
"code": null,
"e": 5026,
"s": 4999,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 5124,
"s": 5026,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5185,
"s": 5124,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5257,
"s": 5185,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 5297,
"s": 5257,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 5338,
"s": 5297,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 5390,
"s": 5338,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 5423,
"s": 5390,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5485,
"s": 5423,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5546,
"s": 5485,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5596,
"s": 5546,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Express.js res.json() Function | 05 May, 2021
The res.json() function sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using the JSON.stringify() method.Syntax:
res.json( [body] )
Parameters: The body parameter is the body which is to be sent in the response.Return Value: It returns an Object.Installation of express module:
1. You can visit the link to Install express module. You can install this package by using this command.
npm install express
2. After installing the express module, you can check your express version in command prompt using the command.
npm version express
3. After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.
node index.js
Example 1: Filename: index.js
javascript
var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){ res.json({ user: 'geek' });}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Steps to run the program:
1. The project structure will look like this:
2. Make sure you have installed express module using the following command:
npm install express
3. Run index.js file using below command:
node index.js
Output:
Server listening on PORT 3000
4. Now open browser and go to http://localhost:3000/, now on your screen you will see the following output:
{"user":"geek"}
Example 2: Filename: index.js
javascript
var express = require('express');var app = express();var PORT = 3000; // With middlewareapp.use('/', function(req, res, next){ res.json({title: "GeeksforGeeks"}) next();}) app.get('/', function(req, res){ console.log("User Page") res.end();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Run index.js file using below command:
node index.js
Now open a browser and go to http://localhost:3000/, now on your screen you will see the following output:
{"title":"GeeksforGeeks"}
And you will see the following output on your console:
User Page
Reference: https://expressjs.com/en/4x/api.html#res.json
simmytarika5
Express.js
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": "\n05 May, 2021"
},
{
"code": null,
"e": 229,
"s": 28,
"text": "The res.json() function sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using the JSON.stringify() method.Syntax: "
},
{
"code": null,
"e": 248,
"s": 229,
"text": "res.json( [body] )"
},
{
"code": null,
"e": 396,
"s": 248,
"text": "Parameters: The body parameter is the body which is to be sent in the response.Return Value: It returns an Object.Installation of express module: "
},
{
"code": null,
"e": 503,
"s": 396,
"text": "1. You can visit the link to Install express module. You can install this package by using this command. "
},
{
"code": null,
"e": 523,
"s": 503,
"text": "npm install express"
},
{
"code": null,
"e": 637,
"s": 523,
"text": "2. After installing the express module, you can check your express version in command prompt using the command. "
},
{
"code": null,
"e": 657,
"s": 637,
"text": "npm version express"
},
{
"code": null,
"e": 797,
"s": 657,
"text": "3. After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. "
},
{
"code": null,
"e": 811,
"s": 797,
"text": "node index.js"
},
{
"code": null,
"e": 843,
"s": 811,
"text": "Example 1: Filename: index.js "
},
{
"code": null,
"e": 854,
"s": 843,
"text": "javascript"
},
{
"code": "var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){ res.json({ user: 'geek' });}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 1127,
"s": 854,
"text": null
},
{
"code": null,
"e": 1155,
"s": 1127,
"text": "Steps to run the program: "
},
{
"code": null,
"e": 1203,
"s": 1155,
"text": "1. The project structure will look like this: "
},
{
"code": null,
"e": 1281,
"s": 1203,
"text": "2. Make sure you have installed express module using the following command: "
},
{
"code": null,
"e": 1301,
"s": 1281,
"text": "npm install express"
},
{
"code": null,
"e": 1345,
"s": 1301,
"text": "3. Run index.js file using below command: "
},
{
"code": null,
"e": 1359,
"s": 1345,
"text": "node index.js"
},
{
"code": null,
"e": 1369,
"s": 1359,
"text": "Output: "
},
{
"code": null,
"e": 1399,
"s": 1369,
"text": "Server listening on PORT 3000"
},
{
"code": null,
"e": 1509,
"s": 1399,
"text": "4. Now open browser and go to http://localhost:3000/, now on your screen you will see the following output: "
},
{
"code": null,
"e": 1525,
"s": 1509,
"text": "{\"user\":\"geek\"}"
},
{
"code": null,
"e": 1559,
"s": 1527,
"text": "Example 2: Filename: index.js "
},
{
"code": null,
"e": 1570,
"s": 1559,
"text": "javascript"
},
{
"code": "var express = require('express');var app = express();var PORT = 3000; // With middlewareapp.use('/', function(req, res, next){ res.json({title: \"GeeksforGeeks\"}) next();}) app.get('/', function(req, res){ console.log(\"User Page\") res.end();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 1943,
"s": 1570,
"text": null
},
{
"code": null,
"e": 1984,
"s": 1943,
"text": "Run index.js file using below command: "
},
{
"code": null,
"e": 1998,
"s": 1984,
"text": "node index.js"
},
{
"code": null,
"e": 2107,
"s": 1998,
"text": "Now open a browser and go to http://localhost:3000/, now on your screen you will see the following output: "
},
{
"code": null,
"e": 2133,
"s": 2107,
"text": "{\"title\":\"GeeksforGeeks\"}"
},
{
"code": null,
"e": 2190,
"s": 2133,
"text": "And you will see the following output on your console: "
},
{
"code": null,
"e": 2200,
"s": 2190,
"text": "User Page"
},
{
"code": null,
"e": 2258,
"s": 2200,
"text": "Reference: https://expressjs.com/en/4x/api.html#res.json "
},
{
"code": null,
"e": 2271,
"s": 2258,
"text": "simmytarika5"
},
{
"code": null,
"e": 2282,
"s": 2271,
"text": "Express.js"
},
{
"code": null,
"e": 2290,
"s": 2282,
"text": "Node.js"
},
{
"code": null,
"e": 2307,
"s": 2290,
"text": "Web Technologies"
}
]
|
HTML5 Video | 12 Jun, 2022
In this article, we will know HTML5 Video, along with knowing the different ways to add the videos to the HTML page & understanding its implementation through the examples. Before HTML 5 came into existence, videos could only be played in a browser using a plugin like flash. But after the release of HTML 5, adding a video to a webpage is as easy as adding an image. The HTML5 “video” element specifies a standard way to embed a video on a web page.
There are three different formats that are commonly supported by web browsers – mp4, Ogg, and WebM. The table below lists the formats supported by different browsers:
Syntax:
<video src="" controls> </video>
Attributes that can be used with the “video” tag are listed below :
Autoplay: It tells the browser to immediately start downloading the video and play it as soon as it can.Preload: It intends to provide a hint to the browser about what the author thinks will lead to the best user experience.Loop: It tells the browser to automatically loop the video.height: It sets the height of the video in CSS pixels.width: It sets the width of the video in CSS pixels.Controls: It shows the default video controls like play, pause, volume, etc.Muted: It mutes the audio from the video.Poster: It loads an image to preview before the loading of the video.src: It is used to specify the URL of the video file.
Autoplay: It tells the browser to immediately start downloading the video and play it as soon as it can.
Preload: It intends to provide a hint to the browser about what the author thinks will lead to the best user experience.
Loop: It tells the browser to automatically loop the video.
height: It sets the height of the video in CSS pixels.
width: It sets the width of the video in CSS pixels.
Controls: It shows the default video controls like play, pause, volume, etc.
Muted: It mutes the audio from the video.
Poster: It loads an image to preview before the loading of the video.
src: It is used to specify the URL of the video file.
Example: This example illustrates the use of <video> tag where we have used preload attribute whose value is set to auto which specifies the browser should load the entire video when the page loads.
HTML
<!DOCTYPE html><html><body> <center> <h1 style="color:green;">GeeksforGeeks</h1> <h3>HTML video tag</h3> <p>Adding video on the webpage <p> <video width="450" height="250" controls preload="auto"> <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.mp4" type="video/mp4"> <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.ogg" type="video/ogg"> </video> </center></body></html>
Output:
We will understand the various ways to implement the <video> tag, through the examples.
Adding Video using HTML5:
Example: This simple example illustrates the use of the <video> tag in HTML. Here, the controls attribute is used to add controls like play, pause, volume, etc, & the “source” element is used to specify the video that the browser will choose to play.
HTML
<!DOCTYPE html><html><body> <p>Adding Video on my webpage </p> <video width="400" height="350" controls> <source src="myvid.mp4" type="video/mp4"> <source src="myvid.ogg" type="video/ogg"> </video></body></html>
Output:
Video addition to the HTML.
Autoplaying a Video using HTML5: In order to start a video automatically, we can use the autoplay attribute.
Example: This example illustrates the use of the autoplay attribute in the HTML <video> tag.
HTML
<!DOCTYPE html><html><body> <p>Adding Video on my webpage</p> <video width="400" height="350" autoplay> <source src="myvid.mp4" type="video/mp4"> <source src="myvid.ogg" type="video/ogg"> </video></body></html>
Output:
Autoplay attribute
Please refer to the How to display video controls in HTML5? article for knowing the various available controls in detail.
HTML Video using JavaScript: Many properties and events can be set for a video like load, play and pause videos, as well as setting duration and volume.
Example: In this example, we have used Javascript in order to play, pause & set the volume & duration of the video in HTML.
HTML
<!DOCTYPE html><html><body> <div style="text-align:center"> <button onclick="Pauseplay()">Pause/Play</button> <button onclick="Big()">Big</button> <button onclick="Small()">Small</button> <button onclick="Normal()">Normal</button> <br> <video id="myvideo" width="450"> <source src="myvid.MP4" type="video/mp4"> <source src="myvid.ogg" type="video/ogg"> </video> </div> <script> var testvideo = document.getElementById("myvideo"); function Pauseplay() { if(testvideo.paused) testvideo.play(); else testvideo.pause(); } function Big() { testvideo.width = 600; } function Small() { testvideo.width = 300; } function Normal() { testvideo.width = 450; } </script></body></html>
Output:
Setting the various video controls using the Javascript events & properties in HTML
Supported browsers:
Google Chrome 3 and above
Internet Explorer 9 and above
Microsoft Edge 12 and above
Firefox 3.5 and above
Opera 10.5 and above
Safari 3.1 and above
nidhi_biet
shubhamyadav4
bhaskargeeksforgeeks
sweetyty
satyamm09
HTML-Tags
HTML5
HTML
Technical Scripter
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n12 Jun, 2022"
},
{
"code": null,
"e": 505,
"s": 53,
"text": "In this article, we will know HTML5 Video, along with knowing the different ways to add the videos to the HTML page & understanding its implementation through the examples. Before HTML 5 came into existence, videos could only be played in a browser using a plugin like flash. But after the release of HTML 5, adding a video to a webpage is as easy as adding an image. The HTML5 “video” element specifies a standard way to embed a video on a web page. "
},
{
"code": null,
"e": 672,
"s": 505,
"text": "There are three different formats that are commonly supported by web browsers – mp4, Ogg, and WebM. The table below lists the formats supported by different browsers:"
},
{
"code": null,
"e": 680,
"s": 672,
"text": "Syntax:"
},
{
"code": null,
"e": 716,
"s": 680,
"text": " <video src=\"\" controls> </video>"
},
{
"code": null,
"e": 784,
"s": 716,
"text": "Attributes that can be used with the “video” tag are listed below :"
},
{
"code": null,
"e": 1413,
"s": 784,
"text": "Autoplay: It tells the browser to immediately start downloading the video and play it as soon as it can.Preload: It intends to provide a hint to the browser about what the author thinks will lead to the best user experience.Loop: It tells the browser to automatically loop the video.height: It sets the height of the video in CSS pixels.width: It sets the width of the video in CSS pixels.Controls: It shows the default video controls like play, pause, volume, etc.Muted: It mutes the audio from the video.Poster: It loads an image to preview before the loading of the video.src: It is used to specify the URL of the video file."
},
{
"code": null,
"e": 1518,
"s": 1413,
"text": "Autoplay: It tells the browser to immediately start downloading the video and play it as soon as it can."
},
{
"code": null,
"e": 1639,
"s": 1518,
"text": "Preload: It intends to provide a hint to the browser about what the author thinks will lead to the best user experience."
},
{
"code": null,
"e": 1699,
"s": 1639,
"text": "Loop: It tells the browser to automatically loop the video."
},
{
"code": null,
"e": 1754,
"s": 1699,
"text": "height: It sets the height of the video in CSS pixels."
},
{
"code": null,
"e": 1807,
"s": 1754,
"text": "width: It sets the width of the video in CSS pixels."
},
{
"code": null,
"e": 1884,
"s": 1807,
"text": "Controls: It shows the default video controls like play, pause, volume, etc."
},
{
"code": null,
"e": 1926,
"s": 1884,
"text": "Muted: It mutes the audio from the video."
},
{
"code": null,
"e": 1996,
"s": 1926,
"text": "Poster: It loads an image to preview before the loading of the video."
},
{
"code": null,
"e": 2050,
"s": 1996,
"text": "src: It is used to specify the URL of the video file."
},
{
"code": null,
"e": 2249,
"s": 2050,
"text": "Example: This example illustrates the use of <video> tag where we have used preload attribute whose value is set to auto which specifies the browser should load the entire video when the page loads."
},
{
"code": null,
"e": 2254,
"s": 2249,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><body> <center> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h3>HTML video tag</h3> <p>Adding video on the webpage <p> <video width=\"450\" height=\"250\" controls preload=\"auto\"> <source src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.mp4\" type=\"video/mp4\"> <source src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.ogg\" type=\"video/ogg\"> </video> </center></body></html>",
"e": 2936,
"s": 2254,
"text": null
},
{
"code": null,
"e": 2944,
"s": 2936,
"text": "Output:"
},
{
"code": null,
"e": 3032,
"s": 2944,
"text": "We will understand the various ways to implement the <video> tag, through the examples."
},
{
"code": null,
"e": 3058,
"s": 3032,
"text": "Adding Video using HTML5:"
},
{
"code": null,
"e": 3309,
"s": 3058,
"text": "Example: This simple example illustrates the use of the <video> tag in HTML. Here, the controls attribute is used to add controls like play, pause, volume, etc, & the “source” element is used to specify the video that the browser will choose to play."
},
{
"code": null,
"e": 3314,
"s": 3309,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><body> <p>Adding Video on my webpage </p> <video width=\"400\" height=\"350\" controls> <source src=\"myvid.mp4\" type=\"video/mp4\"> <source src=\"myvid.ogg\" type=\"video/ogg\"> </video></body></html>",
"e": 3606,
"s": 3314,
"text": null
},
{
"code": null,
"e": 3614,
"s": 3606,
"text": "Output:"
},
{
"code": null,
"e": 3642,
"s": 3614,
"text": "Video addition to the HTML."
},
{
"code": null,
"e": 3751,
"s": 3642,
"text": "Autoplaying a Video using HTML5: In order to start a video automatically, we can use the autoplay attribute."
},
{
"code": null,
"e": 3844,
"s": 3751,
"text": "Example: This example illustrates the use of the autoplay attribute in the HTML <video> tag."
},
{
"code": null,
"e": 3849,
"s": 3844,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><body> <p>Adding Video on my webpage</p> <video width=\"400\" height=\"350\" autoplay> <source src=\"myvid.mp4\" type=\"video/mp4\"> <source src=\"myvid.ogg\" type=\"video/ogg\"> </video></body></html>",
"e": 4110,
"s": 3849,
"text": null
},
{
"code": null,
"e": 4118,
"s": 4110,
"text": "Output:"
},
{
"code": null,
"e": 4137,
"s": 4118,
"text": "Autoplay attribute"
},
{
"code": null,
"e": 4259,
"s": 4137,
"text": "Please refer to the How to display video controls in HTML5? article for knowing the various available controls in detail."
},
{
"code": null,
"e": 4412,
"s": 4259,
"text": "HTML Video using JavaScript: Many properties and events can be set for a video like load, play and pause videos, as well as setting duration and volume."
},
{
"code": null,
"e": 4536,
"s": 4412,
"text": "Example: In this example, we have used Javascript in order to play, pause & set the volume & duration of the video in HTML."
},
{
"code": null,
"e": 4541,
"s": 4536,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><body> <div style=\"text-align:center\"> <button onclick=\"Pauseplay()\">Pause/Play</button> <button onclick=\"Big()\">Big</button> <button onclick=\"Small()\">Small</button> <button onclick=\"Normal()\">Normal</button> <br> <video id=\"myvideo\" width=\"450\"> <source src=\"myvid.MP4\" type=\"video/mp4\"> <source src=\"myvid.ogg\" type=\"video/ogg\"> </video> </div> <script> var testvideo = document.getElementById(\"myvideo\"); function Pauseplay() { if(testvideo.paused) testvideo.play(); else testvideo.pause(); } function Big() { testvideo.width = 600; } function Small() { testvideo.width = 300; } function Normal() { testvideo.width = 450; } </script></body></html>",
"e": 5457,
"s": 4541,
"text": null
},
{
"code": null,
"e": 5465,
"s": 5457,
"text": "Output:"
},
{
"code": null,
"e": 5549,
"s": 5465,
"text": "Setting the various video controls using the Javascript events & properties in HTML"
},
{
"code": null,
"e": 5570,
"s": 5549,
"text": "Supported browsers: "
},
{
"code": null,
"e": 5596,
"s": 5570,
"text": "Google Chrome 3 and above"
},
{
"code": null,
"e": 5626,
"s": 5596,
"text": "Internet Explorer 9 and above"
},
{
"code": null,
"e": 5654,
"s": 5626,
"text": "Microsoft Edge 12 and above"
},
{
"code": null,
"e": 5676,
"s": 5654,
"text": "Firefox 3.5 and above"
},
{
"code": null,
"e": 5697,
"s": 5676,
"text": "Opera 10.5 and above"
},
{
"code": null,
"e": 5718,
"s": 5697,
"text": "Safari 3.1 and above"
},
{
"code": null,
"e": 5729,
"s": 5718,
"text": "nidhi_biet"
},
{
"code": null,
"e": 5743,
"s": 5729,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 5764,
"s": 5743,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 5773,
"s": 5764,
"text": "sweetyty"
},
{
"code": null,
"e": 5783,
"s": 5773,
"text": "satyamm09"
},
{
"code": null,
"e": 5793,
"s": 5783,
"text": "HTML-Tags"
},
{
"code": null,
"e": 5799,
"s": 5793,
"text": "HTML5"
},
{
"code": null,
"e": 5804,
"s": 5799,
"text": "HTML"
},
{
"code": null,
"e": 5823,
"s": 5804,
"text": "Technical Scripter"
},
{
"code": null,
"e": 5828,
"s": 5823,
"text": "HTML"
},
{
"code": null,
"e": 5926,
"s": 5828,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5974,
"s": 5926,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 6036,
"s": 5974,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 6086,
"s": 6036,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 6110,
"s": 6086,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 6163,
"s": 6110,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 6223,
"s": 6163,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 6284,
"s": 6223,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 6334,
"s": 6284,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 6371,
"s": 6334,
"text": "Types of CSS (Cascading Style Sheet)"
}
]
|
How to use gRPC API to Serve a Deep Learning Model? | by Renu Khandelwal | Towards Data Science | In this post, you will learn What is gRPC, how does it work, the benefits of gRPC, the difference between gRPC and REST API, and finally implement gRPC API using Tensorflow Serving to serve a model in Production?
gRPC is a Remote procedure call platform developed by Google.
GRPC is a modern open-source, high-performance, low latency and high speed throughput RPC framework that uses HTTP/2 as transport protocol and uses protocol buffers as the Interface Definition Language(IDL) and also as its underlying message interchange format
A gRPC channel is created that provides a connection to a gRPC server on a specified port. The client invokes a method on the stub as if it is a local object; the server is notified of the client gRPC request. gRPC uses Protocol Buffers to interchange messages between client and server. Protocol Buffers are a way to encode structured data in an efficient, extensible format.
Once the server receives the client's request, it executes the method and sends the client's response back with a status code and optional metadata. gRPC allows clients to specify wait time to allow the server to respond before the RPC call is terminated.
gRPC uses binary payloads, which are efficient to create and parse and hence light-weight.
Bi-directional streaming is possible in gRPC, which is not the case with REST API
gRPC API is built on top of HTTP/2 supporting the traditional request and response steaming as well as bi-directional streaming
10 times faster message transmission compared to REST API as gRPC uses serialized Protocol Buffers and HTTP/2
Loose coupling between client and server makes it easy to make changes
gRPC allows integration of API’s programmed in different languages
Payload Format: REST uses JSON for exchanging messages between client and server, whereas gRPC uses Protocol Buffers. Protocol Buffers are compressed better than JSON, thus making gRPC transmit data over networks more efficiently.
Transfer Protocols: REST heavily uses HTTP 1.1 protocol, which is textual, whereas gRPC is built on the new HTTP/2 binary protocol that compresses the header with efficient parsing and is much safer.
Streaming vs. Request-Response: REST supports the Request-Response model available in HTTP1.1. gRPC uses bi-directional streaming capabilities available in HTTP/2, where the client and server send a sequence of messages to each other using a read-write stream.
Create the request payload from the client to the server as a Protocol Buffer(.proto) file. The client invokes the API through the Stub.Run the docker image that exposes port 8500 for accepting the gRPC request and sending a response back to the clientRun the server and client(s).
Create the request payload from the client to the server as a Protocol Buffer(.proto) file. The client invokes the API through the Stub.
Run the docker image that exposes port 8500 for accepting the gRPC request and sending a response back to the client
Run the server and client(s).
To implement REST API using Tensorflow Serving, follow this blog.
For Windows 10, we will use a TensorFlow serving image.
docker pull tensorflow/serving
Once you have the TensorFlow Serving image
Expose Port 8500 for gRPC
Optional environment variable MODEL_NAME (defaults to model)
Optional environment variable MODEL_BASE_PATH (defaults to /models)
Here I have taken the MNIST dataset from TensorFlow datasets
#Importing required librariesimport osimport jsonimport tempfileimport requestsimport numpy as npimport tensorflow as tfimport tensorflow_datasets as tfds#Loading MNIST train and test dataset#as_supervised=True, will return tuple instead of a dictionary for image and label(ds_train, ds_test), ds_info = tfds.load("mnist", split=['train','test'], with_info=True, as_supervised=True)#to select the 'image' and 'label' using indexing coverting train and test dataset to a numpy arrayarray = np.vstack(tfds.as_numpy(ds_train))X_train = np.array(list(map(lambda x: x[0], array)))y_train = np.array(list(map(lambda x: x[1], array)))X_test = np.array(list(map(lambda x: x[0], array)))y_test = np.array(list(map(lambda x: x[1], array)))#setting batch_size and epochsepoch=10batch_size=128#Creating input data pipeline for train and test dataset# Function to normalize the imagesdef normalize_image(image, label): #Normalizes images from uint8` to float32 return tf.cast(image, tf.float32) / 255., label# Input data pipeline for test dataset#Normalize the image using map function then cache and shuffle the #train dataset # Create a batch of the training dataset and then prefecth for #overlapiing image preprocessing(producer) and model execution work #(consumer)ds_train = ds_train.map( normalize_img, num_parallel_calls=tf.data.experimental.AUTOTUNE)ds_train = ds_train.cache()ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples)ds_train = ds_train.batch(batch_size)ds_train = ds_train.prefetch(tf.data.experimental.AUTOTUNE)# Input data pipeline for test dataset (No need to shuffle the test #dataset)ds_test = ds_test.map( normalize_image, num_parallel_calls=tf.data.experimental.AUTOTUNE)ds_test = ds_test.batch(batch_size)ds_test = ds_test.cache()ds_test = ds_test.prefetch(tf.data.experimental.AUTOTUNE)# Build the modelmodel = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28, 1)), tf.keras.layers.Dense(128,activation='relu'), tf.keras.layers.Dense(196, activation='softmax')])#Compile the modelmodel.compile( loss='sparse_categorical_crossentropy', optimizer=tf.keras.optimizers.Adam(0.001), metrics=['accuracy'],)#Fit the modelmodel.fit( ds_train, epochs=epoch, validation_data=ds_test, verbose=2)
Saving the model into a protocol buffer file by specifying the save_format as “tf”.
MODEL_DIR='tf_model'version = "1"export_path = os.path.join(MODEL_DIR, str(version))#Save the model model.save(export_path, save_format="tf")print('\nexport_path = {}'.format(export_path))!dir {export_path}
You can examine the model using the saved_model_cli command.
!saved_model_cli show --dir {export_path} --all
Importing libraries for gRPC implementation
import grpcfrom tensorflow_serving.apis import predict_pb2from tensorflow_serving.apis import prediction_service_pb2_grpcfrom tensorboard.compat.proto import types_pb2
Establish the channel between the client and server using the gRCP port 8500. Create the client stub for the client to communicate with the server
channel = grpc.insecure_channel('127.0.0.1:8500')stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)
Create the request payload for the server as a Protocol Buffer by specifying the model name and model input, data type, and data size and shape.
request = predict_pb2.PredictRequest()request.model_spec.name = 'mnist'request.inputs['flatten_input'].CopyFrom(tf.make_tensor_proto(X_test[0],dtype=types_pb2.DT_FLOAT, shape=[28,28,1]))
If the data type and data size do not match the model input, you will get an error “input size does not match signature”.
To resolve this error, check the model input data type and size and match it with the request sent to gRPC.
Run the docker image that exposes port 8500 for accepting the gRPC request
docker run -p 8500:8500 --mount type=bind,source=C:\TF_serving\tf_model,target=/models/mnist/ -e MODEL_NAME=mnist -t tensorflow/serving
The source should be an absolute path.
The server is now ready to accept the client request
To predict the result of the request, call the Predict method from the stub
result=stub.Predict(request, 10.0)result
res=np.argmax(result.outputs['dense_1'].float_val)print(" predicted output :", res)
Displaying the input image using matplotlib
import matplotlib.pyplot as plt%matplotlib inlineimg = X_test[0].reshape(28,28)plt.title(res)plt.imshow(img, cmap="gray")
gRPC is Google’s new Remote Procedure call API, which is approximately 10 times faster than the REST API. gRPC is built on HTTP/2, which uses Protocol Buffers to interchange bi-directional messages between client and server efficiently. | [
{
"code": null,
"e": 385,
"s": 172,
"text": "In this post, you will learn What is gRPC, how does it work, the benefits of gRPC, the difference between gRPC and REST API, and finally implement gRPC API using Tensorflow Serving to serve a model in Production?"
},
{
"code": null,
"e": 447,
"s": 385,
"text": "gRPC is a Remote procedure call platform developed by Google."
},
{
"code": null,
"e": 708,
"s": 447,
"text": "GRPC is a modern open-source, high-performance, low latency and high speed throughput RPC framework that uses HTTP/2 as transport protocol and uses protocol buffers as the Interface Definition Language(IDL) and also as its underlying message interchange format"
},
{
"code": null,
"e": 1085,
"s": 708,
"text": "A gRPC channel is created that provides a connection to a gRPC server on a specified port. The client invokes a method on the stub as if it is a local object; the server is notified of the client gRPC request. gRPC uses Protocol Buffers to interchange messages between client and server. Protocol Buffers are a way to encode structured data in an efficient, extensible format."
},
{
"code": null,
"e": 1341,
"s": 1085,
"text": "Once the server receives the client's request, it executes the method and sends the client's response back with a status code and optional metadata. gRPC allows clients to specify wait time to allow the server to respond before the RPC call is terminated."
},
{
"code": null,
"e": 1432,
"s": 1341,
"text": "gRPC uses binary payloads, which are efficient to create and parse and hence light-weight."
},
{
"code": null,
"e": 1514,
"s": 1432,
"text": "Bi-directional streaming is possible in gRPC, which is not the case with REST API"
},
{
"code": null,
"e": 1642,
"s": 1514,
"text": "gRPC API is built on top of HTTP/2 supporting the traditional request and response steaming as well as bi-directional streaming"
},
{
"code": null,
"e": 1752,
"s": 1642,
"text": "10 times faster message transmission compared to REST API as gRPC uses serialized Protocol Buffers and HTTP/2"
},
{
"code": null,
"e": 1823,
"s": 1752,
"text": "Loose coupling between client and server makes it easy to make changes"
},
{
"code": null,
"e": 1890,
"s": 1823,
"text": "gRPC allows integration of API’s programmed in different languages"
},
{
"code": null,
"e": 2121,
"s": 1890,
"text": "Payload Format: REST uses JSON for exchanging messages between client and server, whereas gRPC uses Protocol Buffers. Protocol Buffers are compressed better than JSON, thus making gRPC transmit data over networks more efficiently."
},
{
"code": null,
"e": 2321,
"s": 2121,
"text": "Transfer Protocols: REST heavily uses HTTP 1.1 protocol, which is textual, whereas gRPC is built on the new HTTP/2 binary protocol that compresses the header with efficient parsing and is much safer."
},
{
"code": null,
"e": 2582,
"s": 2321,
"text": "Streaming vs. Request-Response: REST supports the Request-Response model available in HTTP1.1. gRPC uses bi-directional streaming capabilities available in HTTP/2, where the client and server send a sequence of messages to each other using a read-write stream."
},
{
"code": null,
"e": 2864,
"s": 2582,
"text": "Create the request payload from the client to the server as a Protocol Buffer(.proto) file. The client invokes the API through the Stub.Run the docker image that exposes port 8500 for accepting the gRPC request and sending a response back to the clientRun the server and client(s)."
},
{
"code": null,
"e": 3001,
"s": 2864,
"text": "Create the request payload from the client to the server as a Protocol Buffer(.proto) file. The client invokes the API through the Stub."
},
{
"code": null,
"e": 3118,
"s": 3001,
"text": "Run the docker image that exposes port 8500 for accepting the gRPC request and sending a response back to the client"
},
{
"code": null,
"e": 3148,
"s": 3118,
"text": "Run the server and client(s)."
},
{
"code": null,
"e": 3214,
"s": 3148,
"text": "To implement REST API using Tensorflow Serving, follow this blog."
},
{
"code": null,
"e": 3270,
"s": 3214,
"text": "For Windows 10, we will use a TensorFlow serving image."
},
{
"code": null,
"e": 3301,
"s": 3270,
"text": "docker pull tensorflow/serving"
},
{
"code": null,
"e": 3344,
"s": 3301,
"text": "Once you have the TensorFlow Serving image"
},
{
"code": null,
"e": 3370,
"s": 3344,
"text": "Expose Port 8500 for gRPC"
},
{
"code": null,
"e": 3431,
"s": 3370,
"text": "Optional environment variable MODEL_NAME (defaults to model)"
},
{
"code": null,
"e": 3499,
"s": 3431,
"text": "Optional environment variable MODEL_BASE_PATH (defaults to /models)"
},
{
"code": null,
"e": 3560,
"s": 3499,
"text": "Here I have taken the MNIST dataset from TensorFlow datasets"
},
{
"code": null,
"e": 5832,
"s": 3560,
"text": "#Importing required librariesimport osimport jsonimport tempfileimport requestsimport numpy as npimport tensorflow as tfimport tensorflow_datasets as tfds#Loading MNIST train and test dataset#as_supervised=True, will return tuple instead of a dictionary for image and label(ds_train, ds_test), ds_info = tfds.load(\"mnist\", split=['train','test'], with_info=True, as_supervised=True)#to select the 'image' and 'label' using indexing coverting train and test dataset to a numpy arrayarray = np.vstack(tfds.as_numpy(ds_train))X_train = np.array(list(map(lambda x: x[0], array)))y_train = np.array(list(map(lambda x: x[1], array)))X_test = np.array(list(map(lambda x: x[0], array)))y_test = np.array(list(map(lambda x: x[1], array)))#setting batch_size and epochsepoch=10batch_size=128#Creating input data pipeline for train and test dataset# Function to normalize the imagesdef normalize_image(image, label): #Normalizes images from uint8` to float32 return tf.cast(image, tf.float32) / 255., label# Input data pipeline for test dataset#Normalize the image using map function then cache and shuffle the #train dataset # Create a batch of the training dataset and then prefecth for #overlapiing image preprocessing(producer) and model execution work #(consumer)ds_train = ds_train.map( normalize_img, num_parallel_calls=tf.data.experimental.AUTOTUNE)ds_train = ds_train.cache()ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples)ds_train = ds_train.batch(batch_size)ds_train = ds_train.prefetch(tf.data.experimental.AUTOTUNE)# Input data pipeline for test dataset (No need to shuffle the test #dataset)ds_test = ds_test.map( normalize_image, num_parallel_calls=tf.data.experimental.AUTOTUNE)ds_test = ds_test.batch(batch_size)ds_test = ds_test.cache()ds_test = ds_test.prefetch(tf.data.experimental.AUTOTUNE)# Build the modelmodel = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28, 1)), tf.keras.layers.Dense(128,activation='relu'), tf.keras.layers.Dense(196, activation='softmax')])#Compile the modelmodel.compile( loss='sparse_categorical_crossentropy', optimizer=tf.keras.optimizers.Adam(0.001), metrics=['accuracy'],)#Fit the modelmodel.fit( ds_train, epochs=epoch, validation_data=ds_test, verbose=2)"
},
{
"code": null,
"e": 5916,
"s": 5832,
"text": "Saving the model into a protocol buffer file by specifying the save_format as “tf”."
},
{
"code": null,
"e": 6123,
"s": 5916,
"text": "MODEL_DIR='tf_model'version = \"1\"export_path = os.path.join(MODEL_DIR, str(version))#Save the model model.save(export_path, save_format=\"tf\")print('\\nexport_path = {}'.format(export_path))!dir {export_path}"
},
{
"code": null,
"e": 6184,
"s": 6123,
"text": "You can examine the model using the saved_model_cli command."
},
{
"code": null,
"e": 6232,
"s": 6184,
"text": "!saved_model_cli show --dir {export_path} --all"
},
{
"code": null,
"e": 6276,
"s": 6232,
"text": "Importing libraries for gRPC implementation"
},
{
"code": null,
"e": 6444,
"s": 6276,
"text": "import grpcfrom tensorflow_serving.apis import predict_pb2from tensorflow_serving.apis import prediction_service_pb2_grpcfrom tensorboard.compat.proto import types_pb2"
},
{
"code": null,
"e": 6591,
"s": 6444,
"text": "Establish the channel between the client and server using the gRCP port 8500. Create the client stub for the client to communicate with the server"
},
{
"code": null,
"e": 6706,
"s": 6591,
"text": "channel = grpc.insecure_channel('127.0.0.1:8500')stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)"
},
{
"code": null,
"e": 6851,
"s": 6706,
"text": "Create the request payload for the server as a Protocol Buffer by specifying the model name and model input, data type, and data size and shape."
},
{
"code": null,
"e": 7039,
"s": 6851,
"text": "request = predict_pb2.PredictRequest()request.model_spec.name = 'mnist'request.inputs['flatten_input'].CopyFrom(tf.make_tensor_proto(X_test[0],dtype=types_pb2.DT_FLOAT, shape=[28,28,1]))"
},
{
"code": null,
"e": 7161,
"s": 7039,
"text": "If the data type and data size do not match the model input, you will get an error “input size does not match signature”."
},
{
"code": null,
"e": 7269,
"s": 7161,
"text": "To resolve this error, check the model input data type and size and match it with the request sent to gRPC."
},
{
"code": null,
"e": 7344,
"s": 7269,
"text": "Run the docker image that exposes port 8500 for accepting the gRPC request"
},
{
"code": null,
"e": 7480,
"s": 7344,
"text": "docker run -p 8500:8500 --mount type=bind,source=C:\\TF_serving\\tf_model,target=/models/mnist/ -e MODEL_NAME=mnist -t tensorflow/serving"
},
{
"code": null,
"e": 7519,
"s": 7480,
"text": "The source should be an absolute path."
},
{
"code": null,
"e": 7572,
"s": 7519,
"text": "The server is now ready to accept the client request"
},
{
"code": null,
"e": 7648,
"s": 7572,
"text": "To predict the result of the request, call the Predict method from the stub"
},
{
"code": null,
"e": 7689,
"s": 7648,
"text": "result=stub.Predict(request, 10.0)result"
},
{
"code": null,
"e": 7773,
"s": 7689,
"text": "res=np.argmax(result.outputs['dense_1'].float_val)print(\" predicted output :\", res)"
},
{
"code": null,
"e": 7817,
"s": 7773,
"text": "Displaying the input image using matplotlib"
},
{
"code": null,
"e": 7939,
"s": 7817,
"text": "import matplotlib.pyplot as plt%matplotlib inlineimg = X_test[0].reshape(28,28)plt.title(res)plt.imshow(img, cmap=\"gray\")"
}
]
|
Mathematics | Rules of Inference - GeeksforGeeks | 29 Jun, 2021
Prerequisite: Predicates and Quantifiers Set 2, Propositional Equivalences
Every Theorem in Mathematics, or any subject for that matter, is supported by underlying proofs. These proofs are nothing but a set of arguments that are conclusive evidence of the validity of the theory.The arguments are chained together using Rules of Inferences to deduce new statements and ultimately prove that the theorem is valid.
Important Definitions :
1. Argument – A sequence of statements, premises, that end with a conclusion.2. Validity – A deductive argument is said to be valid if and only if it takes a form that makes it impossible for the premises to be true and the conclusion nevertheless to be false.3. Fallacy – An incorrect reasoning or mistake which leads to invalid arguments.
Structure of an Argument :As defined, an argument is a sequence of statements called premises which end with a conclusion.
Premises -
Conclusion -
is a tautology, then the argument is termed valid otherwise termed as invalid. The argument is written as –
Rules of Inference :Simple arguments can be used as building blocks to construct more complicated valid arguments. Certain simple arguments that have been established as valid are very important in terms of their usage. These arguments are called Rules of Inference.
The most commonly used Rules of Inference are tabulated below –
Similarly, we have Rules of Inference for quantified statements –
Let’s see how Rules of Inference can be used to deduce conclusions from given arguments or check the validity of a given argument.
Example : Show that the hypotheses“It is not sunny this afternoon and it is colder than yesterday”,“We will go swimming only if it is sunny”,“If we do not go swimming, then we will take a canoe trip”, and“If we take a canoe trip, then we will be home by sunset”lead to the conclusion“We will be home by sunset”.The first step is to identify propositions and use propositional variables to represent them. “It is sunny this afternoon” “It is colder than yesterday” “We will go swimming” “We will take a canoe trip” “We will be home by sunset”The hypotheses are –, , , and .The conclusion is –To deduce the conclusion we must use Rules of Inference to construct a proof using the given hypotheses.
Resolution Principle :To understand the Resolution principle, first we need to know certain definitions.
Literal – A variable or negation of a variable. Eg- Sum – Disjunction of literals. Eg- Product – Conjunction of literals. Eg- Clause – A disjunction of literals i.e. it is a sum.Resolvent – For any two clauses and , if there is a literal in that is complementary to a literal in , then removing both and joining the remaining clauses through a disjunction produces another clause . is called the resolvent of and
Literal – A variable or negation of a variable. Eg-
Sum – Disjunction of literals. Eg-
Product – Conjunction of literals. Eg-
Clause – A disjunction of literals i.e. it is a sum.
Resolvent – For any two clauses and , if there is a literal in that is complementary to a literal in , then removing both and joining the remaining clauses through a disjunction produces another clause . is called the resolvent of and
For example,
Here, and are complementary to each other. Removing them and joining the remaining clauses with a disjunction gives us-We could skip the removal part and simply join the clauses to get the same resolvent.This is also the Rule of Inference known as Resolution.
Theorem – If is the resolvent of and , then is also the logical consequence of and .
The Resolution Principle – Given a set of clauses, a (resolution) deduction of from is a finite sequence of clauses such that each is either a clause in or a resolvent of clauses preceding and .We can use the resolution principle to check the validity of arguments or deduce conclusions from them. Other Rules of Inference have the same purpose, but Resolution is unique. It is complete by it’s own. You would need no other Rule of Inference to deduce the conclusion from the given argument.
To do so, we first need to convert all the premises to clausal form. The next step is to apply the resolution Rule of Inference to them step by step until it cannot be applied any further.
For example, consider that we have the following premises –
The first step is to convert them to clausal form –
From the resolution of and ,
From the resolution of and ,
From the resolution of and ,
Therefore, the conclusion is .
Note:Implecations can also be visualised on octagon as,It shows how implecation changes on changing order of there exists and for all symbols.
GATE CS Corner Questions
Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them.1. GATE CS 2004, Question 702. GATE CS 2015 Set-2, Question 13
References-Rules of Inference – Simon Fraser UniversityRules of Inference – WikipediaFallacy – WikipediaBook – Discrete Mathematics and Its Applications by Kenneth Rosen
This article is contributed by Chirag Manwani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
VaibhavRai3
Discrete Mathematics
Engineering Mathematics
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inequalities in LaTeX
Arrow Symbols in LaTeX
Newton's Divided Difference Interpolation Formula
Set Notations in LaTeX
Runge-Kutta 2nd order method to solve Differential equations
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Types of Operating Systems | [
{
"code": null,
"e": 30034,
"s": 30006,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 30109,
"s": 30034,
"text": "Prerequisite: Predicates and Quantifiers Set 2, Propositional Equivalences"
},
{
"code": null,
"e": 30447,
"s": 30109,
"text": "Every Theorem in Mathematics, or any subject for that matter, is supported by underlying proofs. These proofs are nothing but a set of arguments that are conclusive evidence of the validity of the theory.The arguments are chained together using Rules of Inferences to deduce new statements and ultimately prove that the theorem is valid."
},
{
"code": null,
"e": 30471,
"s": 30447,
"text": "Important Definitions :"
},
{
"code": null,
"e": 30812,
"s": 30471,
"text": "1. Argument – A sequence of statements, premises, that end with a conclusion.2. Validity – A deductive argument is said to be valid if and only if it takes a form that makes it impossible for the premises to be true and the conclusion nevertheless to be false.3. Fallacy – An incorrect reasoning or mistake which leads to invalid arguments."
},
{
"code": null,
"e": 30935,
"s": 30812,
"text": "Structure of an Argument :As defined, an argument is a sequence of statements called premises which end with a conclusion."
},
{
"code": null,
"e": 30962,
"s": 30935,
"text": "Premises - \nConclusion - \n"
},
{
"code": null,
"e": 31071,
"s": 30962,
"text": " is a tautology, then the argument is termed valid otherwise termed as invalid. The argument is written as –"
},
{
"code": null,
"e": 31340,
"s": 31073,
"text": "Rules of Inference :Simple arguments can be used as building blocks to construct more complicated valid arguments. Certain simple arguments that have been established as valid are very important in terms of their usage. These arguments are called Rules of Inference."
},
{
"code": null,
"e": 31404,
"s": 31340,
"text": "The most commonly used Rules of Inference are tabulated below –"
},
{
"code": null,
"e": 31472,
"s": 31406,
"text": "Similarly, we have Rules of Inference for quantified statements –"
},
{
"code": null,
"e": 31605,
"s": 31474,
"text": "Let’s see how Rules of Inference can be used to deduce conclusions from given arguments or check the validity of a given argument."
},
{
"code": null,
"e": 32301,
"s": 31605,
"text": "Example : Show that the hypotheses“It is not sunny this afternoon and it is colder than yesterday”,“We will go swimming only if it is sunny”,“If we do not go swimming, then we will take a canoe trip”, and“If we take a canoe trip, then we will be home by sunset”lead to the conclusion“We will be home by sunset”.The first step is to identify propositions and use propositional variables to represent them. “It is sunny this afternoon” “It is colder than yesterday” “We will go swimming” “We will take a canoe trip” “We will be home by sunset”The hypotheses are –, , , and .The conclusion is –To deduce the conclusion we must use Rules of Inference to construct a proof using the given hypotheses."
},
{
"code": null,
"e": 32406,
"s": 32301,
"text": "Resolution Principle :To understand the Resolution principle, first we need to know certain definitions."
},
{
"code": null,
"e": 32826,
"s": 32406,
"text": "Literal – A variable or negation of a variable. Eg- Sum – Disjunction of literals. Eg- Product – Conjunction of literals. Eg- Clause – A disjunction of literals i.e. it is a sum.Resolvent – For any two clauses and , if there is a literal in that is complementary to a literal in , then removing both and joining the remaining clauses through a disjunction produces another clause . is called the resolvent of and "
},
{
"code": null,
"e": 32879,
"s": 32826,
"text": "Literal – A variable or negation of a variable. Eg- "
},
{
"code": null,
"e": 32915,
"s": 32879,
"text": "Sum – Disjunction of literals. Eg- "
},
{
"code": null,
"e": 32955,
"s": 32915,
"text": "Product – Conjunction of literals. Eg- "
},
{
"code": null,
"e": 33008,
"s": 32955,
"text": "Clause – A disjunction of literals i.e. it is a sum."
},
{
"code": null,
"e": 33250,
"s": 33008,
"text": "Resolvent – For any two clauses and , if there is a literal in that is complementary to a literal in , then removing both and joining the remaining clauses through a disjunction produces another clause . is called the resolvent of and "
},
{
"code": null,
"e": 33263,
"s": 33250,
"text": "For example,"
},
{
"code": null,
"e": 33530,
"s": 33268,
"text": "Here, and are complementary to each other. Removing them and joining the remaining clauses with a disjunction gives us-We could skip the removal part and simply join the clauses to get the same resolvent.This is also the Rule of Inference known as Resolution."
},
{
"code": null,
"e": 33619,
"s": 33530,
"text": "Theorem – If is the resolvent of and , then is also the logical consequence of and ."
},
{
"code": null,
"e": 34118,
"s": 33619,
"text": "The Resolution Principle – Given a set of clauses, a (resolution) deduction of from is a finite sequence of clauses such that each is either a clause in or a resolvent of clauses preceding and .We can use the resolution principle to check the validity of arguments or deduce conclusions from them. Other Rules of Inference have the same purpose, but Resolution is unique. It is complete by it’s own. You would need no other Rule of Inference to deduce the conclusion from the given argument."
},
{
"code": null,
"e": 34307,
"s": 34118,
"text": "To do so, we first need to convert all the premises to clausal form. The next step is to apply the resolution Rule of Inference to them step by step until it cannot be applied any further."
},
{
"code": null,
"e": 34367,
"s": 34307,
"text": "For example, consider that we have the following premises –"
},
{
"code": null,
"e": 34423,
"s": 34371,
"text": "The first step is to convert them to clausal form –"
},
{
"code": null,
"e": 34555,
"s": 34423,
"text": "\n \n\n\n\n\nFrom the resolution of and , \nFrom the resolution of and , \nFrom the resolution of and , \nTherefore, the conclusion is .\n"
},
{
"code": null,
"e": 34698,
"s": 34555,
"text": "Note:Implecations can also be visualised on octagon as,It shows how implecation changes on changing order of there exists and for all symbols."
},
{
"code": null,
"e": 34723,
"s": 34698,
"text": "GATE CS Corner Questions"
},
{
"code": null,
"e": 34983,
"s": 34723,
"text": "Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them.1. GATE CS 2004, Question 702. GATE CS 2015 Set-2, Question 13"
},
{
"code": null,
"e": 35153,
"s": 34983,
"text": "References-Rules of Inference – Simon Fraser UniversityRules of Inference – WikipediaFallacy – WikipediaBook – Discrete Mathematics and Its Applications by Kenneth Rosen"
},
{
"code": null,
"e": 35451,
"s": 35153,
"text": "This article is contributed by Chirag Manwani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 35576,
"s": 35451,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 35588,
"s": 35576,
"text": "VaibhavRai3"
},
{
"code": null,
"e": 35609,
"s": 35588,
"text": "Discrete Mathematics"
},
{
"code": null,
"e": 35633,
"s": 35609,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 35641,
"s": 35633,
"text": "GATE CS"
},
{
"code": null,
"e": 35739,
"s": 35641,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35761,
"s": 35739,
"text": "Inequalities in LaTeX"
},
{
"code": null,
"e": 35784,
"s": 35761,
"text": "Arrow Symbols in LaTeX"
},
{
"code": null,
"e": 35834,
"s": 35784,
"text": "Newton's Divided Difference Interpolation Formula"
},
{
"code": null,
"e": 35857,
"s": 35834,
"text": "Set Notations in LaTeX"
},
{
"code": null,
"e": 35918,
"s": 35857,
"text": "Runge-Kutta 2nd order method to solve Differential equations"
},
{
"code": null,
"e": 35938,
"s": 35918,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 35962,
"s": 35938,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 35975,
"s": 35962,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 36024,
"s": 35975,
"text": "Page Replacement Algorithms in Operating Systems"
}
]
|
Exception Handling in Lambda Expressions | Lambda expressions are difficult to write when the function throws a checked expression. See the example below −
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.stream.Collectors;
public class FunctionTester {
public static void main(String[] args) {
String url = "www.google.com";
System.out.println(encodedAddress(url));
}
public static String encodedAddress(String... address) {
return Arrays.stream(address)
.map(s -> URLEncoder.encode(s, "UTF-8"))
.collect(Collectors.joining(","));
}
}
The above code fails to compile because URLEncode.encode() throws UnsupportedEncodingException and cannot be thrown by encodeAddress() method.
One possible solution is to extract URLEncoder.encode() into a separate method and handle the exception there.
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.stream.Collectors;
public class FunctionTester {
public static void main(String[] args) {
String url = "www.google.com";
System.out.println(encodedAddress(url));
}
public static String encodedString(String s) {
try {
URLEncoder.encode(s, "UTF-8");
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return s;
}
public static String encodedAddress(String... address) {
return Arrays.stream(address)
.map(s -> encodedString(s))
.collect(Collectors.joining(","));
}
}
But above approach is not good when we have multiple such methods which throws exception. See the following generalized solution using functional interface and a wrapper method.
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.Collectors;
public class FunctionTester {
public static void main(String[] args) {
String url = "www.google.com";
System.out.println(encodedAddress(url));
}
public static String encodedAddress(String... address) {
return Arrays.stream(address)
.map(wrapper(s -> URLEncoder.encode(s, "UTF-8")))
.collect(Collectors.joining(","));
}
private static <T, R, E extends Exception> Function<T, R>
wrapper(FunctionWithThrows<T, R, E> fe) {
return arg -> {
try {
return fe.apply(arg);
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
}
@FunctionalInterface
interface FunctionWithThrows<T, R, E extends Exception> {
R apply(T t) throws E;
}
www.google.com
32 Lectures
3.5 hours
Pavan Lalwani
11 Lectures
1 hours
Prof. Paul Cline, Ed.D
72 Lectures
10.5 hours
Arun Ammasai
51 Lectures
2 hours
Skillbakerystudios
43 Lectures
4 hours
Mohammad Nauman
8 Lectures
1 hours
Santharam Sivalenka
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2202,
"s": 2089,
"text": "Lambda expressions are difficult to write when the function throws a checked expression. See the example below −"
},
{
"code": null,
"e": 2656,
"s": 2202,
"text": "import java.net.URLEncoder;\nimport java.util.Arrays;\nimport java.util.stream.Collectors;\n\npublic class FunctionTester {\n public static void main(String[] args) {\n String url = \"www.google.com\";\n System.out.println(encodedAddress(url));\n } \n\n public static String encodedAddress(String... address) {\n return Arrays.stream(address)\n .map(s -> URLEncoder.encode(s, \"UTF-8\"))\n .collect(Collectors.joining(\",\"));\n }\n}"
},
{
"code": null,
"e": 2799,
"s": 2656,
"text": "The above code fails to compile because URLEncode.encode() throws UnsupportedEncodingException and cannot be thrown by encodeAddress() method."
},
{
"code": null,
"e": 2910,
"s": 2799,
"text": "One possible solution is to extract URLEncoder.encode() into a separate method and handle the exception there."
},
{
"code": null,
"e": 3631,
"s": 2910,
"text": "import java.io.UnsupportedEncodingException;\nimport java.net.URLEncoder;\nimport java.util.Arrays;\nimport java.util.stream.Collectors;\n\npublic class FunctionTester {\n public static void main(String[] args) {\n String url = \"www.google.com\"; \n System.out.println(encodedAddress(url));\n } \n\n public static String encodedString(String s) {\n try {\n URLEncoder.encode(s, \"UTF-8\");\n }\n catch (UnsupportedEncodingException e) { \n e.printStackTrace();\n }\n return s;\n }\n\n public static String encodedAddress(String... address) {\n return Arrays.stream(address)\n .map(s -> encodedString(s))\n .collect(Collectors.joining(\",\"));\n } \n}"
},
{
"code": null,
"e": 3809,
"s": 3631,
"text": "But above approach is not good when we have multiple such methods which throws exception. See the following generalized solution using functional interface and a wrapper method."
},
{
"code": null,
"e": 4702,
"s": 3809,
"text": "import java.net.URLEncoder;\nimport java.util.Arrays;\nimport java.util.function.Function;\nimport java.util.stream.Collectors;\n\npublic class FunctionTester {\n public static void main(String[] args) {\n String url = \"www.google.com\"; \n System.out.println(encodedAddress(url));\n } \n public static String encodedAddress(String... address) {\n return Arrays.stream(address)\n .map(wrapper(s -> URLEncoder.encode(s, \"UTF-8\")))\n .collect(Collectors.joining(\",\"));\n }\n\n private static <T, R, E extends Exception> Function<T, R> \n wrapper(FunctionWithThrows<T, R, E> fe) {\n return arg -> {\n try {\n return fe.apply(arg);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n };\n }\n}\n\n@FunctionalInterface\ninterface FunctionWithThrows<T, R, E extends Exception> {\n R apply(T t) throws E;\n}"
},
{
"code": null,
"e": 4718,
"s": 4702,
"text": "www.google.com\n"
},
{
"code": null,
"e": 4753,
"s": 4718,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4768,
"s": 4753,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 4801,
"s": 4768,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4825,
"s": 4801,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 4861,
"s": 4825,
"text": "\n 72 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 4875,
"s": 4861,
"text": " Arun Ammasai"
},
{
"code": null,
"e": 4908,
"s": 4875,
"text": "\n 51 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4928,
"s": 4908,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 4961,
"s": 4928,
"text": "\n 43 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4978,
"s": 4961,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 5010,
"s": 4978,
"text": "\n 8 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5031,
"s": 5010,
"text": " Santharam Sivalenka"
},
{
"code": null,
"e": 5038,
"s": 5031,
"text": " Print"
},
{
"code": null,
"e": 5049,
"s": 5038,
"text": " Add Notes"
}
]
|
Merging boolean array with AND operator - JavaScript | Let’s say, we have an array of arrays of boolean like this −
const arr = [[true,false,false],[false,false,false],[false,false,true]];
We are required to write a function that merges this array of arrays into a one-dimensional array by combining the corresponding elements of each subarray using the AND (&&) operator.
Let’s write the code for this function. We will be using Array.prototype.reduce() function to achieve this.
Following is the code −
const arr = [[true,false,false],[false,false,false],[false,false,true]];
const andMerge = (arr = []) => {
return arr.reduce((acc, val) => {
val.forEach((bool, ind) => {
acc[ind] = acc[ind] && bool || false;
});
return acc;
}, []);
};
console.log(andMerge(arr));
This will produce the following output in console −
[ false, false, false ] | [
{
"code": null,
"e": 1123,
"s": 1062,
"text": "Let’s say, we have an array of arrays of boolean like this −"
},
{
"code": null,
"e": 1196,
"s": 1123,
"text": "const arr = [[true,false,false],[false,false,false],[false,false,true]];"
},
{
"code": null,
"e": 1380,
"s": 1196,
"text": "We are required to write a function that merges this array of arrays into a one-dimensional array by combining the corresponding elements of each subarray using the AND (&&) operator."
},
{
"code": null,
"e": 1488,
"s": 1380,
"text": "Let’s write the code for this function. We will be using Array.prototype.reduce() function to achieve this."
},
{
"code": null,
"e": 1512,
"s": 1488,
"text": "Following is the code −"
},
{
"code": null,
"e": 1807,
"s": 1512,
"text": "const arr = [[true,false,false],[false,false,false],[false,false,true]];\nconst andMerge = (arr = []) => {\n return arr.reduce((acc, val) => {\n val.forEach((bool, ind) => {\n acc[ind] = acc[ind] && bool || false;\n });\n return acc;\n }, []);\n};\nconsole.log(andMerge(arr));"
},
{
"code": null,
"e": 1859,
"s": 1807,
"text": "This will produce the following output in console −"
},
{
"code": null,
"e": 1883,
"s": 1859,
"text": "[ false, false, false ]"
}
]
|
CharField - Django Models - GeeksforGeeks | 12 Apr, 2022
CharField is a string field, for small- to large-sized strings. It is like a string field in C/C+++. CharField is generally used for storing small strings like first name, last name, etc. To store larger text TextField is used. The default form widget for this field is TextInput.
CharField has one extra required argument:
CharField.max_length
The maximum length (in characters) of the field. The max_length is enforced at the database level and in Django’s validation using MaxLengthValidator.
Syntax:
field_name = models.CharField(max_length=200, **options)
Illustration of CharField using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into models.py file of geeks app.
Python3
from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.CharField(max_length = 200)
Add the geeks app to INSTALLED_APPS
Python3
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]
Now when we run makemigrations command from the terminal,
Python manage.py makemigrations
A new folder named migrations would be created in geeks directory with a file named 0001_initial.py
Python3
# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.CharField( max_length = 200, )), ], ), ]
Now run,
Python manage.py migrate
Thus, an geeks_field CharField is created when you run migrations on the project. It is a field to store small- to large-sized strings.
CharField is used for storing small sized strings in the database. One can store First Name, Last Name, Address Details, etc. CharField should be given an argument max_length for specifying the maximum length of string it is required to store. In production server, after the Django application is deployed, space is very limited. So it is always optimal to use max_length according to the requirement of the field. Let us create an instance of the CharField we created and check if it is working.
Python3
# importing the model# from geeks appfrom geeks.models import GeeksModel # creating a instance of# GeeksModelgeek_object = GeeksModel.objects.create(geeks_field ="GFG is Best")geek_object.save()
Now let’s check it in admin server. We have created an instance of GeeksModel.
Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to CharField will enable it to store empty values for that table in a relational database. Here are the field options and attributes that an CharField can use.
NaveenArora
annianni
tankisingh7
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24226,
"s": 24198,
"text": "\n12 Apr, 2022"
},
{
"code": null,
"e": 24508,
"s": 24226,
"text": "CharField is a string field, for small- to large-sized strings. It is like a string field in C/C+++. CharField is generally used for storing small strings like first name, last name, etc. To store larger text TextField is used. The default form widget for this field is TextInput. "
},
{
"code": null,
"e": 24552,
"s": 24508,
"text": "CharField has one extra required argument: "
},
{
"code": null,
"e": 24573,
"s": 24552,
"text": "CharField.max_length"
},
{
"code": null,
"e": 24725,
"s": 24573,
"text": "The maximum length (in characters) of the field. The max_length is enforced at the database level and in Django’s validation using MaxLengthValidator. "
},
{
"code": null,
"e": 24733,
"s": 24725,
"text": "Syntax:"
},
{
"code": null,
"e": 24791,
"s": 24733,
"text": "field_name = models.CharField(max_length=200, **options) "
},
{
"code": null,
"e": 24903,
"s": 24791,
"text": "Illustration of CharField using an Example. Consider a project named geeksforgeeks having an app named geeks. "
},
{
"code": null,
"e": 24991,
"s": 24903,
"text": "Refer to the following articles to check how to create a project and an app in Django. "
},
{
"code": null,
"e": 25042,
"s": 24991,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 25075,
"s": 25042,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 25135,
"s": 25075,
"text": "Enter the following code into models.py file of geeks app. "
},
{
"code": null,
"e": 25143,
"s": 25135,
"text": "Python3"
},
{
"code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.CharField(max_length = 200)",
"e": 25309,
"s": 25143,
"text": null
},
{
"code": null,
"e": 25346,
"s": 25309,
"text": "Add the geeks app to INSTALLED_APPS "
},
{
"code": null,
"e": 25354,
"s": 25346,
"text": "Python3"
},
{
"code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]",
"e": 25591,
"s": 25354,
"text": null
},
{
"code": null,
"e": 25649,
"s": 25591,
"text": "Now when we run makemigrations command from the terminal,"
},
{
"code": null,
"e": 25681,
"s": 25649,
"text": "Python manage.py makemigrations"
},
{
"code": null,
"e": 25782,
"s": 25681,
"text": "A new folder named migrations would be created in geeks directory with a file named 0001_initial.py "
},
{
"code": null,
"e": 25790,
"s": 25782,
"text": "Python3"
},
{
"code": "# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.CharField( max_length = 200, )), ], ), ]",
"e": 26437,
"s": 25790,
"text": null
},
{
"code": null,
"e": 26447,
"s": 26437,
"text": "Now run, "
},
{
"code": null,
"e": 26472,
"s": 26447,
"text": "Python manage.py migrate"
},
{
"code": null,
"e": 26608,
"s": 26472,
"text": "Thus, an geeks_field CharField is created when you run migrations on the project. It is a field to store small- to large-sized strings."
},
{
"code": null,
"e": 27106,
"s": 26608,
"text": "CharField is used for storing small sized strings in the database. One can store First Name, Last Name, Address Details, etc. CharField should be given an argument max_length for specifying the maximum length of string it is required to store. In production server, after the Django application is deployed, space is very limited. So it is always optimal to use max_length according to the requirement of the field. Let us create an instance of the CharField we created and check if it is working."
},
{
"code": null,
"e": 27114,
"s": 27106,
"text": "Python3"
},
{
"code": "# importing the model# from geeks appfrom geeks.models import GeeksModel # creating a instance of# GeeksModelgeek_object = GeeksModel.objects.create(geeks_field =\"GFG is Best\")geek_object.save()",
"e": 27309,
"s": 27114,
"text": null
},
{
"code": null,
"e": 27389,
"s": 27309,
"text": "Now let’s check it in admin server. We have created an instance of GeeksModel. "
},
{
"code": null,
"e": 27741,
"s": 27391,
"text": "Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to CharField will enable it to store empty values for that table in a relational database. Here are the field options and attributes that an CharField can use. "
},
{
"code": null,
"e": 27753,
"s": 27741,
"text": "NaveenArora"
},
{
"code": null,
"e": 27762,
"s": 27753,
"text": "annianni"
},
{
"code": null,
"e": 27774,
"s": 27762,
"text": "tankisingh7"
},
{
"code": null,
"e": 27788,
"s": 27774,
"text": "Django-models"
},
{
"code": null,
"e": 27802,
"s": 27788,
"text": "Python Django"
},
{
"code": null,
"e": 27809,
"s": 27802,
"text": "Python"
},
{
"code": null,
"e": 27907,
"s": 27809,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27916,
"s": 27907,
"text": "Comments"
},
{
"code": null,
"e": 27929,
"s": 27916,
"text": "Old Comments"
},
{
"code": null,
"e": 27947,
"s": 27929,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27982,
"s": 27947,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28004,
"s": 27982,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28036,
"s": 28004,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28066,
"s": 28036,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28108,
"s": 28066,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28134,
"s": 28108,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28177,
"s": 28134,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28214,
"s": 28177,
"text": "Create a Pandas DataFrame from Lists"
}
]
|
How to convert String to Date in java? | SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.
The SimpleDateFormat class has some additional methods, notably parse( ), which tries to parse a string according to the format stored in the given SimpleDateFormat object.
Live Demo
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateString {
public static void main(String args[]) throws Exception{
String date = "21-9-2017";
SimpleDateFormat sdt = new SimpleDateFormat("dd-MM-YYYY");
Date result = sdt.parse(date);
System.out.println(result);
}
}
Sun Jan 01 00:00:00 IST 2017 | [
{
"code": null,
"e": 1263,
"s": 1062,
"text": "SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting."
},
{
"code": null,
"e": 1436,
"s": 1263,
"text": "The SimpleDateFormat class has some additional methods, notably parse( ), which tries to parse a string according to the format stored in the given SimpleDateFormat object."
},
{
"code": null,
"e": 1447,
"s": 1436,
"text": " Live Demo"
},
{
"code": null,
"e": 1767,
"s": 1447,
"text": "import java.text.SimpleDateFormat;\nimport java.util.Date;\npublic class DateString {\n public static void main(String args[]) throws Exception{\n String date = \"21-9-2017\";\n SimpleDateFormat sdt = new SimpleDateFormat(\"dd-MM-YYYY\");\n Date result = sdt.parse(date);\n System.out.println(result);\n }\n}"
},
{
"code": null,
"e": 1796,
"s": 1767,
"text": "Sun Jan 01 00:00:00 IST 2017"
}
]
|
What is the usage of onblur event in JavaScript? | The blur event triggers when object lose focus. You can try to run the following code to learn how to implement onblur event in JavaScript.
<!DOCTYPE html>
<html>
<body>
<p>Write below:</p>
<input type = "text" onblur = "newFunc(this)">
<script>
function newFunc(a) {
a.style.background = "green";
}
</script>
</body>
</html> | [
{
"code": null,
"e": 1202,
"s": 1062,
"text": "The blur event triggers when object lose focus. You can try to run the following code to learn how to implement onblur event in JavaScript."
},
{
"code": null,
"e": 1448,
"s": 1202,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <p>Write below:</p>\n <input type = \"text\" onblur = \"newFunc(this)\">\n <script>\n function newFunc(a) {\n a.style.background = \"green\";\n }\n </script>\n </body>\n</html>"
}
]
|
Building Basic Test in Cypress | Once Cypress installation is done and the test runner is successfully set up we shall create a JavaScript file under the examples folder. This comes under the integration folder provided by the Cypress framework template.
In order to create a Cypress test, we need to follow any of the Javascript testing
frameworks like Jasmine or Macha. We have to implement our Cypress test and
make it runnable with the help of these frameworks.
Mocha framework gets by default bundled with the Cypress installation. We shall
follow the rules listed below as supported by Mocha or Jasmine framework −
First we should have a test suite block containing single or multiple test
cases. This is achieved with describe function.
First we should have a test suite block containing single or multiple test
cases. This is achieved with describe function.
Inside the test suite we shall have the test case block. This is achieved with
the help of the it () function.
Inside the test suite we shall have the test case block. This is achieved with
the help of the it () function.
Inside each it function, we shall have the individual test step for each test
case.
Inside each it function, we shall have the individual test step for each test
case.
Code Implementation.
// test suite
describe('Tutorialspoint Test', function () {
// test case
it('Test Case1', function (){
// test step to launch a URL
cy.visit("https://www.tutorialspoint.com/index.htm");
});
});
In the above code, cy is a global command which enables us to invoke any Cypress command. This cy does not require any object declaration and it comes automatically on downloading node modules. The visit() method is used to launch any web application.
Once completed, we shall find this JavaScript file in the test runner and we can run
the test case from there by simply clicking on it.
To run the test case from the command line, we need to run the command ./node_modules/.bin/cypress run. If this command is executed all the test cases under the examples folder get triggered. However if we want to run a specific test case, we need to run the command cypress run –spec "<<path of the spec file>>".
Please note, while running from command line, Cypress test case runs in headless
mode and in Electron browser automatically.
To run the same test case in headed mode, the command is ./node_modules/.bin/cypress run -- headed.
Now let us discuss the folder structure that we have on Cypress Test Framework.
Fixtures − All the test data information is stored in fixtures so that they can
be easily loaded to our test case. The data is stored here in the form of a keyvalue
pair. Thus it helps to reduce lines of code to a large extent.
Fixtures − All the test data information is stored in fixtures so that they can
be easily loaded to our test case. The data is stored here in the form of a keyvalue
pair. Thus it helps to reduce lines of code to a large extent.
Integration − All the test cases are created inside the integration folder.
Integration − All the test cases are created inside the integration folder.
Plugins – This folder contains all the Cypress events. We can have customized
code to handle the before and after events.
Plugins – This folder contains all the Cypress events. We can have customized
code to handle the before and after events.
Support − All the reusable methods are created inside the support folder so
that they are available directly to the test cases.
Support − All the reusable methods are created inside the support folder so
that they are available directly to the test cases.
Videos − All the test step execution are recorded and stored in this folder.
Videos − All the test step execution are recorded and stored in this folder.
node_modules − This is the main folder for Cypress test execution.
node_modules − This is the main folder for Cypress test execution.
cypress.json − To change the default Cypress configuration, this folder is
used. We need to set the new configuration here and this will override the
default configuration.
cypress.json − To change the default Cypress configuration, this folder is
used. We need to set the new configuration here and this will override the
default configuration.
package.json − All the project dependencies and scripts are contained here.
package.json − All the project dependencies and scripts are contained here. | [
{
"code": null,
"e": 1284,
"s": 1062,
"text": "Once Cypress installation is done and the test runner is successfully set up we shall create a JavaScript file under the examples folder. This comes under the integration folder provided by the Cypress framework template."
},
{
"code": null,
"e": 1495,
"s": 1284,
"text": "In order to create a Cypress test, we need to follow any of the Javascript testing\nframeworks like Jasmine or Macha. We have to implement our Cypress test and\nmake it runnable with the help of these frameworks."
},
{
"code": null,
"e": 1650,
"s": 1495,
"text": "Mocha framework gets by default bundled with the Cypress installation. We shall\nfollow the rules listed below as supported by Mocha or Jasmine framework −"
},
{
"code": null,
"e": 1773,
"s": 1650,
"text": "First we should have a test suite block containing single or multiple test\ncases. This is achieved with describe function."
},
{
"code": null,
"e": 1896,
"s": 1773,
"text": "First we should have a test suite block containing single or multiple test\ncases. This is achieved with describe function."
},
{
"code": null,
"e": 2007,
"s": 1896,
"text": "Inside the test suite we shall have the test case block. This is achieved with\nthe help of the it () function."
},
{
"code": null,
"e": 2118,
"s": 2007,
"text": "Inside the test suite we shall have the test case block. This is achieved with\nthe help of the it () function."
},
{
"code": null,
"e": 2202,
"s": 2118,
"text": "Inside each it function, we shall have the individual test step for each test\ncase."
},
{
"code": null,
"e": 2286,
"s": 2202,
"text": "Inside each it function, we shall have the individual test step for each test\ncase."
},
{
"code": null,
"e": 2307,
"s": 2286,
"text": "Code Implementation."
},
{
"code": null,
"e": 2522,
"s": 2307,
"text": "// test suite\ndescribe('Tutorialspoint Test', function () {\n // test case\n it('Test Case1', function (){\n // test step to launch a URL\n cy.visit(\"https://www.tutorialspoint.com/index.htm\");\n });\n});"
},
{
"code": null,
"e": 2774,
"s": 2522,
"text": "In the above code, cy is a global command which enables us to invoke any Cypress command. This cy does not require any object declaration and it comes automatically on downloading node modules. The visit() method is used to launch any web application."
},
{
"code": null,
"e": 2910,
"s": 2774,
"text": "Once completed, we shall find this JavaScript file in the test runner and we can run\nthe test case from there by simply clicking on it."
},
{
"code": null,
"e": 3224,
"s": 2910,
"text": "To run the test case from the command line, we need to run the command ./node_modules/.bin/cypress run. If this command is executed all the test cases under the examples folder get triggered. However if we want to run a specific test case, we need to run the command cypress run –spec \"<<path of the spec file>>\"."
},
{
"code": null,
"e": 3349,
"s": 3224,
"text": "Please note, while running from command line, Cypress test case runs in headless\nmode and in Electron browser automatically."
},
{
"code": null,
"e": 3449,
"s": 3349,
"text": "To run the same test case in headed mode, the command is ./node_modules/.bin/cypress run -- headed."
},
{
"code": null,
"e": 3529,
"s": 3449,
"text": "Now let us discuss the folder structure that we have on Cypress Test Framework."
},
{
"code": null,
"e": 3757,
"s": 3529,
"text": "Fixtures − All the test data information is stored in fixtures so that they can\nbe easily loaded to our test case. The data is stored here in the form of a keyvalue\npair. Thus it helps to reduce lines of code to a large extent."
},
{
"code": null,
"e": 3985,
"s": 3757,
"text": "Fixtures − All the test data information is stored in fixtures so that they can\nbe easily loaded to our test case. The data is stored here in the form of a keyvalue\npair. Thus it helps to reduce lines of code to a large extent."
},
{
"code": null,
"e": 4061,
"s": 3985,
"text": "Integration − All the test cases are created inside the integration folder."
},
{
"code": null,
"e": 4137,
"s": 4061,
"text": "Integration − All the test cases are created inside the integration folder."
},
{
"code": null,
"e": 4259,
"s": 4137,
"text": "Plugins – This folder contains all the Cypress events. We can have customized\ncode to handle the before and after events."
},
{
"code": null,
"e": 4381,
"s": 4259,
"text": "Plugins – This folder contains all the Cypress events. We can have customized\ncode to handle the before and after events."
},
{
"code": null,
"e": 4509,
"s": 4381,
"text": "Support − All the reusable methods are created inside the support folder so\nthat they are available directly to the test cases."
},
{
"code": null,
"e": 4637,
"s": 4509,
"text": "Support − All the reusable methods are created inside the support folder so\nthat they are available directly to the test cases."
},
{
"code": null,
"e": 4714,
"s": 4637,
"text": "Videos − All the test step execution are recorded and stored in this folder."
},
{
"code": null,
"e": 4791,
"s": 4714,
"text": "Videos − All the test step execution are recorded and stored in this folder."
},
{
"code": null,
"e": 4858,
"s": 4791,
"text": "node_modules − This is the main folder for Cypress test execution."
},
{
"code": null,
"e": 4925,
"s": 4858,
"text": "node_modules − This is the main folder for Cypress test execution."
},
{
"code": null,
"e": 5098,
"s": 4925,
"text": "cypress.json − To change the default Cypress configuration, this folder is\nused. We need to set the new configuration here and this will override the\ndefault configuration."
},
{
"code": null,
"e": 5271,
"s": 5098,
"text": "cypress.json − To change the default Cypress configuration, this folder is\nused. We need to set the new configuration here and this will override the\ndefault configuration."
},
{
"code": null,
"e": 5347,
"s": 5271,
"text": "package.json − All the project dependencies and scripts are contained here."
},
{
"code": null,
"e": 5423,
"s": 5347,
"text": "package.json − All the project dependencies and scripts are contained here."
}
]
|
R - Web Data | Many websites provide data for consumption by its users. For example the World Health Organization(WHO) provides reports on health and medical information in the form of CSV, txt and XML files. Using R programs, we can programmatically extract specific data from such websites. Some packages in R which are used to scrap data form the web are − "RCurl",XML", and "stringr". They are used to connect to the URL’s, identify required links for the files and download them to the local environment.
The following packages are required for processing the URL’s and links to the files. If they are not available in your R Environment, you can install them using following commands.
install.packages("RCurl")
install.packages("XML")
install.packages("stringr")
install.packages("plyr")
We will visit the URL weather data and download the CSV files using R for the year 2015.
We will use the function getHTMLLinks() to gather the URLs of the files. Then we will use the function download.file() to save the files to the local system. As we will be applying the same code again and again for multiple files, we will create a function to be called multiple times. The filenames are passed as parameters in form of a R list object to this function.
# Read the URL.
url <- "http://www.geos.ed.ac.uk/~weather/jcmb_ws/"
# Gather the html links present in the webpage.
links <- getHTMLLinks(url)
# Identify only the links which point to the JCMB 2015 files.
filenames <- links[str_detect(links, "JCMB_2015")]
# Store the file names as a list.
filenames_list <- as.list(filenames)
# Create a function to download the files by passing the URL and filename list.
downloadcsv <- function (mainurl,filename) {
filedetails <- str_c(mainurl,filename)
download.file(filedetails,filename)
}
# Now apply the l_ply function and save the files into the current R working directory.
l_ply(filenames,downloadcsv,mainurl = "http://www.geos.ed.ac.uk/~weather/jcmb_ws/")
After running the above code, you can locate the following files in the current R working directory.
"JCMB_2015.csv" "JCMB_2015_Apr.csv" "JCMB_2015_Feb.csv" "JCMB_2015_Jan.csv"
"JCMB_2015_Mar.csv"
12 Lectures
2 hours
Nishant Malik
10 Lectures
1.5 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
20 Lectures
2 hours
Asif Hussain
10 Lectures
1.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2897,
"s": 2402,
"text": "Many websites provide data for consumption by its users. For example the World Health Organization(WHO) provides reports on health and medical information in the form of CSV, txt and XML files. Using R programs, we can programmatically extract specific data from such websites. Some packages in R which are used to scrap data form the web are − \"RCurl\",XML\", and \"stringr\". They are used to connect to the URL’s, identify required links for the files and download them to the local environment."
},
{
"code": null,
"e": 3078,
"s": 2897,
"text": "The following packages are required for processing the URL’s and links to the files. If they are not available in your R Environment, you can install them using following commands."
},
{
"code": null,
"e": 3182,
"s": 3078,
"text": "install.packages(\"RCurl\")\ninstall.packages(\"XML\")\ninstall.packages(\"stringr\")\ninstall.packages(\"plyr\")\n"
},
{
"code": null,
"e": 3271,
"s": 3182,
"text": "We will visit the URL weather data and download the CSV files using R for the year 2015."
},
{
"code": null,
"e": 3641,
"s": 3271,
"text": "We will use the function getHTMLLinks() to gather the URLs of the files. Then we will use the function download.file() to save the files to the local system. As we will be applying the same code again and again for multiple files, we will create a function to be called multiple times. The filenames are passed as parameters in form of a R list object to this function."
},
{
"code": null,
"e": 4354,
"s": 3641,
"text": "# Read the URL.\nurl <- \"http://www.geos.ed.ac.uk/~weather/jcmb_ws/\"\n\n# Gather the html links present in the webpage.\nlinks <- getHTMLLinks(url)\n\n# Identify only the links which point to the JCMB 2015 files. \nfilenames <- links[str_detect(links, \"JCMB_2015\")]\n\n# Store the file names as a list.\nfilenames_list <- as.list(filenames)\n\n# Create a function to download the files by passing the URL and filename list.\ndownloadcsv <- function (mainurl,filename) {\n filedetails <- str_c(mainurl,filename)\n download.file(filedetails,filename)\n}\n\n# Now apply the l_ply function and save the files into the current R working directory.\nl_ply(filenames,downloadcsv,mainurl = \"http://www.geos.ed.ac.uk/~weather/jcmb_ws/\")"
},
{
"code": null,
"e": 4455,
"s": 4354,
"text": "After running the above code, you can locate the following files in the current R working directory."
},
{
"code": null,
"e": 4555,
"s": 4455,
"text": "\"JCMB_2015.csv\" \"JCMB_2015_Apr.csv\" \"JCMB_2015_Feb.csv\" \"JCMB_2015_Jan.csv\"\n \"JCMB_2015_Mar.csv\"\n"
},
{
"code": null,
"e": 4588,
"s": 4555,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4603,
"s": 4588,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4638,
"s": 4603,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4653,
"s": 4638,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4688,
"s": 4653,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4703,
"s": 4688,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4736,
"s": 4703,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4750,
"s": 4736,
"text": " Asif Hussain"
},
{
"code": null,
"e": 4785,
"s": 4750,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4800,
"s": 4785,
"text": " Nishant Malik"
},
{
"code": null,
"e": 4835,
"s": 4800,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 4849,
"s": 4835,
"text": " Asif Hussain"
},
{
"code": null,
"e": 4856,
"s": 4849,
"text": " Print"
},
{
"code": null,
"e": 4867,
"s": 4856,
"text": " Add Notes"
}
]
|
JavaScript undefined Property - GeeksforGeeks | 06 Jul, 2020
Below is the example of the undefined Property.
Example:<script> var a ="Geeksforgeeks" function test() { if (typeof a === "undefined") { txt = "'a' is undefined"; } else { txt = "'a' is defined"; } document.write(txt); } test();</script>
<script> var a ="Geeksforgeeks" function test() { if (typeof a === "undefined") { txt = "'a' is undefined"; } else { txt = "'a' is defined"; } document.write(txt); } test();</script>
Output:'a' is defined
'a' is defined
The undefined property is used to check if a value is assigned to a variable or not.
Syntax:
var x;
if (typeof x === "undefined") {
txt = "x is undefined";
} else {
txt = "x is defined";
}
Return Value: It returns ‘defined’ if the variable is assigned any value and ‘undefined’ if the variable is not assigned any value.
More example code for the above property are as follows:Program 1:
<!DOCTYPE html><html> <body> <center> <h1 style="color: green"> GeeksforGeeks </h1> <button onclick="test()"> Press </button> <h4> Click on the Press button to check if "a" is defined or undefined. </h4> <p id="gfg"></p> <script> function test() { if (typeof a === "undefined") { txt = "'a' is undefined"; } else { txt = "'a' is defined"; } document.getElementById( "gfg").innerHTML = txt; } </script> </center></body> </html>
Output:
Supported Browsers:
Google Chrome
Firefox
Internet Explorer
Opera
Safari
JavaScript-Properties
Picked
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
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Remove elements from a JavaScript Array
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25300,
"s": 25272,
"text": "\n06 Jul, 2020"
},
{
"code": null,
"e": 25348,
"s": 25300,
"text": "Below is the example of the undefined Property."
},
{
"code": null,
"e": 25601,
"s": 25348,
"text": "Example:<script> var a =\"Geeksforgeeks\" function test() { if (typeof a === \"undefined\") { txt = \"'a' is undefined\"; } else { txt = \"'a' is defined\"; } document.write(txt); } test();</script>"
},
{
"code": "<script> var a =\"Geeksforgeeks\" function test() { if (typeof a === \"undefined\") { txt = \"'a' is undefined\"; } else { txt = \"'a' is defined\"; } document.write(txt); } test();</script>",
"e": 25846,
"s": 25601,
"text": null
},
{
"code": null,
"e": 25868,
"s": 25846,
"text": "Output:'a' is defined"
},
{
"code": null,
"e": 25883,
"s": 25868,
"text": "'a' is defined"
},
{
"code": null,
"e": 25968,
"s": 25883,
"text": "The undefined property is used to check if a value is assigned to a variable or not."
},
{
"code": null,
"e": 25976,
"s": 25968,
"text": "Syntax:"
},
{
"code": null,
"e": 26076,
"s": 25976,
"text": "var x;\nif (typeof x === \"undefined\") {\n txt = \"x is undefined\";\n} else {\n txt = \"x is defined\";\n}"
},
{
"code": null,
"e": 26208,
"s": 26076,
"text": "Return Value: It returns ‘defined’ if the variable is assigned any value and ‘undefined’ if the variable is not assigned any value."
},
{
"code": null,
"e": 26275,
"s": 26208,
"text": "More example code for the above property are as follows:Program 1:"
},
{
"code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color: green\"> GeeksforGeeks </h1> <button onclick=\"test()\"> Press </button> <h4> Click on the Press button to check if \"a\" is defined or undefined. </h4> <p id=\"gfg\"></p> <script> function test() { if (typeof a === \"undefined\") { txt = \"'a' is undefined\"; } else { txt = \"'a' is defined\"; } document.getElementById( \"gfg\").innerHTML = txt; } </script> </center></body> </html>",
"e": 26925,
"s": 26275,
"text": null
},
{
"code": null,
"e": 26933,
"s": 26925,
"text": "Output:"
},
{
"code": null,
"e": 26953,
"s": 26933,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 26967,
"s": 26953,
"text": "Google Chrome"
},
{
"code": null,
"e": 26975,
"s": 26967,
"text": "Firefox"
},
{
"code": null,
"e": 26993,
"s": 26975,
"text": "Internet Explorer"
},
{
"code": null,
"e": 26999,
"s": 26993,
"text": "Opera"
},
{
"code": null,
"e": 27006,
"s": 26999,
"text": "Safari"
},
{
"code": null,
"e": 27028,
"s": 27006,
"text": "JavaScript-Properties"
},
{
"code": null,
"e": 27035,
"s": 27028,
"text": "Picked"
},
{
"code": null,
"e": 27046,
"s": 27035,
"text": "JavaScript"
},
{
"code": null,
"e": 27063,
"s": 27046,
"text": "Web Technologies"
},
{
"code": null,
"e": 27161,
"s": 27063,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27222,
"s": 27161,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27263,
"s": 27222,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27317,
"s": 27263,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27365,
"s": 27317,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 27405,
"s": 27365,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27447,
"s": 27405,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27480,
"s": 27447,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27523,
"s": 27480,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27585,
"s": 27523,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
]
|
How to use Boto3 to check the statusof all the runsof a given Glue Job? | Problem Statement − Use boto3 library in Python to check statuses of all runs of a given job.
Example − Get the status of all runs of a glue job named as ‘run_s3_file_job’.
Step 1 − Import boto3 and botocore exceptions to handle exceptions.
Step 2 − job_name is the mandatory parameters. The function will fetch the details of a given job_name.
Step 3 − Create an AWS session using boto3 library. Make sure region_name is mentioned in default profile. If it is not mentioned, then explicitly pass the region_name while creating the session.
Step 4 − Create an AWS client for glue.
Step 5 − Now use get_job_runs function and pass the job_name as JobName parameter.
Step 6 − It fetches the details of all past job runs of the given job.
Step 7 − Use for loop to get details of specific job runs one by one.
Step 8 − Now, get the specific status of the job and corresponding job run id. Status could be Running if the job is not completed, else SUCCEEDED/FAILED.
Step 9 − Handle the generic exception if something went wrong while checking the job.
Use the following code to check statuses of all runs of a given job −
import boto3
from botocore.exceptions import ClientError
def get_status_of_job_all_runs(job_name):
session = boto3.session.Session()
glue_client = session.client('glue')
try:
response = glue_client.get_job_runs(JobName=job_name)
for res in response['JobRuns']:
print("Job Run id is:"+res.get("Id"))
print("status is:"+res.get("JobRunState"))
except ClientError as e:
raise Exception("boto3 client error in get_status_of_job_all_runs: " + e.__str__())
except Exception as e:
raise Exception("Unexpected error in get_status_of_job_all_runs: " + e.__str__())
get_status_of_job_all_runs("run_s3_file_job"))
job id
is:jr_6ef92e90ad66b1a6c7abb1c2659d114a34962b8c6ae4bf9b328ac90b99a33b7d
status is:FAILED
job id
is:jr_9fef13265036406e03e7cae79257305353203ab20b5f400e0c429e10a4999dba
status is:FAILED
job id
is:jr_f9d715a33e83460fc2ef6dee0840a98ef52c06c2ff569627633c4505fda7d835
status is:FAILED
job id
is:jr_71b57633ac4d8c24f904f0ae01f613f6d54baee440d0ede23f6030cffb0bf4d7
status is:FAILED
job id
is:jr_b7ead6b6ae43da2580888c73d6896c177510df73bd77c843d3e77b4dc5f22e2f
status is:FAILED
job id
is:jr_6e757509d51066648d49c22a47c26e728d6f842a1c5d2fd4f41941ca868460e6
status is:FAILED
job id
is:jr_89c1a7b8ea045fac36d25733d7fc657d3560eb159e7e122a8960981dd225a9d0
status is:FAILED
job id
is:jr_87522bcb924e41a6cf0294185b0a09e46a4ff4c67db5007ff7c10f959836a44b
status is:FAILED
job id
is:jr_08bb54854c8e5c60e96a3e2bade1184963973c1ea7a1e760029e740d4c4c5d7d
status is:FAILED
job id
is:jr_540a90407bb7fbde72b3e1d6cbc98c3b246c21c87d836ff389491bf95520bb41
status is:FAILED
job id
is:jr_f27227cb16ec9d3df665d8753b09c2e2d24d5b5e5263f3d3f17a9bd4669bee67
status is:FAILED
job id
is:jr_a1ae4ad2edcbdac5c948b8be92a79a37c27517113364ddc88c8a93bc712fe6c1
status is:SUCCEEDED | [
{
"code": null,
"e": 1156,
"s": 1062,
"text": "Problem Statement − Use boto3 library in Python to check statuses of all runs of a given job."
},
{
"code": null,
"e": 1235,
"s": 1156,
"text": "Example − Get the status of all runs of a glue job named as ‘run_s3_file_job’."
},
{
"code": null,
"e": 1303,
"s": 1235,
"text": "Step 1 − Import boto3 and botocore exceptions to handle exceptions."
},
{
"code": null,
"e": 1407,
"s": 1303,
"text": "Step 2 − job_name is the mandatory parameters. The function will fetch the details of a given job_name."
},
{
"code": null,
"e": 1603,
"s": 1407,
"text": "Step 3 − Create an AWS session using boto3 library. Make sure region_name is mentioned in default profile. If it is not mentioned, then explicitly pass the region_name while creating the session."
},
{
"code": null,
"e": 1643,
"s": 1603,
"text": "Step 4 − Create an AWS client for glue."
},
{
"code": null,
"e": 1726,
"s": 1643,
"text": "Step 5 − Now use get_job_runs function and pass the job_name as JobName parameter."
},
{
"code": null,
"e": 1797,
"s": 1726,
"text": "Step 6 − It fetches the details of all past job runs of the given job."
},
{
"code": null,
"e": 1867,
"s": 1797,
"text": "Step 7 − Use for loop to get details of specific job runs one by one."
},
{
"code": null,
"e": 2022,
"s": 1867,
"text": "Step 8 − Now, get the specific status of the job and corresponding job run id. Status could be Running if the job is not completed, else SUCCEEDED/FAILED."
},
{
"code": null,
"e": 2108,
"s": 2022,
"text": "Step 9 − Handle the generic exception if something went wrong while checking the job."
},
{
"code": null,
"e": 2178,
"s": 2108,
"text": "Use the following code to check statuses of all runs of a given job −"
},
{
"code": null,
"e": 2839,
"s": 2178,
"text": "import boto3\nfrom botocore.exceptions import ClientError\n\ndef get_status_of_job_all_runs(job_name):\n session = boto3.session.Session()\n glue_client = session.client('glue')\n try:\n response = glue_client.get_job_runs(JobName=job_name)\n for res in response['JobRuns']:\n print(\"Job Run id is:\"+res.get(\"Id\"))\n print(\"status is:\"+res.get(\"JobRunState\"))\n except ClientError as e:\n raise Exception(\"boto3 client error in get_status_of_job_all_runs: \" + e.__str__())\n except Exception as e:\n raise Exception(\"Unexpected error in get_status_of_job_all_runs: \" + e.__str__())\nget_status_of_job_all_runs(\"run_s3_file_job\"))"
},
{
"code": null,
"e": 3982,
"s": 2839,
"text": "job id\nis:jr_6ef92e90ad66b1a6c7abb1c2659d114a34962b8c6ae4bf9b328ac90b99a33b7d\nstatus is:FAILED\njob id\nis:jr_9fef13265036406e03e7cae79257305353203ab20b5f400e0c429e10a4999dba\nstatus is:FAILED\njob id\nis:jr_f9d715a33e83460fc2ef6dee0840a98ef52c06c2ff569627633c4505fda7d835\nstatus is:FAILED\njob id\nis:jr_71b57633ac4d8c24f904f0ae01f613f6d54baee440d0ede23f6030cffb0bf4d7\nstatus is:FAILED\njob id\nis:jr_b7ead6b6ae43da2580888c73d6896c177510df73bd77c843d3e77b4dc5f22e2f\nstatus is:FAILED\njob id\nis:jr_6e757509d51066648d49c22a47c26e728d6f842a1c5d2fd4f41941ca868460e6\nstatus is:FAILED\njob id\nis:jr_89c1a7b8ea045fac36d25733d7fc657d3560eb159e7e122a8960981dd225a9d0\nstatus is:FAILED\njob id\nis:jr_87522bcb924e41a6cf0294185b0a09e46a4ff4c67db5007ff7c10f959836a44b\nstatus is:FAILED\njob id\nis:jr_08bb54854c8e5c60e96a3e2bade1184963973c1ea7a1e760029e740d4c4c5d7d\nstatus is:FAILED\njob id\nis:jr_540a90407bb7fbde72b3e1d6cbc98c3b246c21c87d836ff389491bf95520bb41\nstatus is:FAILED\njob id\nis:jr_f27227cb16ec9d3df665d8753b09c2e2d24d5b5e5263f3d3f17a9bd4669bee67\nstatus is:FAILED\njob id\nis:jr_a1ae4ad2edcbdac5c948b8be92a79a37c27517113364ddc88c8a93bc712fe6c1\nstatus is:SUCCEEDED"
}
]
|
SQL Tryit Editor v1.6 | SELECT TOP 3 * FROM Customers;
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data. | [
{
"code": null,
"e": 31,
"s": 0,
"text": "SELECT TOP 3 * FROM Customers;"
},
{
"code": null,
"e": 33,
"s": 31,
"text": ""
},
{
"code": null,
"e": 96,
"s": 33,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 156,
"s": 96,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 224,
"s": 156,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 262,
"s": 224,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 347,
"s": 262,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 521,
"s": 347,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 572,
"s": 521,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 640,
"s": 572,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 811,
"s": 640,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 911,
"s": 811,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 971,
"s": 911,
"text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)."
}
]
|
How to find Size of std::forward_list in C++ STL - GeeksforGeeks | 08 Oct, 2021
Forward list in standard template library of C++. It comes under #include<forward_list> header file. It is implemented as a singly linked list. It was introduced in C++ 11 for the first time. Forward lists are sequence containers that allow constant time insert and erase operations from anywhere within the sequence. In the case of a forward list, fast random access is not supported.
Unlike other STL libraries, std::forward_list does not have any size() method. Hence, in this article, we will show you how to get the size of a std::forward_list in C++ STL.
There is a problem in retrieving the size of forward lists because std::forward_list doesn’t have any std::size() member function. To get the size of forward lists, one can use std::distance() function.
Approach:
Since std::distance() function takes two iterators as arguments and it returns an integer, the std::begin() and std::end() function can be passed which points to the address of the first item and the address just after the last item.
Syntax:
size = distance(forward_list.begin(), forward_list.end());
Below is the C++ code to implement the above approach:
C++14
// C++ program to implement// the above approach #include <forward_list>#include <iostream>using namespace std; // Driver codeint main(){ forward_list<int> l1 = { 3, 5, 6, 9, 6 }; // l.size() will throw an error, since // there is no size() method for // forward_list. So, to calculate the // size, we will use std::distance(iterator1, // iterator2), where iterator1 will be // l.begin() and iterator2 will be l.end() int size = distance(l1.begin(), l1.end()); cout << "Size of l1 is : " << size << endl; l1.remove(6); // It will erase all instances of 6 // from the list size = distance(l1.begin(), l1.end()); cout << "Size of l1, after removing all" << " instances of 6 is : " << size << endl; forward_list<int> l2 = { 6, 11, 0 }; int size2 = distance(l2.begin(), l2.end()); cout << "Size of l2, before assigning" << " it to l1 : " << size2 << endl; l1.splice_after(l1.begin(), l2); // It will assign l2 to l at the // provided iterator, making l1 // as empty. size = distance(l1.begin(), l1.end()); size2 = distance(l2.begin(), l2.end()); cout << "Size of l1, after assigning" << " l2 to it : " << size << endl; cout << "Size of l2, after assigning" << " it to l1 : " << size2 << endl;}
Size of l1 is : 5
Size of l1, after removing all instances of 6 is : 3
Size of l2, before assigning it to l1 : 3
Size of l1, after assigning l2 to it : 6
Size of l2, after assigning it to l1 : 0
surindertarika1234
CPP-forward-list
STL
C++
C++ Quiz
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
C++ | Exception Handling | Question 3
C++ | new and delete | Question 4
C++ | Inheritance | Question 7
C++ | Operator Overloading | Question 10
C++ | Inheritance | Question 1 | [
{
"code": null,
"e": 24123,
"s": 24095,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 24509,
"s": 24123,
"text": "Forward list in standard template library of C++. It comes under #include<forward_list> header file. It is implemented as a singly linked list. It was introduced in C++ 11 for the first time. Forward lists are sequence containers that allow constant time insert and erase operations from anywhere within the sequence. In the case of a forward list, fast random access is not supported."
},
{
"code": null,
"e": 24684,
"s": 24509,
"text": "Unlike other STL libraries, std::forward_list does not have any size() method. Hence, in this article, we will show you how to get the size of a std::forward_list in C++ STL."
},
{
"code": null,
"e": 24887,
"s": 24684,
"text": "There is a problem in retrieving the size of forward lists because std::forward_list doesn’t have any std::size() member function. To get the size of forward lists, one can use std::distance() function."
},
{
"code": null,
"e": 24897,
"s": 24887,
"text": "Approach:"
},
{
"code": null,
"e": 25131,
"s": 24897,
"text": "Since std::distance() function takes two iterators as arguments and it returns an integer, the std::begin() and std::end() function can be passed which points to the address of the first item and the address just after the last item."
},
{
"code": null,
"e": 25140,
"s": 25131,
"text": "Syntax: "
},
{
"code": null,
"e": 25201,
"s": 25140,
"text": "size = distance(forward_list.begin(), forward_list.end()); "
},
{
"code": null,
"e": 25258,
"s": 25203,
"text": "Below is the C++ code to implement the above approach:"
},
{
"code": null,
"e": 25264,
"s": 25258,
"text": "C++14"
},
{
"code": "// C++ program to implement// the above approach #include <forward_list>#include <iostream>using namespace std; // Driver codeint main(){ forward_list<int> l1 = { 3, 5, 6, 9, 6 }; // l.size() will throw an error, since // there is no size() method for // forward_list. So, to calculate the // size, we will use std::distance(iterator1, // iterator2), where iterator1 will be // l.begin() and iterator2 will be l.end() int size = distance(l1.begin(), l1.end()); cout << \"Size of l1 is : \" << size << endl; l1.remove(6); // It will erase all instances of 6 // from the list size = distance(l1.begin(), l1.end()); cout << \"Size of l1, after removing all\" << \" instances of 6 is : \" << size << endl; forward_list<int> l2 = { 6, 11, 0 }; int size2 = distance(l2.begin(), l2.end()); cout << \"Size of l2, before assigning\" << \" it to l1 : \" << size2 << endl; l1.splice_after(l1.begin(), l2); // It will assign l2 to l at the // provided iterator, making l1 // as empty. size = distance(l1.begin(), l1.end()); size2 = distance(l2.begin(), l2.end()); cout << \"Size of l1, after assigning\" << \" l2 to it : \" << size << endl; cout << \"Size of l2, after assigning\" << \" it to l1 : \" << size2 << endl;}",
"e": 26668,
"s": 25264,
"text": null
},
{
"code": null,
"e": 26863,
"s": 26668,
"text": "Size of l1 is : 5\nSize of l1, after removing all instances of 6 is : 3\nSize of l2, before assigning it to l1 : 3\nSize of l1, after assigning l2 to it : 6\nSize of l2, after assigning it to l1 : 0"
},
{
"code": null,
"e": 26884,
"s": 26865,
"text": "surindertarika1234"
},
{
"code": null,
"e": 26901,
"s": 26884,
"text": "CPP-forward-list"
},
{
"code": null,
"e": 26905,
"s": 26901,
"text": "STL"
},
{
"code": null,
"e": 26909,
"s": 26905,
"text": "C++"
},
{
"code": null,
"e": 26918,
"s": 26909,
"text": "C++ Quiz"
},
{
"code": null,
"e": 26922,
"s": 26918,
"text": "STL"
},
{
"code": null,
"e": 26926,
"s": 26922,
"text": "CPP"
},
{
"code": null,
"e": 27024,
"s": 26926,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27052,
"s": 27024,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27072,
"s": 27052,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 27096,
"s": 27072,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 27129,
"s": 27096,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 27173,
"s": 27129,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 27211,
"s": 27173,
"text": "C++ | Exception Handling | Question 3"
},
{
"code": null,
"e": 27245,
"s": 27211,
"text": "C++ | new and delete | Question 4"
},
{
"code": null,
"e": 27276,
"s": 27245,
"text": "C++ | Inheritance | Question 7"
},
{
"code": null,
"e": 27317,
"s": 27276,
"text": "C++ | Operator Overloading | Question 10"
}
]
|
p5.js | setup() Function - GeeksforGeeks | 23 Aug, 2019
The setup() function runs when the program starts. It is used to set the initial environment properties such as text-color, screen size, background-color and load the media file such as images and fonts. The program contains only one setup() function. The setup() function can not be called again after its initial execution.
Note: The variable declaration within setup() function can not be access by other functions including draw() function.
Syntax:
setup()
Below examples illustrate the setup() function in p5.js:
Example 1:
function setup() { // Create Canvas of given size createCanvas(400, 300); } function draw() { background(220); // Use color() function let c = color('green'); // Use fill() function to fill color fill(c); // Draw a rectangle rect(50, 50, 300, 200); }
Output:
Example 2:
function setup() { // Create Canvas of given size var cvs = createCanvas(600, 250);} function draw() { // Set the background color background('green'); // Use createDiv() function to // create a div element var myDiv = createDiv('GeeksforGeeks'); var myDiv1 = createDiv('A computer science portal for geeks'); // Use child() function myDiv.child(myDiv1); // Set the position of div element myDiv.position(150, 100); myDiv.style('text-align', 'center'); // Set the font-size of text myDiv.style('font-size', '24px'); // Set the font color myDiv.style('color', 'white'); }
Output:
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 43692,
"s": 43664,
"text": "\n23 Aug, 2019"
},
{
"code": null,
"e": 44018,
"s": 43692,
"text": "The setup() function runs when the program starts. It is used to set the initial environment properties such as text-color, screen size, background-color and load the media file such as images and fonts. The program contains only one setup() function. The setup() function can not be called again after its initial execution."
},
{
"code": null,
"e": 44137,
"s": 44018,
"text": "Note: The variable declaration within setup() function can not be access by other functions including draw() function."
},
{
"code": null,
"e": 44145,
"s": 44137,
"text": "Syntax:"
},
{
"code": null,
"e": 44153,
"s": 44145,
"text": "setup()"
},
{
"code": null,
"e": 44210,
"s": 44153,
"text": "Below examples illustrate the setup() function in p5.js:"
},
{
"code": null,
"e": 44221,
"s": 44210,
"text": "Example 1:"
},
{
"code": "function setup() { // Create Canvas of given size createCanvas(400, 300); } function draw() { background(220); // Use color() function let c = color('green'); // Use fill() function to fill color fill(c); // Draw a rectangle rect(50, 50, 300, 200); } ",
"e": 44545,
"s": 44221,
"text": null
},
{
"code": null,
"e": 44553,
"s": 44545,
"text": "Output:"
},
{
"code": null,
"e": 44564,
"s": 44553,
"text": "Example 2:"
},
{
"code": "function setup() { // Create Canvas of given size var cvs = createCanvas(600, 250);} function draw() { // Set the background color background('green'); // Use createDiv() function to // create a div element var myDiv = createDiv('GeeksforGeeks'); var myDiv1 = createDiv('A computer science portal for geeks'); // Use child() function myDiv.child(myDiv1); // Set the position of div element myDiv.position(150, 100); myDiv.style('text-align', 'center'); // Set the font-size of text myDiv.style('font-size', '24px'); // Set the font color myDiv.style('color', 'white'); }",
"e": 45242,
"s": 44564,
"text": null
},
{
"code": null,
"e": 45250,
"s": 45242,
"text": "Output:"
},
{
"code": null,
"e": 45267,
"s": 45250,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 45278,
"s": 45267,
"text": "JavaScript"
},
{
"code": null,
"e": 45295,
"s": 45278,
"text": "Web Technologies"
},
{
"code": null,
"e": 45393,
"s": 45295,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45438,
"s": 45393,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 45499,
"s": 45438,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 45568,
"s": 45499,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 45640,
"s": 45568,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 45692,
"s": 45640,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 45734,
"s": 45692,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 45767,
"s": 45734,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 45810,
"s": 45767,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 45872,
"s": 45810,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
]
|
Tryit Editor v3.7 | CSS Style Images
Tryit: Create a responsive image | [
{
"code": null,
"e": 26,
"s": 9,
"text": "CSS Style Images"
}
]
|
What are Hash Functions in block chain? | We know that bitcoins enter into the digital market only through mining. It is a cryptocurrency created as a peer-to-peer currency which can be traded without using any Bank or Payment gateway. When these transactions are made, they are accounted for using a publicly distributed ledger which keeps a record of all the transactions made to every Bitcoin.
Every time a transaction is made, a new block is created. Every new block will be verified and added into the block chain by the miners. Here comes the purpose of hash functions to make the block chain secure.
Hash is a process of converting input of any length of string into a fixed length of text using a mathematical algorithm. Whatever may be the size of input, it will only produce a fixed length of output.
Input + Mathematical algorithm (Hash function) = Hash value
In cryptocurrency, SHA 256 (Secure Hashing Algorithm with 256 bits) or SHA512 are used to create the hash values.
There are few specific features of Hash value −
Always the same input will create same hash value. Even a small change will create a new hash.Hello World :d2a84f4b8b650937ec8f73cd8be2c74add5a911ba64df27458ed8229da804a26Hello World :1894a19c85ba153acbf743ac4e43fc004c891604b26f8c69e1e83ea2afc7c48fHere we can see that even a small change in the case of alphabet “w” has produced entirely different hash value. This makes the hash value unique and unmitigated and secure.
Always the same input will create same hash value. Even a small change will create a new hash.
Hello World :
d2a84f4b8b650937ec8f73cd8be2c74add5a911ba64df27458ed8229da804a26
Hello World :
1894a19c85ba153acbf743ac4e43fc004c891604b26f8c69e1e83ea2afc7c48f
Here we can see that even a small change in the case of alphabet “w” has produced entirely different hash value. This makes the hash value unique and unmitigated and secure.
Any length of input will always create the same length of text in hash value.
Any length of input will always create the same length of text in hash value.
The speed at which the hash value is created also matters in block chains.
The speed at which the hash value is created also matters in block chains.
Hash values are highly secure. It is extremely impossible to get the input value from the output. It is also an irreversible and one-way process. You will lose the entire input data once the data passes through hash function and a hash value is created
Hash values are highly secure. It is extremely impossible to get the input value from the output. It is also an irreversible and one-way process. You will lose the entire input data once the data passes through hash function and a hash value is created
In a block chain hashes are used to connect the blocks to each other and create the chain. Every new block added to block chain will have the details of the transaction - Amount, address of sender and receiver, time stamp and most importantly the previous block’s (transaction) information stored as a hash value. This entire information again converts into a Transaction ID, which is the hash value of that particular block.
The previous block information + current block’s transactions = Hash value of current block.
In this manner it creates an unbreakable dependency. Based on the Hash value of the current block you can trace previous and next block. Thus hash functions make the block chain a secure, immutable and transparent network, which is the core of cryptocurrency. The concept of hashing has made the block chains revolutionary and unique. | [
{
"code": null,
"e": 1417,
"s": 1062,
"text": "We know that bitcoins enter into the digital market only through mining. It is a cryptocurrency created as a peer-to-peer currency which can be traded without using any Bank or Payment gateway. When these transactions are made, they are accounted for using a publicly distributed ledger which keeps a record of all the transactions made to every Bitcoin."
},
{
"code": null,
"e": 1627,
"s": 1417,
"text": "Every time a transaction is made, a new block is created. Every new block will be verified and added into the block chain by the miners. Here comes the purpose of hash functions to make the block chain secure."
},
{
"code": null,
"e": 1831,
"s": 1627,
"text": "Hash is a process of converting input of any length of string into a fixed length of text using a mathematical algorithm. Whatever may be the size of input, it will only produce a fixed length of output."
},
{
"code": null,
"e": 1891,
"s": 1831,
"text": "Input + Mathematical algorithm (Hash function) = Hash value"
},
{
"code": null,
"e": 2005,
"s": 1891,
"text": "In cryptocurrency, SHA 256 (Secure Hashing Algorithm with 256 bits) or SHA512 are used to create the hash values."
},
{
"code": null,
"e": 2053,
"s": 2005,
"text": "There are few specific features of Hash value −"
},
{
"code": null,
"e": 2475,
"s": 2053,
"text": "Always the same input will create same hash value. Even a small change will create a new hash.Hello World :d2a84f4b8b650937ec8f73cd8be2c74add5a911ba64df27458ed8229da804a26Hello World :1894a19c85ba153acbf743ac4e43fc004c891604b26f8c69e1e83ea2afc7c48fHere we can see that even a small change in the case of alphabet “w” has produced entirely different hash value. This makes the hash value unique and unmitigated and secure."
},
{
"code": null,
"e": 2570,
"s": 2475,
"text": "Always the same input will create same hash value. Even a small change will create a new hash."
},
{
"code": null,
"e": 2584,
"s": 2570,
"text": "Hello World :"
},
{
"code": null,
"e": 2649,
"s": 2584,
"text": "d2a84f4b8b650937ec8f73cd8be2c74add5a911ba64df27458ed8229da804a26"
},
{
"code": null,
"e": 2663,
"s": 2649,
"text": "Hello World :"
},
{
"code": null,
"e": 2728,
"s": 2663,
"text": "1894a19c85ba153acbf743ac4e43fc004c891604b26f8c69e1e83ea2afc7c48f"
},
{
"code": null,
"e": 2902,
"s": 2728,
"text": "Here we can see that even a small change in the case of alphabet “w” has produced entirely different hash value. This makes the hash value unique and unmitigated and secure."
},
{
"code": null,
"e": 2980,
"s": 2902,
"text": "Any length of input will always create the same length of text in hash value."
},
{
"code": null,
"e": 3058,
"s": 2980,
"text": "Any length of input will always create the same length of text in hash value."
},
{
"code": null,
"e": 3133,
"s": 3058,
"text": "The speed at which the hash value is created also matters in block chains."
},
{
"code": null,
"e": 3208,
"s": 3133,
"text": "The speed at which the hash value is created also matters in block chains."
},
{
"code": null,
"e": 3461,
"s": 3208,
"text": "Hash values are highly secure. It is extremely impossible to get the input value from the output. It is also an irreversible and one-way process. You will lose the entire input data once the data passes through hash function and a hash value is created"
},
{
"code": null,
"e": 3714,
"s": 3461,
"text": "Hash values are highly secure. It is extremely impossible to get the input value from the output. It is also an irreversible and one-way process. You will lose the entire input data once the data passes through hash function and a hash value is created"
},
{
"code": null,
"e": 4140,
"s": 3714,
"text": "In a block chain hashes are used to connect the blocks to each other and create the chain. Every new block added to block chain will have the details of the transaction - Amount, address of sender and receiver, time stamp and most importantly the previous block’s (transaction) information stored as a hash value. This entire information again converts into a Transaction ID, which is the hash value of that particular block."
},
{
"code": null,
"e": 4233,
"s": 4140,
"text": "The previous block information + current block’s transactions = Hash value of current block."
},
{
"code": null,
"e": 4568,
"s": 4233,
"text": "In this manner it creates an unbreakable dependency. Based on the Hash value of the current block you can trace previous and next block. Thus hash functions make the block chain a secure, immutable and transparent network, which is the core of cryptocurrency. The concept of hashing has made the block chains revolutionary and unique."
}
]
|
Comparator comparingInt() in Java with examples - GeeksforGeeks | 29 Apr, 2019
The comparingInt(java.util.function.ToIntFunction) method accepts a function as parameter that extracts an int sort key from a type T, and returns a Comparator that compares by that sort key.The returned comparator is serializable if the specified function is also serializable.
Syntax:
static <T> Comparator<T> comparingInt(ToIntFunction <T> keyExtractor)
Parameters: This method accepts a single parameter keyExtractor which is the function used to extract the integer sort key.
Return value: This method returns a comparator that compares by an extracted key
Exception: This method throws NullPointerException if the argument is null.
Below programs illustrate comparingInt(java.util.function.ToIntFunction) method:Program 1:
// Java program to demonstrate// Comparator.comparingInt(java.util.function.ToIntFunction) method import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import java.util.List;public class GFG { public static void main(String[] args) { // create some user objects User u1 = new User("Aaman", 25); User u2 = new User("Joyita", 22); User u3 = new User("Suvam", 28); User u4 = new User("mahafuj", 25); // before sort List<User> list = Arrays.asList(u2, u1, u4, u3); System.out.println("Before Sort:"); list.forEach(User -> System.out.println("User age " + User.getAge())); Collections.sort(list, Comparator.comparingInt( User::getAge)); System.out.println("\nAfterSort:"); list.forEach(User -> System.out.println("User age " + User.getAge())); }}class User implements Comparable<User> { public String name; public int age; public User(String name, int age) { this.name = name; this.age = age; } public int compareTo(User u1) { return name.compareTo(u1.name); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [name=" + name + ", age=" + age + "]"; }}
The output printed on console of IDE is shown below.Output:
Program 2:
// Java program to demonstrate// Comparator.comparingInt(java.util.function.ToIntFunction) method import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import java.util.List;public class GFG { public static void main(String[] args) { // before sort List<Order> list = Arrays.asList( new Order("A382y482y48", 320), new Order("Vvekhfbkje2", 242), new Order("efkhfbekjfbe", 1345), new Order("bhdhdfaddvad", 230), new Order("abkasbcjabjc", 100)); System.out.println("Before Sort:"); list.forEach(order -> System.out.println(order)); Collections.sort(list, Comparator.comparingInt( Order::getValue)); System.out.println("\nAfter Sort:"); list.forEach(order -> System.out.println(order)); }}class Order implements Comparable<Order> { public String orderNo; public int value; public int compareTo(Order o1) { return orderNo.compareTo(o1.orderNo); } public Order(String orderNo, int value) { super(); this.orderNo = orderNo; this.value = value; } @Override public String toString() { return "Order [orderNo=" + orderNo + ", value=" + value + "]"; } public String getOrderNo() { return orderNo; } public void setOrderNo(String orderNo) { this.orderNo = orderNo; } public int getValue() { return value; } public void setValue(int value) { this.value = value; }}
The output printed on console is shown below.Output:
References: https://docs.oracle.com/javase/10/docs/api/java/util/Comparator.html#comparingInt(java.util.function.ToIntFunction)
Java - util package
Java-Comparator
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stream In Java
Stack Class in Java
Singleton Class in Java | [
{
"code": null,
"e": 24514,
"s": 24486,
"text": "\n29 Apr, 2019"
},
{
"code": null,
"e": 24793,
"s": 24514,
"text": "The comparingInt(java.util.function.ToIntFunction) method accepts a function as parameter that extracts an int sort key from a type T, and returns a Comparator that compares by that sort key.The returned comparator is serializable if the specified function is also serializable."
},
{
"code": null,
"e": 24801,
"s": 24793,
"text": "Syntax:"
},
{
"code": null,
"e": 24872,
"s": 24801,
"text": "static <T> Comparator<T> comparingInt(ToIntFunction <T> keyExtractor)\n"
},
{
"code": null,
"e": 24996,
"s": 24872,
"text": "Parameters: This method accepts a single parameter keyExtractor which is the function used to extract the integer sort key."
},
{
"code": null,
"e": 25077,
"s": 24996,
"text": "Return value: This method returns a comparator that compares by an extracted key"
},
{
"code": null,
"e": 25153,
"s": 25077,
"text": "Exception: This method throws NullPointerException if the argument is null."
},
{
"code": null,
"e": 25244,
"s": 25153,
"text": "Below programs illustrate comparingInt(java.util.function.ToIntFunction) method:Program 1:"
},
{
"code": "// Java program to demonstrate// Comparator.comparingInt(java.util.function.ToIntFunction) method import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import java.util.List;public class GFG { public static void main(String[] args) { // create some user objects User u1 = new User(\"Aaman\", 25); User u2 = new User(\"Joyita\", 22); User u3 = new User(\"Suvam\", 28); User u4 = new User(\"mahafuj\", 25); // before sort List<User> list = Arrays.asList(u2, u1, u4, u3); System.out.println(\"Before Sort:\"); list.forEach(User -> System.out.println(\"User age \" + User.getAge())); Collections.sort(list, Comparator.comparingInt( User::getAge)); System.out.println(\"\\nAfterSort:\"); list.forEach(User -> System.out.println(\"User age \" + User.getAge())); }}class User implements Comparable<User> { public String name; public int age; public User(String name, int age) { this.name = name; this.age = age; } public int compareTo(User u1) { return name.compareTo(u1.name); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return \"User [name=\" + name + \", age=\" + age + \"]\"; }}",
"e": 26940,
"s": 25244,
"text": null
},
{
"code": null,
"e": 27000,
"s": 26940,
"text": "The output printed on console of IDE is shown below.Output:"
},
{
"code": null,
"e": 27011,
"s": 27000,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// Comparator.comparingInt(java.util.function.ToIntFunction) method import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import java.util.List;public class GFG { public static void main(String[] args) { // before sort List<Order> list = Arrays.asList( new Order(\"A382y482y48\", 320), new Order(\"Vvekhfbkje2\", 242), new Order(\"efkhfbekjfbe\", 1345), new Order(\"bhdhdfaddvad\", 230), new Order(\"abkasbcjabjc\", 100)); System.out.println(\"Before Sort:\"); list.forEach(order -> System.out.println(order)); Collections.sort(list, Comparator.comparingInt( Order::getValue)); System.out.println(\"\\nAfter Sort:\"); list.forEach(order -> System.out.println(order)); }}class Order implements Comparable<Order> { public String orderNo; public int value; public int compareTo(Order o1) { return orderNo.compareTo(o1.orderNo); } public Order(String orderNo, int value) { super(); this.orderNo = orderNo; this.value = value; } @Override public String toString() { return \"Order [orderNo=\" + orderNo + \", value=\" + value + \"]\"; } public String getOrderNo() { return orderNo; } public void setOrderNo(String orderNo) { this.orderNo = orderNo; } public int getValue() { return value; } public void setValue(int value) { this.value = value; }}",
"e": 28621,
"s": 27011,
"text": null
},
{
"code": null,
"e": 28674,
"s": 28621,
"text": "The output printed on console is shown below.Output:"
},
{
"code": null,
"e": 28802,
"s": 28674,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/util/Comparator.html#comparingInt(java.util.function.ToIntFunction)"
},
{
"code": null,
"e": 28822,
"s": 28802,
"text": "Java - util package"
},
{
"code": null,
"e": 28838,
"s": 28822,
"text": "Java-Comparator"
},
{
"code": null,
"e": 28853,
"s": 28838,
"text": "Java-Functions"
},
{
"code": null,
"e": 28858,
"s": 28853,
"text": "Java"
},
{
"code": null,
"e": 28863,
"s": 28858,
"text": "Java"
},
{
"code": null,
"e": 28961,
"s": 28863,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28993,
"s": 28961,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 29044,
"s": 28993,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 29074,
"s": 29044,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 29093,
"s": 29074,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29124,
"s": 29093,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 29142,
"s": 29124,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29174,
"s": 29142,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 29189,
"s": 29174,
"text": "Stream In Java"
},
{
"code": null,
"e": 29209,
"s": 29189,
"text": "Stack Class in Java"
}
]
|
How to remove rows that contain NAs in R matrix? | To remove rows that contain NAs in R matrix, we can follow the below steps −
First of all, create a matrix.
First of all, create a matrix.
Then, use na.omit function to remove rows that contains NAs.
Then, use na.omit function to remove rows that contains NAs.
Let’s create a matrix as shown below −
M<-matrix(sample(c(NA,rpois(10,5)),100,replace=TRUE),ncol=4)
M
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
[,1] [,2] [,3] [,4]
[1,] 4 4 2 NA
[2,] 4 NA NA 4
[3,] 4 4 4 6
[4,] 4 3 4 3
[5,] 4 4 4 4
[6,] 4 4 4 4
[7,] 4 4 4 6
[8,] NA 4 4 4
[9,] 4 4 2 4
[10,] 2 4 4 4
[11,] 6 4 NA 3
[12,] NA 3 4 4
[13,] 2 6 3 4
[14,] 4 4 4 NA
[15,] NA 4 4 4
[16,] 2 4 3 4
[17,] 4 2 4 4
[18,] 4 4 4 4
[19,] 4 4 NA 4
[20,] 4 4 4 4
[21,] 4 6 2 2
[22,] 3 4 2 4
[23,] 4 4 4 6
[24,] 4 NA 4 NA
[25,] NA 4 4 4
Remove rows that contains NAs
Using na.omit function to remove rows that contains NAs in matrix M −
M<-matrix(sample(c(NA,rpois(10,5)),100,replace=TRUE),ncol=4)
M<-na.omit(M)
M
[,1] [,2] [,3] [,4]
[1,] 4 4 4 6
[2,] 4 3 4 3
[3,] 4 4 4 4
[4,] 4 4 4 4
[5,] 4 4 4 6
[6,] 4 4 2 4
[7,] 2 4 4 4
[8,] 2 6 3 4
[9,] 2 4 3 4
[10,] 4 2 4 4
[11,] 4 4 4 4
[12,] 4 4 4 4
[13,] 4 6 2 2
[14,] 3 4 2 4
[15,] 4 4 4 6
attr(,"na.action")
[1] 8 12 15 25 2 24 11 19 1 14
attr(,"class")
[1] "omit" | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "To remove rows that contain NAs in R matrix, we can follow the below steps −"
},
{
"code": null,
"e": 1170,
"s": 1139,
"text": "First of all, create a matrix."
},
{
"code": null,
"e": 1201,
"s": 1170,
"text": "First of all, create a matrix."
},
{
"code": null,
"e": 1262,
"s": 1201,
"text": "Then, use na.omit function to remove rows that contains NAs."
},
{
"code": null,
"e": 1323,
"s": 1262,
"text": "Then, use na.omit function to remove rows that contains NAs."
},
{
"code": null,
"e": 1362,
"s": 1323,
"text": "Let’s create a matrix as shown below −"
},
{
"code": null,
"e": 1425,
"s": 1362,
"text": "M<-matrix(sample(c(NA,rpois(10,5)),100,replace=TRUE),ncol=4)\nM"
},
{
"code": null,
"e": 1544,
"s": 1425,
"text": "On executing, the above script generates the below output(this output will vary on your system due to randomization) −"
},
{
"code": null,
"e": 2121,
"s": 1544,
"text": " [,1] [,2] [,3] [,4]\n[1,] 4 4 2 NA\n[2,] 4 NA NA 4\n[3,] 4 4 4 6\n[4,] 4 3 4 3\n[5,] 4 4 4 4\n[6,] 4 4 4 4\n[7,] 4 4 4 6\n[8,] NA 4 4 4\n[9,] 4 4 2 4\n[10,] 2 4 4 4\n[11,] 6 4 NA 3\n[12,] NA 3 4 4\n[13,] 2 6 3 4\n[14,] 4 4 4 NA\n[15,] NA 4 4 4\n[16,] 2 4 3 4\n[17,] 4 2 4 4\n[18,] 4 4 4 4\n[19,] 4 4 NA 4\n[20,] 4 4 4 4\n[21,] 4 6 2 2\n[22,] 3 4 2 4\n[23,] 4 4 4 6\n[24,] 4 NA 4 NA\n[25,] NA 4 4 4"
},
{
"code": null,
"e": 2151,
"s": 2121,
"text": "Remove rows that contains NAs"
},
{
"code": null,
"e": 2221,
"s": 2151,
"text": "Using na.omit function to remove rows that contains NAs in matrix M −"
},
{
"code": null,
"e": 2298,
"s": 2221,
"text": "M<-matrix(sample(c(NA,rpois(10,5)),100,replace=TRUE),ncol=4)\nM<-na.omit(M)\nM"
},
{
"code": null,
"e": 2728,
"s": 2298,
"text": " [,1] [,2] [,3] [,4]\n[1,] 4 4 4 6\n[2,] 4 3 4 3\n[3,] 4 4 4 4\n[4,] 4 4 4 4\n[5,] 4 4 4 6\n[6,] 4 4 2 4\n[7,] 2 4 4 4\n[8,] 2 6 3 4\n[9,] 2 4 3 4\n[10,] 4 2 4 4\n[11,] 4 4 4 4\n[12,] 4 4 4 4\n[13,] 4 6 2 2\n[14,] 3 4 2 4\n[15,] 4 4 4 6\nattr(,\"na.action\")\n[1] 8 12 15 25 2 24 11 19 1 14\nattr(,\"class\")\n[1] \"omit\""
}
]
|
How to create a linear model with interaction term only in R? | To create a linear model with interaction term only, we can use the interaction variable while creating the model. For example, if we have a data frame called df that has two independent variables say V1 and V2 and one dependent variable Y then the linear model with interaction term only can be created as lm(Y~V1:V2,data=df).
Consider the below data frame −
Live Demo
x1<-rnorm(20,5,1.2)
x2<-rnorm(20,2,1.2)
y1<-rnorm(20,3,1.25)
df1<-data.frame(x1,x2,y1)
df1
x1 x2 y1
1 4.442636 2.63714281 0.9120181
2 5.912804 1.72409663 2.2746513
3 7.881736 3.48780844 3.2675991
4 6.145395 1.51225991 3.2177194
5 6.303181 4.34733534 3.3361897
6 5.689431 0.08564247 2.0863346
7 6.008397 1.30221198 2.7183725
8 6.580716 1.45239970 4.0301650
9 4.000381 3.71539569 3.9404225
10 5.535338 3.48976926 4.9557343
11 5.968661 2.18208048 3.9992293
12 4.783326 -0.90756376 4.2661775
13 3.843528 -0.50299042 0.6496255
14 6.034803 1.06019093 5.2339701
15 4.177977 1.70476660 2.5932408
16 5.746300 0.85021792 3.0145627
17 4.658000 1.49894326 5.2826538
18 3.797983 0.46900834 3.6511403
19 5.415130 -0.31811078 2.6574529
20 4.709443 2.72001915 1.8893078
Creating linear model for y1 with interaction between x1 and x2 −
Model1<-lm(y1~x1:x2,data=df1)
summary(Model1)
Call −
lm(formula = y1 ~ x1:x2, data = df1)
Residuals −
Min 1Q Median 3Q Max
-2.3517 -0.6387 -0.1708 0.7321 2.1390
Coefficients −
Estimate Std. Error t value Pr(>|t|)
(Intercept) 2.96669 0.42803 6.931 1.77e-06 ***
x1:x2 0.02535 0.03434 0.738 0.47
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 1.299 on 18 degrees of freedom
Multiple R-squared: 0.02939, Adjusted R-squared: -0.02454
F-statistic: 0.545 on 1 and 18 DF, p-value: 0.4699
Live Demo
v1<-rpois(20,2)
v2<-rpois(20,2)
v3<-rpois(20,2)
Response<-rpois(20,5)
df2<-data.frame(v1,v2,v3,Response)
df2
v1 v2 v3 Response
1 2 2 4 10
2 1 1 2 2
3 3 4 3 4
4 2 1 2 5
5 0 0 2 4
6 0 2 1 5
7 1 3 0 5
8 0 0 1 6
9 1 3 1 6
10 3 0 2 6
11 2 1 0 3
12 1 3 1 2
13 2 1 3 5
14 0 1 0 8
15 0 3 1 4
16 1 0 3 2
17 3 1 3 2
18 0 4 1 9
19 1 2 3 9
20 3 2 0 9
Creating linear model for Response with interaction between v1, v2, and v3 −
Model2<-lm(Response~v1:v2+v2:v3+v1:v3+v1:v2:v3,data=df2)
summary(Model2)
Call −
lm(formula = Response ~ v1:v2 + v2:v3 + v1:v3 + v1:v2:v3, data = df2)
Residuals −
Min 1Q Median 3Q Max
-4.3677 -1.7339 -0.0289 1.7127 4.0160
Coefficients −
Estimate Std. Error t value Pr(>|t|)
(Intercept) 3.98404 1.21641 3.275 0.00511 **
v1:v2 0.31934 0.44221 0.722 0.48131
v2:v3 0.83716 0.46012 1.819 0.08886 .
v1:v3 0.02783 0.30125 0.092 0.92762
v1:v2:v3 -0.37123 0.28280 -1.313 0.20901
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 2.609 on 15 degrees of freedom
Multiple R-squared: 0.1907, Adjusted R-squared: -0.02517
F-statistic: 0.8834 on 4 and 15 DF, p-value: 0.4973 | [
{
"code": null,
"e": 1390,
"s": 1062,
"text": "To create a linear model with interaction term only, we can use the interaction variable while creating the model. For example, if we have a data frame called df that has two independent variables say V1 and V2 and one dependent variable Y then the linear model with interaction term only can be created as lm(Y~V1:V2,data=df)."
},
{
"code": null,
"e": 1422,
"s": 1390,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1433,
"s": 1422,
"text": " Live Demo"
},
{
"code": null,
"e": 1524,
"s": 1433,
"text": "x1<-rnorm(20,5,1.2)\nx2<-rnorm(20,2,1.2)\ny1<-rnorm(20,3,1.25)\ndf1<-data.frame(x1,x2,y1)\ndf1"
},
{
"code": null,
"e": 2244,
"s": 1524,
"text": " x1 x2 y1\n1 4.442636 2.63714281 0.9120181\n2 5.912804 1.72409663 2.2746513\n3 7.881736 3.48780844 3.2675991\n4 6.145395 1.51225991 3.2177194\n5 6.303181 4.34733534 3.3361897\n6 5.689431 0.08564247 2.0863346\n7 6.008397 1.30221198 2.7183725\n8 6.580716 1.45239970 4.0301650\n9 4.000381 3.71539569 3.9404225\n10 5.535338 3.48976926 4.9557343\n11 5.968661 2.18208048 3.9992293\n12 4.783326 -0.90756376 4.2661775\n13 3.843528 -0.50299042 0.6496255\n14 6.034803 1.06019093 5.2339701\n15 4.177977 1.70476660 2.5932408\n16 5.746300 0.85021792 3.0145627\n17 4.658000 1.49894326 5.2826538\n18 3.797983 0.46900834 3.6511403\n19 5.415130 -0.31811078 2.6574529\n20 4.709443 2.72001915 1.8893078"
},
{
"code": null,
"e": 2310,
"s": 2244,
"text": "Creating linear model for y1 with interaction between x1 and x2 −"
},
{
"code": null,
"e": 2356,
"s": 2310,
"text": "Model1<-lm(y1~x1:x2,data=df1)\nsummary(Model1)"
},
{
"code": null,
"e": 2363,
"s": 2356,
"text": "Call −"
},
{
"code": null,
"e": 2400,
"s": 2363,
"text": "lm(formula = y1 ~ x1:x2, data = df1)"
},
{
"code": null,
"e": 2412,
"s": 2400,
"text": "Residuals −"
},
{
"code": null,
"e": 2471,
"s": 2412,
"text": "Min 1Q Median 3Q Max\n-2.3517 -0.6387 -0.1708 0.7321 2.1390"
},
{
"code": null,
"e": 2486,
"s": 2471,
"text": "Coefficients −"
},
{
"code": null,
"e": 2669,
"s": 2486,
"text": "Estimate Std. Error t value Pr(>|t|)\n(Intercept) 2.96669 0.42803 6.931 1.77e-06 ***\nx1:x2 0.02535 0.03434 0.738 0.47\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1"
},
{
"code": null,
"e": 2834,
"s": 2669,
"text": "Residual standard error: 1.299 on 18 degrees of freedom\nMultiple R-squared: 0.02939, Adjusted R-squared: -0.02454\nF-statistic: 0.545 on 1 and 18 DF, p-value: 0.4699"
},
{
"code": null,
"e": 2845,
"s": 2834,
"text": " Live Demo"
},
{
"code": null,
"e": 2954,
"s": 2845,
"text": "v1<-rpois(20,2)\nv2<-rpois(20,2)\nv3<-rpois(20,2)\nResponse<-rpois(20,5)\ndf2<-data.frame(v1,v2,v3,Response)\ndf2"
},
{
"code": null,
"e": 3235,
"s": 2954,
"text": " v1 v2 v3 Response\n1 2 2 4 10\n2 1 1 2 2\n3 3 4 3 4\n4 2 1 2 5\n5 0 0 2 4\n6 0 2 1 5\n7 1 3 0 5\n8 0 0 1 6\n9 1 3 1 6\n10 3 0 2 6\n11 2 1 0 3\n12 1 3 1 2\n13 2 1 3 5\n14 0 1 0 8\n15 0 3 1 4\n16 1 0 3 2\n17 3 1 3 2\n18 0 4 1 9\n19 1 2 3 9\n20 3 2 0 9"
},
{
"code": null,
"e": 3312,
"s": 3235,
"text": "Creating linear model for Response with interaction between v1, v2, and v3 −"
},
{
"code": null,
"e": 3385,
"s": 3312,
"text": "Model2<-lm(Response~v1:v2+v2:v3+v1:v3+v1:v2:v3,data=df2)\nsummary(Model2)"
},
{
"code": null,
"e": 3392,
"s": 3385,
"text": "Call −"
},
{
"code": null,
"e": 3462,
"s": 3392,
"text": "lm(formula = Response ~ v1:v2 + v2:v3 + v1:v3 + v1:v2:v3, data = df2)"
},
{
"code": null,
"e": 3474,
"s": 3462,
"text": "Residuals −"
},
{
"code": null,
"e": 3533,
"s": 3474,
"text": "Min 1Q Median 3Q Max\n-4.3677 -1.7339 -0.0289 1.7127 4.0160"
},
{
"code": null,
"e": 3548,
"s": 3533,
"text": "Coefficients −"
},
{
"code": null,
"e": 3847,
"s": 3548,
"text": "Estimate Std. Error t value Pr(>|t|)\n(Intercept) 3.98404 1.21641 3.275 0.00511 **\nv1:v2 0.31934 0.44221 0.722 0.48131\nv2:v3 0.83716 0.46012 1.819 0.08886 .\nv1:v3 0.02783 0.30125 0.092 0.92762\nv1:v2:v3 -0.37123 0.28280 -1.313 0.20901\n---\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1"
},
{
"code": null,
"e": 4012,
"s": 3847,
"text": "Residual standard error: 2.609 on 15 degrees of freedom\nMultiple R-squared: 0.1907, Adjusted R-squared: -0.02517\nF-statistic: 0.8834 on 4 and 15 DF, p-value: 0.4973"
}
]
|
Using Tensorflow Lite for Object Detection | Towards Data Science | Tensorflow has recently released its object detection API for Tensorflow 2 which has a very large model zoo. However, they have only provided one MobileNet v1 SSD model with Tensorflow lite which is described here. In that blog post, they have provided codes to run it on Android and IOS devices but not for edge devices. With the increase in popularity of edge devices and the release of spatial AI kits by OpenCV, I wanted to fill the missing gap. So that’s exactly what we are going to see here.
This does not require the installation of the Tensorflow Object Detection API to run. A simple Tensorflow installation, along with OpenCV for image processing is enough to run it.
pip install tensorflowpip install opencv
I have used some code provided in the Object Detection API to make the work easier, but there is no need to worry about it as does not require its explicit installation and you can find the whole code here.
The pre-trained model can be downloaded from Tensorflow’s blog from here or it is provided with the code as well.
Our first step to make the labels in the format required later on that is as a nested dictionary having id and label inside. We will use the label map text file provided with the model and convert it to the required format.
Note:- The labels with “???” need to be ignored and those indices are skipped except for the first one. So each label is shifted one place back. For example, the label “person” is on the first row but it will be assigned a label 0 and so on.
This can be found commented in its Java implementation.
// SSD Mobilenet V1 Model assumes class 0 is background class
// in label file and class labels start from 1 to number_of_classes+1,
// while outputClasses correspond to class index from 0 to number_of_classes
This can be done with the following code:
def create_category_index(label_path='path_to/labelmap.txt'): f = open(label_path) category_index = {} for i, val in enumerate(f): if i != 0: val = val[:-1] if val != '???': category_index.update({(i-1): {'id': (i-1), 'name': val}}) f.close() return category_index
Here, to ignore the first line, I am using an if statement and storing i-1. This creates a dictionary as shown below.
It will have 80 rows with keys going to 89.
With labels done, let’s understand TfLite’s interpreter and how we can get the results.
import tensorflow as tfinterpreter = tf.lite.Interpreter(model_path="path/detect.tflite")interpreter.allocate_tensors()
Just load the correct model path of your tflite model and allocate tensors.
To get input and output details, write:
input_details = interpreter.get_input_details()output_details = interpreter.get_output_details()
Now, let’s study them to see what type of inputs to give and the outputs we will get.
The input details are a list of only 1 element which is a dictionary as shown below.
Here, we can see the input shape to be [1, 300, 300, 3]. Other than this it requires the input image to have a datatype of np.uint8.
The output details are a list of 4 elements, each containing a dictionary like the input details. Each call returns 10 results with the first item storing the rectangle bounding boxes, the second item the detection classes, the third item the detection scores, and finally the last item the number of detections returned. The bounding boxes returned are normalized so they can be scaled to any input dimension.
To get the outputs we need to read the image, convert it to RGB if OpenCV is used, resize it appropriately, and invoke the interpreter after setting the tensor with the input frame. Then the required values can be achieved using the get_tensor function of the interpreter.
import cv2img = cv2.imread('image.jpg')img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)img_rgb = cv2.resize(img_rgb, (300, 300), cv2.INTER_AREA)img_rgb = img_rgb.reshape([1, 300, 300, 3])interpreter.set_tensor(input_details[0]['index'], img_rgb)interpreter.invoke()de_boxes = interpreter.get_tensor(output_details[0]['index'])[0]det_classes = interpreter.get_tensor(output_details[1]['index'])[0]det_scores = interpreter.get_tensor(output_details[2]['index'])[0]num_det = interpreter.get_tensor(output_details[3]['index'])[0]
For visualization, I used the python code available here, which not only can be used to draw bounding boxes but also keypoints and instance masks if required. We need to pass the image to draw on, bounding boxes, detected classes, detection scores, and the labels dictionary. Other than that we also set the normalized coordinates to true as we receive normalized bounding box coordinates from the interpreter.
from object_detection.utils import visualization_utils as vis_utilvis_util.visualize_boxes_and_labels_on_image_array( img, output_dict['detection_boxes'], output_dict['detection_classes'], output_dict['detection_scores'], category_index, use_normalized_coordinates=True, min_score_thresh=0.6, line_thickness=3)
It will give the results something like shown below.
However, there is still one problem to address as shown below.
This can be done via non-maximum suppression.
I am not going to explain it as it has already been covered in-depth across various articles throughout the internet. One such example is this article. To implement it, I am going to use combined_non_max_suppression Tensorflow Image to perform this task as it allows us to work with multiple classes at once. It takes the outputs and returns the predictions left after the threshold.
def apply_nms(output_dict, iou_thresh=0.5, score_thresh=0.6):q = 90 # no of classes num = int(output_dict['num_detections']) boxes = np.zeros([1, num, q, 4]) scores = np.zeros([1, num, q]) # val = [0]*q for i in range(num): # indices = np.where(classes == output_dict['detection_classes'][i])[0][0] boxes[0, i, output_dict['detection_classes'][i], :] = output_dict['detection_boxes'][i] scores[0, i, output_dict['detection_classes'][i]] = output_dict['detection_scores'][i] nmsd = tf.image.combined_non_max_suppression( boxes=boxes, scores=scores, max_output_size_per_class=num, max_total_size=num, iou_threshold=iou_thresh, score_threshold=score_thresh, pad_per_class=False, clip_boxes=False) valid = nmsd.valid_detections[0].numpy() output_dict = { 'detection_boxes' : nmsd.nmsed_boxes[0].numpy()[:valid], 'detection_classes' : nmsd.nmsed_classes[0].numpy().astype(np.int64)[:valid], 'detection_scores' : nmsd.nmsed_scores[0].numpy()[:valid], } return output_dict
The full code is given below and or you visit my Github repo which also contains visualization_utils.py and models.
Before ending, I would like to clear up a thing, that if you try to run it on Windows with an Intel processor, you will get a terrible fps. I got ~2 on an i5 and for comparison, the same Tensorflow model without tflite gave me ~8 fps. This is explained here. However, on edge devices that won’t be a problem, and it’s considerably less memory footprint would benefit their memory limitations.
Although this model is not very accurate, I hope I would have provided a boilerplate to make your task easier when using an Object detector if Tflite. | [
{
"code": null,
"e": 671,
"s": 172,
"text": "Tensorflow has recently released its object detection API for Tensorflow 2 which has a very large model zoo. However, they have only provided one MobileNet v1 SSD model with Tensorflow lite which is described here. In that blog post, they have provided codes to run it on Android and IOS devices but not for edge devices. With the increase in popularity of edge devices and the release of spatial AI kits by OpenCV, I wanted to fill the missing gap. So that’s exactly what we are going to see here."
},
{
"code": null,
"e": 851,
"s": 671,
"text": "This does not require the installation of the Tensorflow Object Detection API to run. A simple Tensorflow installation, along with OpenCV for image processing is enough to run it."
},
{
"code": null,
"e": 892,
"s": 851,
"text": "pip install tensorflowpip install opencv"
},
{
"code": null,
"e": 1099,
"s": 892,
"text": "I have used some code provided in the Object Detection API to make the work easier, but there is no need to worry about it as does not require its explicit installation and you can find the whole code here."
},
{
"code": null,
"e": 1213,
"s": 1099,
"text": "The pre-trained model can be downloaded from Tensorflow’s blog from here or it is provided with the code as well."
},
{
"code": null,
"e": 1437,
"s": 1213,
"text": "Our first step to make the labels in the format required later on that is as a nested dictionary having id and label inside. We will use the label map text file provided with the model and convert it to the required format."
},
{
"code": null,
"e": 1679,
"s": 1437,
"text": "Note:- The labels with “???” need to be ignored and those indices are skipped except for the first one. So each label is shifted one place back. For example, the label “person” is on the first row but it will be assigned a label 0 and so on."
},
{
"code": null,
"e": 1735,
"s": 1679,
"text": "This can be found commented in its Java implementation."
},
{
"code": null,
"e": 1797,
"s": 1735,
"text": "// SSD Mobilenet V1 Model assumes class 0 is background class"
},
{
"code": null,
"e": 1868,
"s": 1797,
"text": "// in label file and class labels start from 1 to number_of_classes+1,"
},
{
"code": null,
"e": 1945,
"s": 1868,
"text": "// while outputClasses correspond to class index from 0 to number_of_classes"
},
{
"code": null,
"e": 1987,
"s": 1945,
"text": "This can be done with the following code:"
},
{
"code": null,
"e": 2323,
"s": 1987,
"text": "def create_category_index(label_path='path_to/labelmap.txt'): f = open(label_path) category_index = {} for i, val in enumerate(f): if i != 0: val = val[:-1] if val != '???': category_index.update({(i-1): {'id': (i-1), 'name': val}}) f.close() return category_index"
},
{
"code": null,
"e": 2441,
"s": 2323,
"text": "Here, to ignore the first line, I am using an if statement and storing i-1. This creates a dictionary as shown below."
},
{
"code": null,
"e": 2485,
"s": 2441,
"text": "It will have 80 rows with keys going to 89."
},
{
"code": null,
"e": 2573,
"s": 2485,
"text": "With labels done, let’s understand TfLite’s interpreter and how we can get the results."
},
{
"code": null,
"e": 2693,
"s": 2573,
"text": "import tensorflow as tfinterpreter = tf.lite.Interpreter(model_path=\"path/detect.tflite\")interpreter.allocate_tensors()"
},
{
"code": null,
"e": 2769,
"s": 2693,
"text": "Just load the correct model path of your tflite model and allocate tensors."
},
{
"code": null,
"e": 2809,
"s": 2769,
"text": "To get input and output details, write:"
},
{
"code": null,
"e": 2906,
"s": 2809,
"text": "input_details = interpreter.get_input_details()output_details = interpreter.get_output_details()"
},
{
"code": null,
"e": 2992,
"s": 2906,
"text": "Now, let’s study them to see what type of inputs to give and the outputs we will get."
},
{
"code": null,
"e": 3077,
"s": 2992,
"text": "The input details are a list of only 1 element which is a dictionary as shown below."
},
{
"code": null,
"e": 3210,
"s": 3077,
"text": "Here, we can see the input shape to be [1, 300, 300, 3]. Other than this it requires the input image to have a datatype of np.uint8."
},
{
"code": null,
"e": 3621,
"s": 3210,
"text": "The output details are a list of 4 elements, each containing a dictionary like the input details. Each call returns 10 results with the first item storing the rectangle bounding boxes, the second item the detection classes, the third item the detection scores, and finally the last item the number of detections returned. The bounding boxes returned are normalized so they can be scaled to any input dimension."
},
{
"code": null,
"e": 3894,
"s": 3621,
"text": "To get the outputs we need to read the image, convert it to RGB if OpenCV is used, resize it appropriately, and invoke the interpreter after setting the tensor with the input frame. Then the required values can be achieved using the get_tensor function of the interpreter."
},
{
"code": null,
"e": 4418,
"s": 3894,
"text": "import cv2img = cv2.imread('image.jpg')img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)img_rgb = cv2.resize(img_rgb, (300, 300), cv2.INTER_AREA)img_rgb = img_rgb.reshape([1, 300, 300, 3])interpreter.set_tensor(input_details[0]['index'], img_rgb)interpreter.invoke()de_boxes = interpreter.get_tensor(output_details[0]['index'])[0]det_classes = interpreter.get_tensor(output_details[1]['index'])[0]det_scores = interpreter.get_tensor(output_details[2]['index'])[0]num_det = interpreter.get_tensor(output_details[3]['index'])[0]"
},
{
"code": null,
"e": 4829,
"s": 4418,
"text": "For visualization, I used the python code available here, which not only can be used to draw bounding boxes but also keypoints and instance masks if required. We need to pass the image to draw on, bounding boxes, detected classes, detection scores, and the labels dictionary. Other than that we also set the normalized coordinates to true as we receive normalized bounding box coordinates from the interpreter."
},
{
"code": null,
"e": 5164,
"s": 4829,
"text": "from object_detection.utils import visualization_utils as vis_utilvis_util.visualize_boxes_and_labels_on_image_array( img, output_dict['detection_boxes'], output_dict['detection_classes'], output_dict['detection_scores'], category_index, use_normalized_coordinates=True, min_score_thresh=0.6, line_thickness=3)"
},
{
"code": null,
"e": 5217,
"s": 5164,
"text": "It will give the results something like shown below."
},
{
"code": null,
"e": 5280,
"s": 5217,
"text": "However, there is still one problem to address as shown below."
},
{
"code": null,
"e": 5326,
"s": 5280,
"text": "This can be done via non-maximum suppression."
},
{
"code": null,
"e": 5710,
"s": 5326,
"text": "I am not going to explain it as it has already been covered in-depth across various articles throughout the internet. One such example is this article. To implement it, I am going to use combined_non_max_suppression Tensorflow Image to perform this task as it allows us to work with multiple classes at once. It takes the outputs and returns the predictions left after the threshold."
},
{
"code": null,
"e": 6872,
"s": 5710,
"text": "def apply_nms(output_dict, iou_thresh=0.5, score_thresh=0.6):q = 90 # no of classes num = int(output_dict['num_detections']) boxes = np.zeros([1, num, q, 4]) scores = np.zeros([1, num, q]) # val = [0]*q for i in range(num): # indices = np.where(classes == output_dict['detection_classes'][i])[0][0] boxes[0, i, output_dict['detection_classes'][i], :] = output_dict['detection_boxes'][i] scores[0, i, output_dict['detection_classes'][i]] = output_dict['detection_scores'][i] nmsd = tf.image.combined_non_max_suppression( boxes=boxes, scores=scores, max_output_size_per_class=num, max_total_size=num, iou_threshold=iou_thresh, score_threshold=score_thresh, pad_per_class=False, clip_boxes=False) valid = nmsd.valid_detections[0].numpy() output_dict = { 'detection_boxes' : nmsd.nmsed_boxes[0].numpy()[:valid], 'detection_classes' : nmsd.nmsed_classes[0].numpy().astype(np.int64)[:valid], 'detection_scores' : nmsd.nmsed_scores[0].numpy()[:valid], } return output_dict"
},
{
"code": null,
"e": 6988,
"s": 6872,
"text": "The full code is given below and or you visit my Github repo which also contains visualization_utils.py and models."
},
{
"code": null,
"e": 7381,
"s": 6988,
"text": "Before ending, I would like to clear up a thing, that if you try to run it on Windows with an Intel processor, you will get a terrible fps. I got ~2 on an i5 and for comparison, the same Tensorflow model without tflite gave me ~8 fps. This is explained here. However, on edge devices that won’t be a problem, and it’s considerably less memory footprint would benefit their memory limitations."
}
]
|
\hskip - Tex Command | \hskip - Used to create horizontal space.
{ \hskip }
\hskip command draws horizontal space.
w\hskip1em i\hskip2em d\hskip3em e\hskip4em r
wider
w\hskip1em i\hskip2em d\hskip3em e\hskip4em r
wider
w\hskip1em i\hskip2em d\hskip3em e\hskip4em r
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 8028,
"s": 7986,
"text": "\\hskip - Used to create horizontal space."
},
{
"code": null,
"e": 8039,
"s": 8028,
"text": "{ \\hskip }"
},
{
"code": null,
"e": 8078,
"s": 8039,
"text": "\\hskip command draws horizontal space."
},
{
"code": null,
"e": 8135,
"s": 8078,
"text": "\nw\\hskip1em i\\hskip2em d\\hskip3em e\\hskip4em r\n\nwider\n\n\n"
},
{
"code": null,
"e": 8190,
"s": 8135,
"text": "w\\hskip1em i\\hskip2em d\\hskip3em e\\hskip4em r\n\nwider\n\n"
},
{
"code": null,
"e": 8236,
"s": 8190,
"text": "w\\hskip1em i\\hskip2em d\\hskip3em e\\hskip4em r"
},
{
"code": null,
"e": 8268,
"s": 8236,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8281,
"s": 8268,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8314,
"s": 8281,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8327,
"s": 8314,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8359,
"s": 8327,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8395,
"s": 8359,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8430,
"s": 8395,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8447,
"s": 8430,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8480,
"s": 8447,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8494,
"s": 8480,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8526,
"s": 8494,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8541,
"s": 8526,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8548,
"s": 8541,
"text": " Print"
},
{
"code": null,
"e": 8559,
"s": 8548,
"text": " Add Notes"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.